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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -36,23 +36,23 @@
*/
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
public static int FILTER = 8;
@Deprecated
public static int FILTER = 8;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -33,9 +33,9 @@
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.spatial.SpatialDialect;
import org.hibernate.spatial.SpatialFunction;
import org.hibernate.type.StandardBasicTypes;
/**
* @author Karel Maesen, Geovise BVBA
@ -43,24 +43,24 @@
*/
public class HavingSridExpression implements Criterion {
private final String propertyName;
private final int srid;
private final String propertyName;
private final int srid;
public HavingSridExpression(String propertyName, int srid) {
this.propertyName = propertyName;
this.srid = srid;
}
public HavingSridExpression(String propertyName, int srid) {
this.propertyName = propertyName;
this.srid = srid;
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn(propertyName, criteria, criteriaQuery);
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect(criteriaQuery, SpatialFunction.srid);
return spatialDialect.getHavingSridSQL(column);
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn( propertyName, criteria, criteriaQuery );
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect( criteriaQuery, SpatialFunction.srid );
return spatialDialect.getHavingSridSQL( column );
}
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[]{
new TypedValue(StandardBasicTypes.INTEGER, Integer.valueOf(srid), EntityMode.POJO)
};
}
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] {
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
* hibernate ORM solution for geographic data.
@ -42,24 +41,24 @@
*/
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 boolean isEmpty;
private final String propertyName;
private final boolean isEmpty;
public IsEmptyExpression(String propertyName, boolean isEmpty) {
this.propertyName = propertyName;
this.isEmpty = isEmpty;
}
public IsEmptyExpression(String propertyName, boolean isEmpty) {
this.propertyName = propertyName;
this.isEmpty = isEmpty;
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn(propertyName, criteria, criteriaQuery);
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect(criteriaQuery, SpatialFunction.isempty);
return spatialDialect.getIsEmptySQL(column, isEmpty);
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn( propertyName, criteria, criteriaQuery );
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect( criteriaQuery, SpatialFunction.isempty );
return spatialDialect.getIsEmptySQL( column, isEmpty );
}
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return NO_VALUES;
}
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return NO_VALUES;
}
}

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* 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.Geometry;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
@ -44,7 +45,7 @@
* An implementation for a simple spatial filter. This <code>Criterion</code>
* restricts the resultset to those features whose bounding box overlaps the
* filter geometry. It is intended for quick, but inexact spatial queries.
*
*
* @author Karel Maesen
*/
public class SpatialFilter implements Criterion {
@ -62,28 +63,37 @@ public SpatialFilter(String propertyName, Geometry filter) {
public SpatialFilter(String propertyName, Envelope envelope, int SRID) {
this.propertyName = propertyName;
this.filter = EnvelopeAdapter.toPolygon(envelope, SRID);
this.filter = EnvelopeAdapter.toPolygon( envelope, SRID );
}
public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] { criteriaQuery.getTypedValue(criteria,
propertyName, filter) };
CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] {
criteriaQuery.getTypedValue(
criteria,
propertyName, filter
)
};
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
this.propertyName);
String[] columns = criteriaQuery.getColumnsUsingProjection(
criteria,
this.propertyName
);
Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) {
if ( dialect instanceof SpatialDialect ) {
SpatialDialect seDialect = (SpatialDialect) dialect;
return seDialect.getSpatialFilterExpression(columns[0]);
} else
return seDialect.getSpatialFilterExpression( columns[0] );
}
else {
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
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
*
* This work was partially supported by the European Commission,
@ -40,7 +40,6 @@
/**
* @author Karel Maesen
*
*/
public class SpatialProjections {
@ -48,25 +47,34 @@ public static Projection extent(final String propertyName) {
return new SimpleProjection() {
public Type[] getTypes(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
return new Type[] { criteriaQuery.getType(criteria,
propertyName) };
CriteriaQuery criteriaQuery) throws HibernateException {
return new Type[] {
criteriaQuery.getType(
criteria,
propertyName
)
};
}
public String toSqlString(Criteria criteria, int position,
CriteriaQuery criteriaQuery) throws HibernateException {
CriteriaQuery criteriaQuery) throws HibernateException {
StringBuilder stbuf = new StringBuilder();
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(
criteria, propertyName);
criteria, propertyName
);
Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) {
if ( dialect instanceof SpatialDialect ) {
SpatialDialect seDialect = (SpatialDialect) dialect;
stbuf.append(seDialect.getSpatialAggregateSQL(columns[0],
SpatialAggregate.EXTENT));
stbuf.append(" as y").append(position).append('_');
stbuf.append(
seDialect.getSpatialAggregateSQL(
columns[0],
SpatialAggregate.EXTENT
)
);
stbuf.append( " as y" ).append( position ).append( '_' );
return stbuf.toString();
}
return null;

View File

@ -29,6 +29,7 @@
package org.hibernate.spatial.criterion;
import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
@ -47,65 +48,75 @@
*/
public class SpatialRelateExpression implements Criterion {
/**
* The geometry property
*/
private String propertyName = null;
/**
* The geometry property
*/
private String propertyName = null;
/**
* The test geometry
*/
private Geometry value = null;
/**
* The test geometry
*/
private Geometry value = null;
/**
* The spatial relation that is queried for.
*/
private int spatialRelation = -1;
/**
* The spatial relation that is queried for.
*/
private int spatialRelation = -1;
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public SpatialRelateExpression(String propertyName,
Geometry value, int spatialRelation) {
this.propertyName = propertyName;
this.spatialRelation = spatialRelation;
this.value = value;
}
public SpatialRelateExpression(String propertyName,
Geometry value, int spatialRelation) {
this.propertyName = propertyName;
this.spatialRelation = spatialRelation;
this.value = value;
}
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[]{criteriaQuery.getTypedValue(criteria,
propertyName, value)};
public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] {
criteriaQuery.getTypedValue(
criteria,
propertyName, value
)
};
}
}
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
this.propertyName);
Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) {
SpatialDialect seDialect = (SpatialDialect) dialect;
return seDialect.getSpatialRelateSQL(columns[0],
spatialRelation);
} else {
throw new IllegalStateException(
"Dialect must be spatially enabled dialect");
}
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(
criteria,
this.propertyName
);
Dialect dialect = factory.getDialect();
if ( dialect instanceof SpatialDialect ) {
SpatialDialect seDialect = (SpatialDialect) dialect;
return seDialect.getSpatialRelateSQL(
columns[0],
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.Geometry;
import org.hibernate.criterion.Criterion;
import org.hibernate.spatial.SpatialRelation;
@ -50,100 +51,117 @@
*/
public class SpatialRestrictions {
SpatialRestrictions() {
}
SpatialRestrictions() {
}
public static SpatialRelateExpression eq(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.EQUALS);
}
public static SpatialRelateExpression eq(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.EQUALS
);
}
public static SpatialRelateExpression within(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.WITHIN);
}
public static SpatialRelateExpression within(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.WITHIN
);
}
public static SpatialRelateExpression contains(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.CONTAINS);
}
public static SpatialRelateExpression contains(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.CONTAINS
);
}
public static SpatialRelateExpression crosses(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.CROSSES);
}
public static SpatialRelateExpression crosses(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.CROSSES
);
}
public static SpatialRelateExpression disjoint(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.DISJOINT);
}
public static SpatialRelateExpression disjoint(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.DISJOINT
);
}
public static SpatialRelateExpression intersects(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.INTERSECTS);
}
public static SpatialRelateExpression intersects(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.INTERSECTS
);
}
public static SpatialRelateExpression overlaps(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.OVERLAPS);
}
public static SpatialRelateExpression overlaps(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.OVERLAPS
);
}
public static SpatialRelateExpression touches(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value,
SpatialRelation.TOUCHES);
}
public static SpatialRelateExpression touches(String propertyName, Geometry value) {
return new SpatialRelateExpression(
propertyName, value,
SpatialRelation.TOUCHES
);
}
public static SpatialFilter filter(String propertyName, Geometry filter) {
return new SpatialFilter(propertyName, filter);
}
public static SpatialFilter filter(String propertyName, Geometry filter) {
return new SpatialFilter( propertyName, filter );
}
public static SpatialFilter filter(String propertyName, Envelope envelope,
int SRID) {
return new SpatialFilter(propertyName, envelope, SRID);
}
public static SpatialFilter filter(String propertyName, Envelope envelope,
int SRID) {
return new SpatialFilter( propertyName, envelope, SRID );
}
public static Criterion distanceWithin(String propertyName, Geometry geometry, double distance) {
return new DWithinExpression(propertyName, geometry, distance);
}
public static Criterion distanceWithin(String propertyName, Geometry geometry, double distance) {
return new DWithinExpression( propertyName, geometry, distance );
}
public static Criterion havingSRID(String propertyName, int srid) {
return new HavingSridExpression(propertyName, srid);
}
public static Criterion havingSRID(String propertyName, int srid) {
return new HavingSridExpression( propertyName, srid );
}
public static Criterion isEmpty(String propertyName) {
return new IsEmptyExpression(propertyName, true);
}
public static Criterion isEmpty(String propertyName) {
return new IsEmptyExpression( propertyName, true );
}
public static Criterion isNotEmpty(String propertyName) {
return new IsEmptyExpression(propertyName, false);
}
public static Criterion isNotEmpty(String propertyName) {
return new IsEmptyExpression( propertyName, false );
}
public static Criterion spatialRestriction(int relation,
String propertyName, Geometry value) {
switch (relation) {
case SpatialRelation.CONTAINS:
return contains(propertyName, value);
case SpatialRelation.CROSSES:
return crosses(propertyName, value);
case SpatialRelation.DISJOINT:
return disjoint(propertyName, value);
case SpatialRelation.INTERSECTS:
return intersects(propertyName, value);
case SpatialRelation.EQUALS:
return eq(propertyName, value);
case SpatialRelation.FILTER:
return filter(propertyName, value);
case SpatialRelation.OVERLAPS:
return overlaps(propertyName, value);
case SpatialRelation.TOUCHES:
return touches(propertyName, value);
case SpatialRelation.WITHIN:
return within(propertyName, value);
default:
throw new IllegalArgumentException(
"Non-existant spatial relation passed.");
}
}
public static Criterion spatialRestriction(int relation,
String propertyName, Geometry value) {
switch ( relation ) {
case SpatialRelation.CONTAINS:
return contains( propertyName, value );
case SpatialRelation.CROSSES:
return crosses( propertyName, value );
case SpatialRelation.DISJOINT:
return disjoint( propertyName, value );
case SpatialRelation.INTERSECTS:
return intersects( propertyName, value );
case SpatialRelation.EQUALS:
return eq( propertyName, value );
case SpatialRelation.FILTER:
return filter( propertyName, value );
case SpatialRelation.OVERLAPS:
return overlaps( propertyName, value );
case SpatialRelation.TOUCHES:
return touches( propertyName, value );
case SpatialRelation.WITHIN:
return within( propertyName, value );
default:
throw new IllegalArgumentException(
"Non-existant spatial relation passed."
);
}
}
}

View File

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

View File

@ -1,239 +1,289 @@
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.PreparedStatement;
import java.sql.SQLException;
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
* creation-date: 7/27/11
*/
public class PGGeometryValueBinder implements ValueBinder {
public class PGGeometryValueBinder implements ValueBinder<Geometry> {
@Override
public void bind(PreparedStatement st, Object value, int index, WrapperOptions options) throws SQLException {
if (value == null) {
st.setNull(index, Types.STRUCT);
} else {
Geometry jtsGeom = (Geometry) value;
Object dbGeom = toJTS(jtsGeom, st.getConnection());
st.setObject(index, dbGeom);
@Override
public void bind(PreparedStatement st, Geometry value, int index, WrapperOptions options) throws SQLException {
if ( value == null ) {
st.setNull( index, Types.STRUCT );
}
}
else {
Geometry jtsGeom = (Geometry) value;
Object dbGeom = toNative( jtsGeom, st.getConnection() );
st.setObject( index, dbGeom );
}
}
public MGeometryFactory getGeometryFactory(){
public MGeometryFactory getGeometryFactory() {
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 );
}
/**
* 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.
*/
public Object toJTS(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 ) {
return new PGgeometry( geom );
}
else {
throw new UnsupportedOperationException(
"Conversion of "
+ jtsGeom.getClass().getSimpleName()
+ " to PGgeometry not supported"
);
}
}
if (geom != null)
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
//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) {
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 MultiPolygon convertJTSMultiPolygon(
com.vividsolutions.jts.geom.MultiPolygon multiPolygon) {
Polygon[] pgPolygons = new Polygon[multiPolygon.getNumGeometries()];
for ( int i = 0; i < pgPolygons.length; i++ ) {
pgPolygons[i] = convertJTSPolygon(
(com.vividsolutions.jts.geom.Polygon) multiPolygon
.getGeometryN( i )
);
}
MultiPolygon mpg = new MultiPolygon( pgPolygons );
mpg.setSrid( multiPolygon.getSRID() );
return mpg;
}
private MultiPolygon convertJTSMultiPolygon(
com.vividsolutions.jts.geom.MultiPolygon multiPolygon) {
Polygon[] pgPolygons = new Polygon[multiPolygon.getNumGeometries()];
for (int i = 0; i < pgPolygons.length; i++) {
pgPolygons[i] = convertJTSPolygon((com.vividsolutions.jts.geom.Polygon) multiPolygon
.getGeometryN(i));
}
MultiPolygon mpg = new MultiPolygon(pgPolygons);
mpg.setSrid(multiPolygon.getSRID());
return mpg;
}
private MultiPoint convertJTSMultiPoint(
com.vividsolutions.jts.geom.MultiPoint multiPoint) {
Point[] pgPoints = new Point[multiPoint.getNumGeometries()];
for ( int i = 0; i < pgPoints.length; i++ ) {
pgPoints[i] = convertJTSPoint(
(com.vividsolutions.jts.geom.Point) multiPoint
.getGeometryN( i )
);
}
MultiPoint mp = new MultiPoint( pgPoints );
mp.setSrid( multiPoint.getSRID() );
return mp;
}
private MultiPoint convertJTSMultiPoint(
com.vividsolutions.jts.geom.MultiPoint multiPoint) {
Point[] pgPoints = new Point[multiPoint.getNumGeometries()];
for (int i = 0; i < pgPoints.length; i++) {
pgPoints[i] = convertJTSPoint((com.vividsolutions.jts.geom.Point) multiPoint
.getGeometryN(i));
}
MultiPoint mp = new MultiPoint(pgPoints);
mp.setSrid(multiPoint.getSRID());
return mp;
}
private Polygon convertJTSPolygon(
com.vividsolutions.jts.geom.Polygon jtsPolygon) {
int numRings = jtsPolygon.getNumInteriorRing();
org.postgis.LinearRing[] rings = new org.postgis.LinearRing[numRings + 1];
rings[0] = convertJTSLineStringToLinearRing(
jtsPolygon
.getExteriorRing()
);
for ( int i = 0; i < numRings; i++ ) {
rings[i + 1] = convertJTSLineStringToLinearRing(
jtsPolygon
.getInteriorRingN( i )
);
}
Polygon polygon = new org.postgis.Polygon( rings );
polygon.setSrid( jtsPolygon.getSRID() );
return polygon;
}
private Polygon convertJTSPolygon(
com.vividsolutions.jts.geom.Polygon jtsPolygon) {
int numRings = jtsPolygon.getNumInteriorRing();
org.postgis.LinearRing[] rings = new org.postgis.LinearRing[numRings + 1];
rings[0] = convertJTSLineStringToLinearRing(jtsPolygon
.getExteriorRing());
for (int i = 0; i < numRings; i++) {
rings[i + 1] = convertJTSLineStringToLinearRing(jtsPolygon
.getInteriorRingN(i));
}
Polygon polygon = new org.postgis.Polygon(rings);
polygon.setSrid(jtsPolygon.getSRID());
return polygon;
}
private LinearRing convertJTSLineStringToLinearRing(
com.vividsolutions.jts.geom.LineString lineString) {
LinearRing lr = new org.postgis.LinearRing(
toPoints(
lineString
.getCoordinates()
)
);
lr.setSrid( lineString.getSRID() );
return lr;
}
private LinearRing convertJTSLineStringToLinearRing(
com.vividsolutions.jts.geom.LineString lineString) {
LinearRing lr = new org.postgis.LinearRing(toPoints(lineString
.getCoordinates()));
lr.setSrid(lineString.getSRID());
return lr;
}
private LineString convertJTSLineString(
com.vividsolutions.jts.geom.LineString string) {
LineString ls = new org.postgis.LineString(
toPoints(
string
.getCoordinates()
)
);
if ( string instanceof MGeometry ) {
ls.haveMeasure = true;
}
ls.setSrid( string.getSRID() );
return ls;
}
private LineString convertJTSLineString(
com.vividsolutions.jts.geom.LineString string) {
LineString ls = new org.postgis.LineString(toPoints(string
.getCoordinates()));
if (string instanceof MGeometry) {
ls.haveMeasure = true;
}
ls.setSrid(string.getSRID());
return ls;
}
private MultiLineString convertJTSMultiLineString(
com.vividsolutions.jts.geom.MultiLineString string) {
org.postgis.LineString[] lines = new org.postgis.LineString[string
.getNumGeometries()];
for ( int i = 0; i < string.getNumGeometries(); i++ ) {
lines[i] = new org.postgis.LineString(
toPoints(
string.getGeometryN(
i
).getCoordinates()
)
);
}
MultiLineString mls = new MultiLineString( lines );
if ( string instanceof MGeometry ) {
mls.haveMeasure = true;
}
mls.setSrid( string.getSRID() );
return mls;
}
private MultiLineString convertJTSMultiLineString(
com.vividsolutions.jts.geom.MultiLineString string) {
org.postgis.LineString[] lines = new org.postgis.LineString[string
.getNumGeometries()];
for (int i = 0; i < string.getNumGeometries(); i++) {
lines[i] = new org.postgis.LineString(toPoints(string.getGeometryN(
i).getCoordinates()));
}
MultiLineString mls = new MultiLineString(lines);
if (string instanceof MGeometry) {
mls.haveMeasure = true;
}
mls.setSrid(string.getSRID());
return mls;
}
private Point convertJTSPoint(com.vividsolutions.jts.geom.Point point) {
org.postgis.Point pgPoint = new org.postgis.Point();
pgPoint.srid = point.getSRID();
pgPoint.x = point.getX();
pgPoint.y = point.getY();
Coordinate coordinate = point.getCoordinate();
if ( Double.isNaN( coordinate.z ) ) {
pgPoint.dimension = 2;
}
else {
pgPoint.z = coordinate.z;
pgPoint.dimension = 3;
}
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) {
org.postgis.Point pgPoint = new org.postgis.Point();
pgPoint.srid = point.getSRID();
pgPoint.x = point.getX();
pgPoint.y = point.getY();
Coordinate coordinate = point.getCoordinate();
if (Double.isNaN(coordinate.z)) {
pgPoint.dimension = 2;
} else {
pgPoint.z = coordinate.z;
pgPoint.dimension = 3;
}
pgPoint.haveMeasure = false;
if (coordinate instanceof MCoordinate && !Double.isNaN(((MCoordinate) coordinate).m)) {
pgPoint.m = ((MCoordinate) coordinate).m;
pgPoint.haveMeasure = true;
}
return pgPoint;
}
private GeometryCollection convertJTSGeometryCollection(
com.vividsolutions.jts.geom.GeometryCollection collection) {
com.vividsolutions.jts.geom.Geometry currentGeom;
org.postgis.Geometry[] pgCollections = new org.postgis.Geometry[collection
.getNumGeometries()];
for (int i = 0; i < pgCollections.length; i++) {
currentGeom = collection.getGeometryN(i);
currentGeom = forceEmptyToGeometryCollection(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.LinearRing.class) {
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);
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPoint.class) {
pgCollections[i] = convertJTSMultiPoint((com.vividsolutions.jts.geom.MultiPoint) currentGeom);
} 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 GeometryCollection convertJTSGeometryCollection(
com.vividsolutions.jts.geom.GeometryCollection collection) {
com.vividsolutions.jts.geom.Geometry currentGeom;
org.postgis.Geometry[] pgCollections = new org.postgis.Geometry[collection
.getNumGeometries()];
for ( int i = 0; i < pgCollections.length; i++ ) {
currentGeom = collection.getGeometryN( i );
currentGeom = forceEmptyToGeometryCollection( 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.LinearRing.class ) {
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 );
}
else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPoint.class ) {
pgCollections[i] = convertJTSMultiPoint( (com.vividsolutions.jts.geom.MultiPoint) currentGeom );
}
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) {
Point[] points = new Point[coordinates.length];
for (int i = 0; i < coordinates.length; i++) {
Coordinate c = coordinates[i];
Point pt;
if (Double.isNaN(c.z)) {
pt = new Point(c.x, c.y);
} else {
pt = new Point(c.x, c.y, c.z);
}
if (c instanceof MCoordinate) {
MCoordinate mc = (MCoordinate) c;
if (!Double.isNaN(mc.m)) {
pt.setM(mc.m);
}
}
points[i] = pt;
}
return points;
}
private Point[] toPoints(Coordinate[] coordinates) {
Point[] points = new Point[coordinates.length];
for ( int i = 0; i < coordinates.length; i++ ) {
Coordinate c = coordinates[i];
Point pt;
if ( Double.isNaN( c.z ) ) {
pt = new Point( c.x, c.y );
}
else {
pt = new Point( c.x, c.y, c.z );
}
if ( c instanceof MCoordinate ) {
MCoordinate mc = (MCoordinate) c;
if ( !Double.isNaN( mc.m ) ) {
pt.setM( mc.m );
}
}
points[i] = pt;
}
return points;
}
}

View File

@ -1,231 +1,274 @@
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.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.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.mgeom.MLineString;
import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions;
import org.postgis.*;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Karel Maesen, Geovise BVBA
* creation-date: 7/27/11
*/
public class PGGeometryValueExtractor implements ValueExtractor {
@Override
public Object extract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
Object geomObj = rs.getObject(name);
return toJTS(geomObj);
}
public class PGGeometryValueExtractor implements ValueExtractor<Geometry> {
public MGeometryFactory getGeometryFactory() {
return HBSpatialExtension.getDefaultGeomFactory();
}
@Override
public Geometry extract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
Object geomObj = rs.getObject( name );
return toJTS( geomObj );
}
public Geometry toJTS(Object object) {
if (object == null)
return null;
public MGeometryFactory getGeometryFactory() {
return HBSpatialExtension.getDefaultGeomFactory();
}
// in some cases, Postgis returns not PGgeometry objects
// but org.postgis.Geometry instances.
// This has been observed when retrieving GeometryCollections
// as the result of an SQL-operation such as Union.
if (object instanceof org.postgis.Geometry) {
object = new PGgeometry((org.postgis.Geometry) object);
}
public Geometry toJTS(Object object) {
if ( object == null ) {
return null;
}
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());
// in some cases, Postgis returns not PGgeometry objects
// but org.postgis.Geometry instances.
// This has been observed when retrieving GeometryCollections
// 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 ) {
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) {
org.postgis.Geometry[] geometries = collection.getGeometries();
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;
}
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 convertMultiPolygon(MultiPolygon pgMultiPolygon) {
com.vividsolutions.jts.geom.Polygon[] polygons = new com.vividsolutions.jts.geom.Polygon[pgMultiPolygon
.numPolygons()];
private Geometry convertGeometryCollection(GeometryCollection collection) {
org.postgis.Geometry[] geometries = collection.getGeometries();
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++) {
Polygon pgPolygon = pgMultiPolygon.getPolygon(i);
polygons[i] = (com.vividsolutions.jts.geom.Polygon) convertPolygon(pgPolygon);
}
private Geometry convertMultiPolygon(MultiPolygon pgMultiPolygon) {
com.vividsolutions.jts.geom.Polygon[] polygons = new com.vividsolutions.jts.geom.Polygon[pgMultiPolygon
.numPolygons()];
com.vividsolutions.jts.geom.MultiPolygon out = getGeometryFactory()
.createMultiPolygon(polygons);
return out;
}
for ( int i = 0; i < polygons.length; i++ ) {
Polygon pgPolygon = pgMultiPolygon.getPolygon( i );
polygons[i] = (com.vividsolutions.jts.geom.Polygon) convertPolygon( pgPolygon );
}
private Geometry convertMultiPoint(MultiPoint pgMultiPoint) {
com.vividsolutions.jts.geom.Point[] points = new com.vividsolutions.jts.geom.Point[pgMultiPoint
.numPoints()];
com.vividsolutions.jts.geom.MultiPolygon out = getGeometryFactory()
.createMultiPolygon( polygons );
return out;
}
for (int i = 0; i < points.length; i++) {
points[i] = convertPoint(pgMultiPoint.getPoint(i));
}
com.vividsolutions.jts.geom.MultiPoint out = getGeometryFactory()
.createMultiPoint(points);
out.setSRID(pgMultiPoint.srid);
return out;
}
private Geometry convertMultiPoint(MultiPoint pgMultiPoint) {
com.vividsolutions.jts.geom.Point[] points = new com.vividsolutions.jts.geom.Point[pgMultiPoint
.numPoints()];
private com.vividsolutions.jts.geom.Geometry convertMultiLineString(
MultiLineString mlstr) {
com.vividsolutions.jts.geom.MultiLineString out;
if (mlstr.haveMeasure) {
MLineString[] lstrs = new MLineString[mlstr.numLines()];
for (int i = 0; i < mlstr.numLines(); i++) {
MCoordinate[] coordinates = toJTSCoordinates(mlstr.getLine(i)
.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;
}
for ( int i = 0; i < points.length; i++ ) {
points[i] = convertPoint( pgMultiPoint.getPoint( i ) );
}
com.vividsolutions.jts.geom.MultiPoint out = getGeometryFactory()
.createMultiPoint( points );
out.setSRID( pgMultiPoint.srid );
return out;
}
protected com.vividsolutions.jts.geom.Geometry convertPolygon(
Polygon polygon) {
com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory()
.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;
}
private com.vividsolutions.jts.geom.Geometry convertMultiLineString(
MultiLineString mlstr) {
com.vividsolutions.jts.geom.MultiLineString out;
if ( mlstr.haveMeasure ) {
MLineString[] lstrs = new MLineString[mlstr.numLines()];
for ( int i = 0; i < mlstr.numLines(); i++ ) {
MCoordinate[] coordinates = toJTSCoordinates(
mlstr.getLine( i )
.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.Point convertPoint(Point pnt) {
com.vividsolutions.jts.geom.Point g = getGeometryFactory().createPoint(
this.toJTSCoordinate(pnt));
return g;
}
protected com.vividsolutions.jts.geom.Geometry convertPolygon(
Polygon polygon) {
com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory()
.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(
org.postgis.LineString lstr) {
com.vividsolutions.jts.geom.LineString out = lstr.haveMeasure ? getGeometryFactory()
.createMLineString(toJTSCoordinates(lstr.getPoints()))
: getGeometryFactory().createLineString(
toJTSCoordinates(lstr.getPoints()));
return out;
}
protected com.vividsolutions.jts.geom.Point convertPoint(Point pnt) {
com.vividsolutions.jts.geom.Point g = getGeometryFactory().createPoint(
this.toJTSCoordinate( pnt )
);
return g;
}
private MCoordinate[] toJTSCoordinates(Point[] points) {
MCoordinate[] coordinates = new MCoordinate[points.length];
for (int i = 0; i < points.length; i++) {
coordinates[i] = this.toJTSCoordinate(points[i]);
}
return coordinates;
}
protected com.vividsolutions.jts.geom.LineString convertLineString(
org.postgis.LineString lstr) {
com.vividsolutions.jts.geom.LineString out = lstr.haveMeasure ? getGeometryFactory()
.createMLineString( toJTSCoordinates( lstr.getPoints() ) )
: getGeometryFactory().createLineString(
toJTSCoordinates( lstr.getPoints() )
);
return out;
}
private MCoordinate toJTSCoordinate(Point pt) {
MCoordinate mc;
if (pt.dimension == 2) {
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;
}
private MCoordinate[] toJTSCoordinates(Point[] points) {
MCoordinate[] coordinates = new MCoordinate[points.length];
for ( int i = 0; i < points.length; i++ ) {
coordinates[i] = this.toJTSCoordinate( points[i] );
}
return coordinates;
}
private MCoordinate toJTSCoordinate(Point pt) {
MCoordinate mc;
if ( pt.dimension == 2 ) {
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.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.descriptor.sql.SqlTypeDescriptor;
@ -44,155 +49,266 @@
public class PostgisDialect extends PostgreSQLDialect implements SpatialDialect {
public PostgisDialect() {
super();
registerTypesAndFunctions();
}
public PostgisDialect() {
super();
registerTypesAndFunctions();
}
protected void registerTypesAndFunctions() {
protected void registerTypesAndFunctions() {
registerColumnType(java.sql.Types.STRUCT, "geometry");
// registering OGC functions
// (spec_simplefeatures_sql_99-04.pdf)
registerColumnType( java.sql.Types.STRUCT, "geometry" );
// registering OGC functions
// (spec_simplefeatures_sql_99-04.pdf)
// section 2.1.1.1
// Registerfunction calls for registering geometry functions:
// first argument is the OGC standard functionname, second the name as
// it occurs in the spatial dialect
registerFunction("dimension", new StandardSQLFunction("st_dimension",
StandardBasicTypes.INTEGER));
registerFunction("geometrytype", new StandardSQLFunction(
"st_geometrytype", StandardBasicTypes.STRING));
registerFunction("srid", new StandardSQLFunction("st_srid",
StandardBasicTypes.INTEGER));
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));
// section 2.1.1.1
// Registerfunction calls for registering geometry functions:
// first argument is the OGC standard functionname, second the name as
// it occurs in the spatial dialect
registerFunction(
"dimension", new StandardSQLFunction(
"st_dimension",
StandardBasicTypes.INTEGER
)
);
registerFunction(
"geometrytype", new StandardSQLFunction(
"st_geometrytype", StandardBasicTypes.STRING
)
);
registerFunction(
"srid", new StandardSQLFunction(
"st_srid",
StandardBasicTypes.INTEGER
)
);
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
registerFunction("overlaps", new StandardSQLFunction("st_overlaps",
StandardBasicTypes.BOOLEAN));
registerFunction("intersects", new StandardSQLFunction("st_intersects",
StandardBasicTypes.BOOLEAN));
registerFunction("equals", new StandardSQLFunction("st_equals",
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 functions for spatial relation constructs
registerFunction(
"overlaps", new StandardSQLFunction(
"st_overlaps",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"intersects", new StandardSQLFunction(
"st_intersects",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"equals", new StandardSQLFunction(
"st_equals",
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
registerFunction("distance", new StandardSQLFunction("st_distance",
StandardBasicTypes.DOUBLE));
registerFunction("buffer", new StandardSQLFunction("st_buffer",
GeometryType.INSTANCE));
registerFunction("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 the spatial analysis functions
registerFunction(
"distance", new StandardSQLFunction(
"st_distance",
StandardBasicTypes.DOUBLE
)
);
registerFunction(
"buffer", new StandardSQLFunction(
"st_buffer",
GeometryType.INSTANCE
)
);
registerFunction(
"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
registerFunction("extent", new StandardSQLFunction("extent",
GeometryType.INSTANCE));
//register Spatial Aggregate function
registerFunction(
"extent", new StandardSQLFunction(
"extent",
GeometryType.INSTANCE
)
);
//other common functions
registerFunction("dwithin", new StandardSQLFunction("st_dwithin",
StandardBasicTypes.BOOLEAN));
registerFunction("transform", new StandardSQLFunction("st_transform",
GeometryType.INSTANCE));
}
//other common functions
registerFunction(
"dwithin", new StandardSQLFunction(
"st_dwithin",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"transform", new StandardSQLFunction(
"st_transform",
GeometryType.INSTANCE
)
);
}
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (sqlTypeDescriptor instanceof SpatialGeometrySqlTypeDescriptor) {
return PGGeometryTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
}
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if ( sqlTypeDescriptor instanceof SpatialGeometrySqlTypeDescriptor ) {
return PGGeometryTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor( sqlTypeDescriptor );
}
public String getSpatialRelateSQL(String columnName, int spatialRelation) {
switch (spatialRelation) {
case SpatialRelation.WITHIN:
return " ST_within(" + columnName + ",?)";
case SpatialRelation.CONTAINS:
return " ST_contains(" + columnName + ", ?)";
case SpatialRelation.CROSSES:
return " ST_crosses(" + columnName + ", ?)";
case SpatialRelation.OVERLAPS:
return " ST_overlaps(" + columnName + ", ?)";
case SpatialRelation.DISJOINT:
return " ST_disjoint(" + columnName + ", ?)";
case SpatialRelation.INTERSECTS:
return " ST_intersects(" + columnName
+ ", ?)";
case SpatialRelation.TOUCHES:
return " ST_touches(" + columnName + ", ?)";
case SpatialRelation.EQUALS:
return " ST_equals(" + columnName + ", ?)";
default:
throw new IllegalArgumentException(
"Spatial relation is not known by this dialect");
}
public String getSpatialRelateSQL(String columnName, int spatialRelation) {
switch ( spatialRelation ) {
case SpatialRelation.WITHIN:
return " ST_within(" + columnName + ",?)";
case SpatialRelation.CONTAINS:
return " ST_contains(" + columnName + ", ?)";
case SpatialRelation.CROSSES:
return " ST_crosses(" + columnName + ", ?)";
case SpatialRelation.OVERLAPS:
return " ST_overlaps(" + columnName + ", ?)";
case SpatialRelation.DISJOINT:
return " ST_disjoint(" + columnName + ", ?)";
case SpatialRelation.INTERSECTS:
return " ST_intersects(" + columnName
+ ", ?)";
case SpatialRelation.TOUCHES:
return " ST_touches(" + columnName + ", ?)";
case SpatialRelation.EQUALS:
return " ST_equals(" + columnName + ", ?)";
default:
throw new IllegalArgumentException(
"Spatial relation is not known by this dialect"
);
}
}
}
public String getDWithinSQL(String columnName) {
return "ST_DWithin(" + columnName + ",?,?)";
}
public String getDWithinSQL(String columnName) {
return "ST_DWithin(" + columnName + ",?,?)";
}
public String getHavingSridSQL(String columnName) {
return "( ST_srid(" + columnName + ") = ?)";
}
public String getHavingSridSQL(String columnName) {
return "( ST_srid(" + columnName + ") = ?)";
}
public String getIsEmptySQL(String columnName, boolean isEmpty) {
String emptyExpr = " ST_IsEmpty(" + columnName + ") ";
return isEmpty ? emptyExpr : "( NOT " + emptyExpr + ")";
}
public String getIsEmptySQL(String columnName, boolean isEmpty) {
String emptyExpr = " ST_IsEmpty(" + columnName + ") ";
return isEmpty ? emptyExpr : "( NOT " + emptyExpr + ")";
}
public String getSpatialFilterExpression(String columnName) {
return "(" + columnName + " && ? ) ";
}
public String getSpatialFilterExpression(String columnName) {
return "(" + columnName + " && ? ) ";
}
public String getSpatialAggregateSQL(String columnName, int aggregation) {
switch (aggregation) {
case SpatialAggregate.EXTENT:
StringBuilder stbuf = new StringBuilder();
stbuf.append("extent(").append(columnName).append(")");
return stbuf.toString();
default:
throw new IllegalArgumentException("Aggregation of type "
+ aggregation + " are not supported by this dialect");
}
}
public String getSpatialAggregateSQL(String columnName, int aggregation) {
switch ( aggregation ) {
case SpatialAggregate.EXTENT:
StringBuilder stbuf = new StringBuilder();
stbuf.append( "extent(" ).append( columnName ).append( ")" );
return stbuf.toString();
default:
throw new IllegalArgumentException(
"Aggregation of type "
+ aggregation + " are not supported by this dialect"
);
}
}
public boolean supportsFiltering() {
return true;
}
public boolean supportsFiltering() {
return true;
}
public boolean supports(SpatialFunction function) {
return (getFunctions().get(function.toString()) != null);
}
public boolean supports(SpatialFunction function) {
return ( getFunctions().get( function.toString() ) != null );
}
}

View File

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

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* 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) {
Coordinate[] coords = new Coordinate[5];
coords[0] = new Coordinate(env.getMinX(), env.getMinY());
coords[1] = new Coordinate(env.getMinX(), env.getMaxY());
coords[2] = new Coordinate(env.getMaxX(), env.getMaxY());
coords[3] = new Coordinate(env.getMaxX(), env.getMinY());
coords[4] = new Coordinate(env.getMinX(), env.getMinY());
LinearRing shell = geomFactory.createLinearRing(coords);
coords[0] = new Coordinate( env.getMinX(), env.getMinY() );
coords[1] = new Coordinate( env.getMinX(), env.getMaxY() );
coords[2] = new Coordinate( env.getMaxX(), env.getMaxY() );
coords[3] = new Coordinate( env.getMaxX(), env.getMinY() );
coords[4] = new Coordinate( env.getMinX(), env.getMinY() );
LinearRing shell = geomFactory.createLinearRing( coords );
Polygon pg = geomFactory.createPolygon(shell, null);
pg.setSRID(SRID);
Polygon pg = geomFactory.createPolygon( shell, null );
pg.setSRID( SRID );
return pg;
}

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2008 Geovise BVBA
*
* 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
* resource.
*
*
* @author maesenka
*
*/
public class FinderException extends Exception {
private static final long serialVersionUID = 1L;
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
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2008 Geovise BVBA
*
* 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
* useful in cases where reflection is used to determine some property of a
* class.
*
*
* @param <T> the return type of the <code>find</code> method
* @param <S> the type of subject
*
* @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> {
/**
* Find a feature or property of a subject
*
* @param subject
* the object that is being searched
*
* @param subject the object that is being searched
*
* @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;

View File

@ -24,13 +24,14 @@
*/
package org.hibernate.spatial.helper;
import java.util.Map;
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.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
@ -40,46 +41,59 @@
*/
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) {
return new MGeometryFactory();
}
String precisionModelName = null;
Double scale = null;
if (map.containsKey(HSProperty.PRECISION_MODEL.toString())) {
precisionModelName = (String) map.get(HSProperty.PRECISION_MODEL
.toString());
}
if (map.containsKey(HSProperty.PRECISION_MODEL_SCALE.toString())) {
scale = Double.parseDouble(((String) map
.get(HSProperty.PRECISION_MODEL_SCALE.toString())));
}
if (scale != null && !scale.isNaN() && precisionModelName != null
&& precisionModelName.equalsIgnoreCase("FIXED")) {
return new MGeometryFactory(new PrecisionModel(scale));
}
if (precisionModelName == null) {
return new MGeometryFactory();
}
if (precisionModelName.equalsIgnoreCase("FIXED")) {
return new MGeometryFactory(
new PrecisionModel(PrecisionModel.FIXED));
}
if (precisionModelName.equalsIgnoreCase("FLOATING")) {
return new MGeometryFactory(new PrecisionModel(
PrecisionModel.FLOATING));
}
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();
}
if ( map == null ) {
return new MGeometryFactory();
}
String precisionModelName = null;
Double scale = null;
if ( map.containsKey( HSProperty.PRECISION_MODEL.toString() ) ) {
precisionModelName = (String) map.get(
HSProperty.PRECISION_MODEL
.toString()
);
}
if ( map.containsKey( HSProperty.PRECISION_MODEL_SCALE.toString() ) ) {
scale = Double.parseDouble(
( (String) map
.get( HSProperty.PRECISION_MODEL_SCALE.toString() ) )
);
}
if ( scale != null && !scale.isNaN() && precisionModelName != null
&& precisionModelName.equalsIgnoreCase( "FIXED" ) ) {
return new MGeometryFactory( new PrecisionModel( scale ) );
}
if ( precisionModelName == null ) {
return new MGeometryFactory();
}
if ( precisionModelName.equalsIgnoreCase( "FIXED" ) ) {
return new MGeometryFactory(
new PrecisionModel( PrecisionModel.FIXED )
);
}
if ( precisionModelName.equalsIgnoreCase( "FLOATING" ) ) {
return new MGeometryFactory(
new PrecisionModel(
PrecisionModel.FLOATING
)
);
}
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;
import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.Type;
import com.vividsolutions.jts.geom.Geometry;
/**
* This <code>FinderStrategy</code> implementation returns the first
* geometry-valued property.
*
*/
public class GeometryPropertyFinder implements FinderStrategy<String, ClassMetadata> {
public String find(ClassMetadata metadata) throws FinderException {
for (String prop : metadata.getPropertyNames()) {
Type type = metadata.getPropertyType(prop);
for ( String prop : metadata.getPropertyNames() ) {
Type type = metadata.getPropertyType( prop );
if (Geometry.class.isAssignableFrom(type.getReturnedClass())) {
if ( Geometry.class.isAssignableFrom( type.getReturnedClass() ) ) {
return prop;
}
}
throw new FinderException(
"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
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
*
@ -43,19 +43,18 @@
/**
* Helper class to read settings and properties files.
*
*
* @author Karel Maesen
*
*/
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.
*/
private static final Pattern nonCommentPattern = Pattern
.compile("^([^#]+)");
.compile( "^([^#]+)" );
private InputStream is = null;
@ -64,28 +63,30 @@ public PropertyFileReader(InputStream is) {
}
public Properties getProperties() throws IOException {
if (is == null)
if ( is == null ) {
return null;
}
Properties props = new Properties();
props.load(is);
props.load( is );
return props;
}
/**
* Returns the non-comment lines in a file.
*
*
* @return set of non-comment strings.
*
* @throws IOException
*/
public Set<String> getNonCommentLines() throws IOException {
Set<String> lines = new HashSet<String>();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
while ( ( line = reader.readLine() ) != null ) {
line = line.trim();
Matcher m = nonCommentPattern.matcher(line);
if (m.find()) {
lines.add(m.group().trim());
Matcher m = nonCommentPattern.matcher( line );
if ( m.find() ) {
lines.add( m.group().trim() );
}
}
return lines;
@ -94,8 +95,9 @@ public Set<String> getNonCommentLines() throws IOException {
public void close() {
try {
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 {
@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
sessionFactory.getTypeResolver().registerTypeOverride(GeometryType.INSTANCE);
}
@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
sessionFactory.getTypeResolver().registerTypeOverride( GeometryType.INSTANCE );
}
@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
//do nothing.
}
@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
//do nothing.
}
}

View File

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

View File

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

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* 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
* substitute in the event that the Measure value is not used. In these cases
* the Measure value shall simply be Double.NaN
*
*
* @see com.vividsolutions.jts.geom.Coordinate
*/
public class MCoordinate extends Coordinate {
/**
*
*
*/
private static final long serialVersionUID = 1L;
@ -60,25 +60,27 @@ public MCoordinate() {
}
public MCoordinate(double x, double y, double z, double m) {
super(x, y, z);
super( x, y, z );
this.m = m;
}
public MCoordinate(double x, double y) {
super(x, y);
super( x, y );
m = Double.NaN;
}
public MCoordinate(Coordinate coord) {
super(coord);
if (coord instanceof MCoordinate)
m = ((MCoordinate) coord).m;
else
super( coord );
if ( coord instanceof MCoordinate ) {
m = ( (MCoordinate) coord ).m;
}
else {
m = Double.NaN;
}
}
public MCoordinate(MCoordinate coord) {
super(coord);
super( coord );
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
* geometry with a measure value. Therefore, these constants are highly
* recommended.
*
* @param ordinateIndex
* the desired ordinate index.
*
* @param ordinateIndex the desired ordinate index.
*
* @return the value of stored in the ordinate index. Incorrect or unused
* indexes shall return Double.NaN
*/
public double getOrdinate(int ordinateIndex) {
switch (ordinateIndex) {
case CoordinateSequence.X:
return this.x;
case CoordinateSequence.Y:
return this.y;
case CoordinateSequence.Z:
return this.z;
case CoordinateSequence.M:
return this.m;
switch ( ordinateIndex ) {
case CoordinateSequence.X:
return this.x;
case CoordinateSequence.Y:
return this.y;
case CoordinateSequence.Z:
return this.z;
case CoordinateSequence.M:
return this.m;
}
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
* the value for a given ordinate. This should be specified using the
* CoordinateSequence ordinate index constants.
*
* @param ordinateIndex
* the desired ordinate index.
* @param value
* the new ordinate value
* @throws IllegalArgumentException
* if the ordinateIndex value is incorrect
*
* @param ordinateIndex the desired ordinate index.
* @param value the new ordinate value
*
* @throws IllegalArgumentException if the ordinateIndex value is incorrect
* @see #getOrdinate(int)
*/
public void setOrdinate(int ordinateIndex, double value) {
switch (ordinateIndex) {
case CoordinateSequence.X:
this.x = value;
break;
case CoordinateSequence.Y:
this.y = value;
break;
case CoordinateSequence.Z:
this.z = value;
break;
case CoordinateSequence.M:
this.m = value;
break;
default:
throw new IllegalArgumentException("invalid ordinateIndex");
switch ( ordinateIndex ) {
case CoordinateSequence.X:
this.x = value;
break;
case CoordinateSequence.Y:
this.y = value;
break;
case CoordinateSequence.Z:
this.z = value;
break;
case CoordinateSequence.M:
this.m = value;
break;
default:
throw new IllegalArgumentException( "invalid ordinateIndex" );
}
}
public boolean equals2DWithMeasure(Coordinate other) {
boolean result = this.equals2D(other);
if (result) {
MCoordinate mc = convertCoordinate(other);
result = (Double.compare(this.m, mc.m) == 0);
boolean result = this.equals2D( other );
if ( result ) {
MCoordinate mc = convertCoordinate( other );
result = ( Double.compare( this.m, mc.m ) == 0 );
}
return result;
}
public boolean equals3DWithMeasure(Coordinate other) {
boolean result = this.equals3D(other);
if (result) {
MCoordinate mc = convertCoordinate(other);
result = (Double.compare(this.m, mc.m) == 0);
boolean result = this.equals3D( other );
if ( result ) {
MCoordinate mc = convertCoordinate( other );
result = ( Double.compare( this.m, mc.m ) == 0 );
}
return result;
}
@ -173,9 +173,10 @@ public boolean equals3DWithMeasure(Coordinate other) {
* @see com.vividsolutions.jts.geom.Coordinate#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other instanceof Coordinate) {
return equals2D((Coordinate) other);
} else {
if ( other instanceof Coordinate ) {
return equals2D( (Coordinate) other );
}
else {
return false;
}
}
@ -189,85 +190,79 @@ public String toString() {
* coordinate is already an instance of an MCoordinate, then it is simply
* returned. In cases where it is converted, the measure value of the
* coordinate is initialized to Double.NaN.
*
* @param coordinate
* The coordinate to be converted
*
* @param coordinate The coordinate to be converted
*
* @return an instance of MCoordinate corresponding to the
* <code>coordinate</code> parameter
*/
public static MCoordinate convertCoordinate(Coordinate coordinate) {
if (coordinate == null)
if ( coordinate == null ) {
return null;
if (coordinate instanceof MCoordinate)
}
if ( coordinate instanceof MCoordinate ) {
return (MCoordinate) coordinate;
return new MCoordinate(coordinate);
}
return new MCoordinate( coordinate );
}
/**
* A convenience method for creating a MCoordinate instance where there are
* only 2 coordinates and an lrs measure value. The z value of the
* coordinate shall be set to Double.NaN
*
* @param x
* the x coordinate value
* @param y
* the y coordinate value
* @param m
* the lrs measure value
*
* @param x the x coordinate value
* @param y the y coordinate value
* @param m the lrs measure value
*
* @return The constructed MCoordinate value
*/
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
* only 2 coordinates and an lrs measure value. The z and m value of the
* coordinate shall be set to Double.NaN
*
* @param x
* the x coordinate value
* @param y
* the y coordinate value
*
* @param x the x coordinate value
* @param y the y coordinate value
*
* @return The constructed MCoordinate value
*/
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
* 3 coordinates and an lrs measure value.
*
* @param x
* the x coordinate value
* @param y
* the y coordinate value
* @param z
* the z coordinate value
* @param m
* the lrs measure value
*
* @param x the x coordinate value
* @param y the y coordinate value
* @param z the z coordinate value
* @param m the lrs measure value
*
* @return The constructed MCoordinate value
*/
public static MCoordinate create3dWithMeasure(double x, double y, double z,
double m) {
return new MCoordinate(x, y, z, m);
double m) {
return new MCoordinate( x, y, z, m );
}
/**
* A convenience method for creating a MCoordinate instance where there are
* 3 coordinates but no lrs measure value. The m value of the coordinate
* shall be set to Double.NaN
*
* @param x
* the x coordinate value
* @param y
* the y coordinate value
* @param z
* the z coordinate value
*
* @param x the x coordinate value
* @param y the y coordinate value
* @param z the z coordinate value
*
* @return The constructed MCoordinate value
*/
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
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
*
@ -28,12 +28,12 @@
*/
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 com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Envelope;
/**
* Implements the CoordinateSequence interface. In this implementation,
* Coordinates returned by #toArray and #get are live -- parties that change
@ -41,7 +41,7 @@
*/
public class MCoordinateSequence implements CoordinateSequence, Serializable {
/**
*
*
*/
private static final long serialVersionUID = 1L;
@ -49,16 +49,16 @@ public class MCoordinateSequence implements CoordinateSequence, Serializable {
public static MCoordinate[] copy(Coordinate[] coordinates) {
MCoordinate[] copy = new MCoordinate[coordinates.length];
for (int i = 0; i < coordinates.length; i++) {
copy[i] = new MCoordinate(coordinates[i]);
for ( int i = 0; i < coordinates.length; i++ ) {
copy[i] = new MCoordinate( coordinates[i] );
}
return copy;
}
public static MCoordinate[] copy(CoordinateSequence coordSeq) {
MCoordinate[] copy = new MCoordinate[coordSeq.size()];
for (int i = 0; i < coordSeq.size(); i++) {
copy[i] = new MCoordinate(coordSeq.getCoordinate(i));
for ( int i = 0; i < coordSeq.size(); i++ ) {
copy[i] = new MCoordinate( coordSeq.getCoordinate( i ) );
}
return copy;
}
@ -66,7 +66,7 @@ public static MCoordinate[] copy(CoordinateSequence coordSeq) {
/**
* Copy constructor -- simply aliases the input array, for better
* performance.
*
*
* @param 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
* copy of the input array, since the actual class of the Coordinates in the
* input array may be different from MCoordinate.
*
*
* @param copyCoords
*/
public MCoordinateSequence(Coordinate[] copyCoords) {
coordinates = copy(copyCoords);
coordinates = copy( copyCoords );
}
/**
* Constructor that makes a copy of a CoordinateSequence.
*
*
* @param coordSeq
*/
public MCoordinateSequence(CoordinateSequence coordSeq) {
coordinates = copy(coordSeq);
coordinates = copy( coordSeq );
}
/**
* Constructs a sequence of a given size, populated with new
* {@link MCoordinate}s.
*
* @param size
* the size of the sequence to create
*
* @param size the size of the sequence to create
*/
public MCoordinateSequence(int size) {
coordinates = new MCoordinate[size];
for (int i = 0; i < size; i++) {
for ( int i = 0; i < size; i++ ) {
coordinates[i] = new MCoordinate();
}
}
@ -122,12 +121,12 @@ public Coordinate getCoordinate(int i) {
* @see com.vividsolutions.jts.geom.CoordinateSequence#getCoordinateCopy(int)
*/
public Coordinate getCoordinateCopy(int index) {
return new Coordinate(coordinates[index]);
return new Coordinate( coordinates[index] );
}
/**
* @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) {
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) {
switch (ordinateIndex) {
case CoordinateSequence.X:
return coordinates[index].x;
case CoordinateSequence.Y:
return coordinates[index].y;
case CoordinateSequence.Z:
return coordinates[index].z;
case CoordinateSequence.M:
return coordinates[index].m;
switch ( ordinateIndex ) {
case CoordinateSequence.X:
return coordinates[index].x;
case CoordinateSequence.Y:
return coordinates[index].y;
case CoordinateSequence.Z:
return coordinates[index].z;
case CoordinateSequence.M:
return coordinates[index].m;
}
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) {
switch (ordinateIndex) {
case CoordinateSequence.X:
coordinates[index].x = value;
break;
case CoordinateSequence.Y:
coordinates[index].y = value;
break;
case CoordinateSequence.Z:
coordinates[index].z = value;
break;
case CoordinateSequence.M:
coordinates[index].m = value;
break;
default:
throw new IllegalArgumentException("invalid ordinateIndex");
switch ( ordinateIndex ) {
case CoordinateSequence.X:
coordinates[index].x = value;
break;
case CoordinateSequence.Y:
coordinates[index].y = value;
break;
case CoordinateSequence.Z:
coordinates[index].z = value;
break;
case CoordinateSequence.M:
coordinates[index].m = value;
break;
default:
throw new IllegalArgumentException( "invalid ordinateIndex" );
}
}
public Object clone() {
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();
}
return new MCoordinateSequence(cloneCoordinates);
return new MCoordinateSequence( cloneCoordinates );
}
public int size() {
@ -212,21 +211,22 @@ public Coordinate[] toCoordinateArray() {
}
public Envelope expandEnvelope(Envelope env) {
for (int i = 0; i < coordinates.length; i++) {
env.expandToInclude(coordinates[i]);
for ( int i = 0; i < coordinates.length; i++ ) {
env.expandToInclude( coordinates[i] );
}
return env;
}
public String toString() {
StringBuffer strBuf = new StringBuffer();
strBuf.append("MCoordinateSequence [");
for (int i = 0; i < coordinates.length; i++) {
if (i > 0)
strBuf.append(", ");
strBuf.append(coordinates[i]);
strBuf.append( "MCoordinateSequence [" );
for ( int i = 0; i < coordinates.length; i++ ) {
if ( i > 0 ) {
strBuf.append( ", " );
}
strBuf.append( coordinates[i] );
}
strBuf.append("]");
strBuf.append( "]" );
return strBuf.toString();
}
}

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
*
@ -42,7 +42,7 @@ public class MCoordinateSequenceFactory implements CoordinateSequenceFactory,
Serializable {
/**
*
*
*/
private static final long serialVersionUID = 1L;
@ -65,22 +65,24 @@ public static MCoordinateSequenceFactory instance() {
*/
public CoordinateSequence create(Coordinate[] coordinates) {
return coordinates instanceof MCoordinate[] ? new MCoordinateSequence(
(MCoordinate[]) coordinates) : new MCoordinateSequence(
coordinates);
(MCoordinate[]) coordinates
) : new MCoordinateSequence(
coordinates
);
}
public CoordinateSequence create(CoordinateSequence coordSeq) {
return new MCoordinateSequence(coordSeq);
return new MCoordinateSequence( coordSeq );
}
/**
* Creates a MCoordinateSequence instance initialized to the size parameter.
* 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) {
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
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
*
@ -28,16 +28,16 @@
*/
package org.hibernate.spatial.mgeom;
import java.io.Serializable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry;
import java.io.Serializable;
import com.vividsolutions.jts.geom.GeometryFactory;
/**
* Defines geometries that carry measures in their CoordinateSequence.
*
*
* @author Karel Maesen
*/
@ -65,19 +65,18 @@ public interface MGeometry extends Cloneable, Serializable {
/**
* Returns the measure value at the Coordinate
*
* @param c
* the Coordinate for which the measure value is sought
* @param tolerance
* distance to the MGeometry within which Coordinate c has to lie
*
* @param c the Coordinate for which the measure value is sought
* @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
* Geometry, else Double.NaN
* <p>
* When the geometry is a ring or is self-intersecting more
* coordinates may be determined by one coordinate. In that case,
* 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)
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
* (first coordinate) of the Geometry.
*
*
* @param keepBeginMeasure -
* if true, the measure of the first coordinate is maintained and
* used as start value, unless this measure is Double.NaN
* if true, the measure of the first coordinate is maintained and
* used as start value, unless this measure is Double.NaN
*/
public void measureOnLength(boolean keepBeginMeasure);
/**
* Returns the Coordinate along the Geometry at the measure value
*
* @param m
* measure value
*
* @param m measure value
*
* @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;
/**
* Returns the coordinatesequence(s) containing all coordinates between the
* begin and end measures.
*
* @param begin
* begin measure
* @param end
* end measure
*
* @param begin begin measure
* @param end end measure
*
* @return an array containing all coordinatesequences in order between
* begin and end. Each CoordinateSequence covers a contiguous
* 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)
throws MGeometryException;
/**
* Returns the GeometryFactory of the MGeometry
*
*
* @return the GeometryFactory of this MGeometry
*/
public GeometryFactory getFactory();
/**
* Returns the minimum M-value of the MGeometry
*
*
* @return the minimum M-value
*/
public double getMinM();
/**
* Returns the maximum M-value of the MGeometry
*
*
* @return the maximum M-value
*/
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> [5,3,3,0] - Non-strict Monotone Decreasing
* </ul>
*
*
* @return true if the coordinates in the CoordinateSequence of the geometry
* are monotone.
*/
@ -175,13 +173,13 @@ public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
// */
// public boolean isStrictMonotone();
/**
* Returns this <code>MGeometry</code> as a <code>Geometry</code>.
*
* Modifying the returned <code>Geometry</code> will result in internal state changes.
*
* @return this object as a Geometry.
*/
public Geometry asGeometry();
/**
* Returns this <code>MGeometry</code> as a <code>Geometry</code>.
*
* Modifying the returned <code>Geometry</code> will result in internal state changes.
*
* @return this object as a Geometry.
*/
public Geometry asGeometry();
}

View File

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

View File

@ -3,7 +3,7 @@
*
* This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data.
*
*
* Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
*
@ -28,77 +28,83 @@
*/
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
* support.
*
*
* @see com.vividsolutions.jts.geom.GeometryFactory
*/
public class MGeometryFactory extends GeometryFactory {
/**
*
*
*/
private static final long serialVersionUID = 1L;
public MGeometryFactory(PrecisionModel precisionModel, int SRID,
MCoordinateSequenceFactory coordinateSequenceFactory) {
super(precisionModel, SRID, coordinateSequenceFactory);
MCoordinateSequenceFactory coordinateSequenceFactory) {
super( precisionModel, SRID, coordinateSequenceFactory );
}
public MGeometryFactory(MCoordinateSequenceFactory coordinateSequenceFactory) {
super(coordinateSequenceFactory);
super( coordinateSequenceFactory );
}
public MGeometryFactory(PrecisionModel precisionModel) {
this(precisionModel, 0, MCoordinateSequenceFactory.instance());
this( precisionModel, 0, MCoordinateSequenceFactory.instance() );
}
public MGeometryFactory(PrecisionModel precisionModel, int SRID) {
this(precisionModel, SRID, MCoordinateSequenceFactory.instance());
this( precisionModel, SRID, MCoordinateSequenceFactory.instance() );
}
public MGeometryFactory() {
this(new PrecisionModel(), 0);
this( new PrecisionModel(), 0 );
}
/**
* Constructs a MLineString using the given Coordinates; a null or empty
* array will create an empty MLineString.
*
* @param coordinates
* array of MCoordinate defining this geometry's vertices
* @see #createLineString(com.vividsolutions.jts.geom.Coordinate[])
*
* @param coordinates array of MCoordinate defining this geometry's vertices
*
* @return An instance of MLineString containing the coordinates
*
* @see #createLineString(com.vividsolutions.jts.geom.Coordinate[])
*/
public MLineString createMLineString(MCoordinate[] coordinates) {
return createMLineString(coordinates != null ? getCoordinateSequenceFactory()
.create(coordinates)
: null);
return createMLineString(
coordinates != null ? getCoordinateSequenceFactory()
.create( coordinates )
: null
);
}
public MultiMLineString createMultiMLineString(MLineString[] mlines,
double mGap) {
return new MultiMLineString(mlines, mGap, this);
double mGap) {
return new MultiMLineString( mlines, mGap, this );
}
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
* CoordinateSequence will create an empty MLineString.
*
* @param coordinates
* a CoordinateSequence possibly empty, or null
*
* @param coordinates a CoordinateSequence possibly empty, or null
*
* @return An MLineString instance based on the <code>coordinates</code>
*
* @see #createLineString(com.vividsolutions.jts.geom.CoordinateSequence)
*/
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;
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 {
/**
*
*/
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
* <code>MultiMLineString</code>, or <code>null</code> or an
* empty array to create the empty geometry. Elements may be
* empty <code>LineString</code>s, but not <code>null</code>s.
*/
public MultiMLineString(MLineString[] MlineStrings, double mGap,
GeometryFactory factory) {
super(MlineStrings, factory);
this.mGap = mGap;
determineMonotone();
}
/**
* @param MlineStrings the <code>MLineString</code>s for this
* <code>MultiMLineString</code>, or <code>null</code> or an
* empty array to create the empty geometry. Elements may be
* empty <code>LineString</code>s, but not <code>null</code>s.
*/
public MultiMLineString(MLineString[] MlineStrings, double mGap,
GeometryFactory factory) {
super( MlineStrings, factory );
this.mGap = mGap;
determineMonotone();
}
/**
* TODO Improve this, and add more unit tests
*/
private void determineMonotone() {
this.monotone = true;
this.strictMonotone = true;
if (this.isEmpty()) {
return;
}
int mdir = MGeometry.CONSTANT;
for (int i = 0; i < this.geometries.length; i++) {
MLineString ml = (MLineString) this.geometries[0];
if (!ml.isEmpty()) {
mdir = ml.getMeasureDirection();
break;
}
}
for (int i = 0; i < this.geometries.length; i++) {
MLineString ml = (MLineString) this.geometries[i];
if (ml.isEmpty()) continue;
// check whether mlinestrings are all pointing in same direction,
// and
// are monotone
if (!ml.isMonotone(false)
|| (ml.getMeasureDirection() != mdir && !(ml
.getMeasureDirection() == MGeometry.CONSTANT))) {
this.monotone = false;
break;
}
/**
* TODO Improve this, and add more unit tests
*/
private void determineMonotone() {
this.monotone = true;
this.strictMonotone = true;
if ( this.isEmpty() ) {
return;
}
int mdir = MGeometry.CONSTANT;
for ( int i = 0; i < this.geometries.length; i++ ) {
MLineString ml = (MLineString) this.geometries[0];
if ( !ml.isEmpty() ) {
mdir = ml.getMeasureDirection();
break;
}
}
for ( int i = 0; i < this.geometries.length; i++ ) {
MLineString ml = (MLineString) this.geometries[i];
if ( ml.isEmpty() ) {
continue;
}
// check whether mlinestrings are all pointing in same direction,
// and
// are monotone
if ( !ml.isMonotone( false )
|| ( ml.getMeasureDirection() != mdir && !( ml
.getMeasureDirection() == MGeometry.CONSTANT ) ) ) {
this.monotone = false;
break;
}
if (!ml.isMonotone(true) || (ml.getMeasureDirection() != mdir)) {
this.strictMonotone = false;
break;
}
if ( !ml.isMonotone( true ) || ( ml.getMeasureDirection() != mdir ) ) {
this.strictMonotone = false;
break;
}
// check whether the geometry measures do not overlap or
// are inconsistent with previous parts
if (i > 0) {
MLineString mlp = (MLineString) this.geometries[i - 1];
if (mdir == MGeometry.INCREASING) {
if (mlp.getMaxM() > ml.getMinM()) {
monotone = false;
} else if (mlp.getMaxM() >= ml.getMinM()) {
strictMonotone = false;
}
} else {
if (mlp.getMinM() < ml.getMaxM()) {
monotone = false;
} else if (mlp.getMinM() <= ml.getMaxM()) {
strictMonotone = false;
}
}
// check whether the geometry measures do not overlap or
// are inconsistent with previous parts
if ( i > 0 ) {
MLineString mlp = (MLineString) this.geometries[i - 1];
if ( mdir == MGeometry.INCREASING ) {
if ( mlp.getMaxM() > ml.getMinM() ) {
monotone = false;
}
else if ( mlp.getMaxM() >= ml.getMinM() ) {
strictMonotone = false;
}
}
else {
if ( mlp.getMinM() < ml.getMaxM() ) {
monotone = false;
}
else if ( mlp.getMinM() <= ml.getMaxM() ) {
strictMonotone = false;
}
}
}
}
}
if (!monotone) {
this.strictMonotone = false;
}
}
if ( !monotone ) {
this.strictMonotone = false;
}
}
}
protected void geometryChangedAction() {
determineMonotone();
}
protected void geometryChangedAction() {
determineMonotone();
}
public String getGeometryType() {
return "MultiMLineString";
}
public String getGeometryType() {
return "MultiMLineString";
}
public double getMGap() {
return this.mGap;
}
public double getMGap() {
return this.mGap;
}
public double getMatCoordinate(Coordinate co, double tolerance)
throws MGeometryException {
public double getMatCoordinate(Coordinate co, double tolerance)
throws MGeometryException {
if (!this.isMonotone(false)) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE);
}
if ( !this.isMonotone( false ) ) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE
);
}
double mval = Double.NaN;
double dist = Double.POSITIVE_INFINITY;
double mval = Double.NaN;
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
for (int i = 0; i < this.getNumGeometries(); i++) {
MLineString ml = (MLineString) this.getGeometryN(i);
// go to next MLineString if the input point is beyond tolerance
if (ml.distance(p) > tolerance)
continue;
// find points within tolerance for getMatCoordinate
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN( i );
// go to next MLineString if the input point is beyond tolerance
if ( ml.distance( p ) > tolerance ) {
continue;
}
MCoordinate mc = ml.getClosestPoint(co, tolerance);
if (mc != null) {
double d = mc.distance(co);
if (d <= tolerance && d < dist) {
dist = d;
mval = mc.m;
}
}
}
return mval;
}
MCoordinate mc = ml.getClosestPoint( co, tolerance );
if ( mc != null ) {
double d = mc.distance( co );
if ( d <= tolerance && d < dist ) {
dist = d;
mval = mc.m;
}
}
}
return mval;
}
public Object clone() {
MultiLineString ml = (MultiLineString) super.clone();
return ml;
}
public Object clone() {
MultiLineString ml = (MultiLineString) super.clone();
return ml;
}
public void measureOnLength(boolean keepBeginMeasure) {
double startM = 0.0;
for (int i = 0; i < this.getNumGeometries(); i++) {
MLineString ml = (MLineString) this.getGeometryN(i);
if (i == 0) {
ml.measureOnLength(keepBeginMeasure);
} else {
ml.measureOnLength(false);
}
if (startM != 0.0) {
ml.shiftMeasure(startM);
}
startM += ml.getLength() + mGap;
}
this.geometryChanged();
}
public void measureOnLength(boolean keepBeginMeasure) {
double startM = 0.0;
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN( i );
if ( i == 0 ) {
ml.measureOnLength( keepBeginMeasure );
}
else {
ml.measureOnLength( false );
}
if ( startM != 0.0 ) {
ml.shiftMeasure( startM );
}
startM += ml.getLength() + mGap;
}
this.geometryChanged();
}
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#getCoordinateAtM(double)
*/
/*
* (non-Javadoc)
*
* @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)) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE);
}
if ( !this.isMonotone( false ) ) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE
);
}
Coordinate c = null;
for (int i = 0; i < this.getNumGeometries(); i++) {
MGeometry mg = (MGeometry) this.getGeometryN(i);
c = mg.getCoordinateAtM(m);
if (c != null) {
return c;
}
}
return null;
}
Coordinate c = null;
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MGeometry mg = (MGeometry) this.getGeometryN( i );
c = mg.getCoordinateAtM( m );
if ( c != null ) {
return c;
}
}
return null;
}
public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
throws MGeometryException {
public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
throws MGeometryException {
if (!this.isMonotone(false)) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE,
"Operation requires geometry with monotonic measures");
}
if ( !this.isMonotone( false ) ) {
throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE,
"Operation requires geometry with monotonic measures"
);
}
if (this.isEmpty())
return null;
if ( this.isEmpty() ) {
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++) {
MLineString ml = (MLineString) this.getGeometryN(i);
for (CoordinateSequence cs : ml.getCoordinatesBetween(begin, end)) {
if (cs.size() > 0) {
ar.add(cs);
}
}
}
return ar.toArray(new CoordinateSequence[ar.size()]);
}
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN( i );
for ( CoordinateSequence cs : ml.getCoordinatesBetween( begin, end ) ) {
if ( cs.size() > 0 ) {
ar.add( cs );
}
}
}
return ar.toArray( new CoordinateSequence[ar.size()] );
}
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#getMinM()
*/
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#getMinM()
*/
public double getMinM() {
double minM = Double.POSITIVE_INFINITY;
for (int i = 0; i < this.getNumGeometries(); i++) {
MLineString ml = (MLineString) this.getGeometryN(i);
double d = ml.getMinM();
if (d < minM)
minM = d;
}
return minM;
}
public double getMinM() {
double minM = Double.POSITIVE_INFINITY;
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN( i );
double d = ml.getMinM();
if ( d < minM ) {
minM = d;
}
}
return minM;
}
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#getMaxM()
*/
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#getMaxM()
*/
public double getMaxM() {
double maxM = Double.NEGATIVE_INFINITY;
for (int i = 0; i < this.getNumGeometries(); i++) {
MLineString ml = (MLineString) this.getGeometryN(i);
double d = ml.getMaxM();
if (d > maxM)
maxM = d;
}
return maxM;
}
public double getMaxM() {
double maxM = Double.NEGATIVE_INFINITY;
for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN( i );
double d = ml.getMaxM();
if ( d > maxM ) {
maxM = d;
}
}
return maxM;
}
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#isMonotone()
*/
/*
* (non-Javadoc)
*
* @see org.hibernate.spatial.mgeom.MGeometry#isMonotone()
*/
public boolean isMonotone(boolean strictMonotone) {
return strictMonotone ? this.strictMonotone : monotone;
}
public boolean isMonotone(boolean strictMonotone) {
return strictMonotone ? this.strictMonotone : monotone;
}
public Geometry asGeometry() {
return this;
}
public Geometry asGeometry() {
return this;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -25,186 +25,225 @@
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.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.spatial.criterion.SpatialRestrictions;
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 org.junit.Assert.fail;
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() {
super.prepareTest();
try {
dataSourceUtils.insertTestData(testData);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
protected Logger getLogger() {
return LOGGER;
}
protected Logger getLogger() {
return LOGGER;
}
@Test
public void testRestrictions() throws Exception {
within();
filter();
contains();
crosses();
touches();
disjoint();
eq();
intersects();
overlaps();
dwithin();
havingSRID();
isEmpty();
isNotEmpty();
}
@Test
public void testRestrictions() throws Exception {
within();
filter();
contains();
crosses();
touches();
disjoint();
eq();
intersects();
overlaps();
dwithin();
havingSRID();
isEmpty();
isNotEmpty();
}
public void within() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.within ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.within( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void within() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.within)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.within("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void filter() throws SQLException {
if ( !dialectSupportsFiltering() ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getFilter( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.filter( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void filter() throws SQLException {
if (!dialectSupportsFiltering()) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getFilter(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.filter("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void contains() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.contains ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getContains( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.contains( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void contains() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.contains)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getContains(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.contains("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void crosses() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.crosses ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.crosses( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void crosses() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.crosses)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.crosses("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void touches() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.touches ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.touches( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void touches() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.touches)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.touches("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void disjoint() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.disjoint ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.disjoint( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void disjoint() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.disjoint)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.disjoint("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void eq() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.equals ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.eq( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void eq() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.equals)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.eq("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void intersects() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.intersects ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.intersects( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void intersects() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.intersects)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.intersects("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void overlaps() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.overlaps ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps( expectationsFactory.getTestPolygon() );
Criterion spatialCriterion = SpatialRestrictions.overlaps( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void overlaps() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.overlaps)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps(expectationsFactory.getTestPolygon());
Criterion spatialCriterion = SpatialRestrictions.overlaps("geom", expectationsFactory.getTestPolygon());
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void dwithin() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.dwithin ) ) {
return;
}
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 {
if (!isSupportedByDialect(SpatialFunction.dwithin)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getDwithin(expectationsFactory.getTestPoint(), 30.0);
Criterion spatialCriterion = SpatialRestrictions.distanceWithin("geom", expectationsFactory.getTestPoint(), 30.0);
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void isEmpty() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.isempty ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty();
Criterion spatialCriterion = SpatialRestrictions.isEmpty( "geom" );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void isEmpty() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.isempty)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty();
Criterion spatialCriterion = SpatialRestrictions.isEmpty("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 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 {
if (!isSupportedByDialect(SpatialFunction.srid)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.havingSRID(4326);
Criterion spatialCriterion = SpatialRestrictions.havingSRID("geom", 4326);
retrieveAndCompare(dbexpected, spatialCriterion);
dbexpected = expectationsFactory.havingSRID(31370);
spatialCriterion = SpatialRestrictions.havingSRID("geom", 31370);
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void havingSRID() throws SQLException {
if ( !isSupportedByDialect( SpatialFunction.srid ) ) {
return;
}
Map<Integer, Boolean> dbexpected = expectationsFactory.havingSRID( 4326 );
Criterion spatialCriterion = SpatialRestrictions.havingSRID( "geom", 4326 );
retrieveAndCompare( dbexpected, spatialCriterion );
dbexpected = expectationsFactory.havingSRID( 31370 );
spatialCriterion = SpatialRestrictions.havingSRID( "geom", 31370 );
retrieveAndCompare( dbexpected, spatialCriterion );
}
private void retrieveAndCompare(Map<Integer, Boolean> dbexpected, Criterion spatialCriterion) {
Session session = null;
Transaction tx = null;
try {
session = openSession();
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(GeomEntity.class);
criteria.add(spatialCriterion);
compare(dbexpected, criteria.list());
} finally {
if (tx != null) tx.rollback();
if (session != null) session.close();
}
}
private void retrieveAndCompare(Map<Integer, Boolean> dbexpected, Criterion spatialCriterion) {
Session session = null;
Transaction tx = null;
try {
session = openSession();
tx = session.beginTransaction();
Criteria criteria = session.createCriteria( GeomEntity.class );
criteria.add( spatialCriterion );
compare( dbexpected, criteria.list() );
}
finally {
if ( tx != null ) {
tx.rollback();
}
if ( session != null ) {
session.close();
}
}
}
private void compare(Map<Integer, Boolean> dbexpected, List list) {
int cnt = 0;
for (Integer id : dbexpected.keySet()) {
if (dbexpected.get(id)) {
cnt++;
if (!findInList(id, (List<GeomEntity>) list))
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));
}
private void compare(Map<Integer, Boolean> dbexpected, List list) {
int cnt = 0;
for ( Integer id : dbexpected.keySet() ) {
if ( dbexpected.get( id ) ) {
cnt++;
if ( !findInList( id, (List<GeomEntity>) list ) ) {
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 ) );
}
private boolean findInList(Integer id, List<GeomEntity> list) {
for (GeomEntity entity : list) {
if (entity.getId() == id) return true;
}
return false;
}
private boolean findInList(Integer id, List<GeomEntity> list) {
for ( GeomEntity entity : list ) {
if ( entity.getId() == id ) {
return true;
}
}
return false;
}
}

View File

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

View File

@ -10,38 +10,42 @@
*/
public class TestSupportFactories {
private static TestSupportFactories instance = new TestSupportFactories();
private static TestSupportFactories instance = new TestSupportFactories();
public static TestSupportFactories instance() {
return instance;
}
public static TestSupportFactories instance() {
return instance;
}
private TestSupportFactories() {
}
private TestSupportFactories() {
}
public TestSupport getTestSupportFactory(Dialect dialect) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
if (dialect == null) throw new IllegalArgumentException("Dialect argument is required.");
String testSupportFactoryClassName = getSupportFactoryClassName(dialect);
return instantiate(testSupportFactoryClassName);
public TestSupport getTestSupportFactory(Dialect dialect)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
if ( dialect == null ) {
throw new IllegalArgumentException( "Dialect argument is required." );
}
String testSupportFactoryClassName = getSupportFactoryClassName( dialect );
return instantiate( testSupportFactoryClassName );
}
}
private TestSupport instantiate(String testSupportFactoryClassName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
ClassLoader cloader = getClassLoader();
Class<TestSupport> cl = (Class<TestSupport>) (cloader.loadClass(testSupportFactoryClassName));
return cl.newInstance();
}
private TestSupport instantiate(String testSupportFactoryClassName)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
ClassLoader cloader = getClassLoader();
Class<TestSupport> cl = (Class<TestSupport>) ( cloader.loadClass( testSupportFactoryClassName ) );
return cl.newInstance();
}
private ClassLoader getClassLoader() {
return this.getClass().getClassLoader();
}
private ClassLoader getClassLoader() {
return this.getClass().getClassLoader();
}
private static String getSupportFactoryClassName(Dialect dialect) {
String canonicalName = dialect.getClass().getCanonicalName();
if ("org.hibernate.spatial.dialect.postgis.PostgisDialect".equals(canonicalName)) {
return "org.hibernate.spatial.dialect.postgis.PostgisTestSupport";
}
private static String getSupportFactoryClassName(Dialect dialect) {
String canonicalName = dialect.getClass().getCanonicalName();
if ( "org.hibernate.spatial.dialect.postgis.PostgisDialect".equals( canonicalName ) ) {
return "org.hibernate.spatial.dialect.postgis.PostgisTestSupport";
}
// if ("org.hibernate.spatial.geodb.GeoDBDialect".equals(canonicalName)) {
// return "org.hibernate.spatial.geodb.GeoDBSupport";
// }
@ -55,8 +59,8 @@ private static String getSupportFactoryClassName(Dialect dialect) {
// if ("org.hibernatespatial.oracle.OracleSpatial10gDialect".equals(canonicalName)) {
// 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 {
@Test
public void testConfigureFailure() {
HSConfiguration config = new HSConfiguration();
config.configure("non-existing-file");
}
@Test
public void testConfigureFailure() {
HSConfiguration config = new HSConfiguration();
config.configure( "non-existing-file" );
}
@Test
public void testConfigureFile() {
HSConfiguration config = new HSConfiguration();
config.configure("test.cfg.xml");
testResults(config);
}
@Test
public void testConfigureFile() {
HSConfiguration config = new HSConfiguration();
config.configure( "test.cfg.xml" );
testResults( config );
}
private void testResults(HSConfiguration config) {
assertEquals("org.hibernate.spatial.postgis.PostgisDialect", config
.getDefaultDialect());
assertEquals("FIXED", config.getPrecisionModel());
assertEquals("5", config.getPrecisionModelScale());
}
private void testResults(HSConfiguration config) {
assertEquals(
"org.hibernate.spatial.postgis.PostgisDialect", config
.getDefaultDialect()
);
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.Point;
import org.hibernate.spatial.test.AbstractExpectationsFactory;
import org.hibernate.spatial.test.DataSourceUtils;
import org.hibernate.spatial.test.NativeSQLStatement;
@ -38,199 +39,217 @@
*/
public class PostgisExpectationsFactory extends AbstractExpectationsFactory {
private final PGGeometryValueExtractor decoder = new PGGeometryValueExtractor();
private final PGGeometryValueExtractor decoder = new PGGeometryValueExtractor();
public PostgisExpectationsFactory(DataSourceUtils utils) {
super(utils);
}
public PostgisExpectationsFactory(DataSourceUtils utils) {
super( utils );
}
@Override
protected NativeSQLStatement createNativeTouchesStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeTouchesStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeOverlapsStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeOverlapsStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
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";
return createNativeSQLStatementAllWKTParams(sql, geom.toText());
}
@Override
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";
return createNativeSQLStatementAllWKTParams( sql, geom.toText() );
}
@Override
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";
return createNativeSQLStatementAllWKTParams(sql, geom.toText());
}
@Override
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";
return createNativeSQLStatementAllWKTParams( sql, geom.toText() );
}
@Override
protected NativeSQLStatement createNativeIntersectsStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeIntersectsStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeFilterStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeFilterStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeDistanceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_distance(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeDistanceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_distance(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeDimensionSQL() {
return createNativeSQLStatement("select id, st_dimension(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeDimensionSQL() {
return createNativeSQLStatement( "select id, st_dimension(geom) from geomtest" );
}
@Override
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});
}
@Override
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 }
);
}
@Override
protected NativeSQLStatement createNativeConvexHullStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_convexhull(st_union(t.geom, ST_GeomFromText(?, 4326))) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeConvexHullStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_convexhull(st_union(t.geom, ST_GeomFromText(?, 4326))) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeIntersectionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_intersection(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeIntersectionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_intersection(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_difference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_difference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeSymDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_symdifference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeSymDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_symdifference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeGeomUnionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_union(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeGeomUnionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams(
"select t.id, st_union(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeTransformStatement(int epsg) {
return createNativeSQLStatement(
"select t.id, st_transform(t.geom," + epsg + ") from GeomTest t where ST_SRID(t.geom) = 4326"
);
}
@Override
protected NativeSQLStatement createNativeTransformStatement(int epsg) {
return createNativeSQLStatement(
"select t.id, st_transform(t.geom," + epsg + ") from GeomTest t where ST_SRID(t.geom) = 4326"
);
}
@Override
protected NativeSQLStatement createNativeHavingSRIDStatement(int srid) {
return createNativeSQLStatement("select t.id, (st_srid(t.geom) = " + srid + ") from GeomTest t where ST_SRID(t.geom) = " + srid);
}
@Override
protected NativeSQLStatement createNativeHavingSRIDStatement(int srid) {
return createNativeSQLStatement( "select t.id, (st_srid(t.geom) = " + srid + ") from GeomTest t where ST_SRID(t.geom) = " + srid );
}
@Override
protected NativeSQLStatement createNativeAsTextStatement() {
return createNativeSQLStatement("select id, st_astext(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeAsTextStatement() {
return createNativeSQLStatement( "select id, st_astext(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeSridStatement() {
return createNativeSQLStatement("select id, ST_SRID(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeSridStatement() {
return createNativeSQLStatement( "select id, ST_SRID(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeIsSimpleStatement() {
return createNativeSQLStatement("select id, st_issimple(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeIsSimpleStatement() {
return createNativeSQLStatement( "select id, st_issimple(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeIsEmptyStatement() {
return createNativeSQLStatement("select id, st_isempty(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeIsEmptyStatement() {
return createNativeSQLStatement( "select id, st_isempty(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeIsNotEmptyStatement() {
return createNativeSQLStatement("select id, not st_isempty(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeIsNotEmptyStatement() {
return createNativeSQLStatement( "select id, not st_isempty(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeBoundaryStatement() {
return createNativeSQLStatement("select id, st_boundary(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeBoundaryStatement() {
return createNativeSQLStatement( "select id, st_boundary(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeEnvelopeStatement() {
return createNativeSQLStatement("select id, st_envelope(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeEnvelopeStatement() {
return createNativeSQLStatement( "select id, st_envelope(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeAsBinaryStatement() {
return createNativeSQLStatement("select id, st_asbinary(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeAsBinaryStatement() {
return createNativeSQLStatement( "select id, st_asbinary(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeGeometryTypeStatement() {
return createNativeSQLStatement("select id, st_GeometryType(geom) from geomtest");
}
@Override
protected NativeSQLStatement createNativeGeometryTypeStatement() {
return createNativeSQLStatement( "select id, st_GeometryType(geom) from geomtest" );
}
@Override
protected NativeSQLStatement createNativeWithinStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeWithinStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeEqualsStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeEqualsStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeCrossesStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeCrossesStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeContainsStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeContainsStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected NativeSQLStatement createNativeDisjointStatement(Geometry geom) {
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",
geom.toText());
}
@Override
protected NativeSQLStatement createNativeDisjointStatement(Geometry geom) {
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",
geom.toText()
);
}
@Override
protected Geometry decode(Object o) {
return decoder.toJTS(o);
}
@Override
protected Geometry decode(Object o) {
return decoder.toJTS( o );
}
}

View File

@ -35,9 +35,15 @@
*/
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) {
return String.format(SQL_TEMPLATE, testDataElement.id, testDataElement.type, testDataElement.wkt, testDataElement.srid);
}
public String toInsertSql(TestDataElement testDataElement) {
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;
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;
/**
@ -11,22 +15,22 @@
public class PostgisTestSupport extends TestSupport {
public TestData createTestData(BaseCoreFunctionalTestCase testcase) {
if (testcase.getClass().getCanonicalName().contains("TestSpatialFunctions") ||
testcase.getClass().getCanonicalName().contains("TestSpatialRestrictions")) {
return TestData.fromFile("postgis-functions-test.xml");
}
return TestData.fromFile("test-data-set.xml");
}
public TestData createTestData(BaseCoreFunctionalTestCase testcase) {
if ( testcase.getClass().getCanonicalName().contains( "TestSpatialFunctions" ) ||
testcase.getClass().getCanonicalName().contains( "TestSpatialRestrictions" ) ) {
return TestData.fromFile( "postgis-functions-test.xml" );
}
return TestData.fromFile( "test-data-set.xml" );
}
public AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils) {
return new PostgisExpectationsFactory(dataSourceUtils);
}
public AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils) {
return new PostgisExpectationsFactory( dataSourceUtils );
}
@Override
public SQLExpressionTemplate getSQLExpressionTemplate() {
return new org.hibernate.spatial.dialect.postgis.PostgisExpressionTemplate();
}
@Override
public SQLExpressionTemplate getSQLExpressionTemplate() {
return new org.hibernate.spatial.dialect.postgis.PostgisExpressionTemplate();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -29,10 +29,14 @@
package org.hibernate.spatial.test;
import com.vividsolutions.jts.geom.Coordinate;
import org.hibernate.spatial.Circle;
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
@ -41,156 +45,164 @@
*/
public class TestCircle {
@Test
public void testCreateCircle() {
@Test
public void testCreateCircle() {
Coordinate center = (new Coordinate(0, 0));
double radius = 5;
Coordinate center = ( new Coordinate( 0, 0 ) );
double radius = 5;
Coordinate p1 = new Coordinate(3, 4);
Coordinate p2 = new Coordinate(0, 5);
Coordinate p3 = new Coordinate(-3, 4);
Coordinate p1 = new Coordinate( 3, 4 );
Coordinate p2 = new Coordinate( 0, 5 );
Coordinate p3 = new Coordinate( -3, 4 );
Circle c0 = new Circle(center, radius);
Circle c1 = new Circle(p1, p2, p3);
assertEquals(c0, c1);
Circle c0 = new Circle( center, radius );
Circle c1 = new Circle( p1, p2, p3 );
assertEquals( c0, c1 );
assertTrue(Double.compare(c1.getRadius(), radius) == 0);
assertTrue(c1.getCenter().equals2D(center));
assertTrue( Double.compare( c1.getRadius(), radius ) == 0 );
assertTrue( c1.getCenter().equals2D( center ) );
double distance = c1.distanceFromCenter(p3);
assertTrue(Double.compare(c1.getRadius(), distance) == 0);
}
double distance = c1.distanceFromCenter( p3 );
assertTrue( Double.compare( c1.getRadius(), distance ) == 0 );
}
@Test
public void testNormalize() {
double actual, expected = 0;
@Test
public void testNormalize() {
double actual, expected = 0;
double angleIncr = Math.PI / 4; // increment by 45 degrees
double twoPi = Math.PI * 2;
int factor = 8;
for (int i = 0; i <= factor; i++) {
expected = i * angleIncr;
actual = (Circle.normalizeAngle(expected));
assertEquals(actual, expected, Math.ulp(expected));
double degrees = Math.toDegrees(actual);
assertTrue(actual <= twoPi);
assertTrue(degrees <= 360);
}
double angleIncr = Math.PI / 4; // increment by 45 degrees
double twoPi = Math.PI * 2;
int factor = 8;
for ( int i = 0; i <= factor; i++ ) {
expected = i * angleIncr;
actual = ( Circle.normalizeAngle( expected ) );
assertEquals( actual, expected, Math.ulp( expected ) );
double degrees = Math.toDegrees( actual );
assertTrue( actual <= twoPi );
assertTrue( degrees <= 360 );
}
factor = -8;
double testAngle;
for (int i = -1; i >= factor; i--) {
testAngle = i * angleIncr;
expected = twoPi + (i * angleIncr);
actual = (Circle.normalizeAngle(testAngle));
assertEquals(actual, expected, Math.ulp(expected));
double degrees = Math.toDegrees(actual);
assertTrue(actual <= Math.PI * 2);
assertTrue(degrees <= 360);
}
factor = -8;
double testAngle;
for ( int i = -1; i >= factor; i-- ) {
testAngle = i * angleIncr;
expected = twoPi + ( i * angleIncr );
actual = ( Circle.normalizeAngle( testAngle ) );
assertEquals( actual, expected, Math.ulp( expected ) );
double degrees = Math.toDegrees( actual );
assertTrue( actual <= Math.PI * 2 );
assertTrue( degrees <= 360 );
}
// couple extra boundary cases
expected = 0;
actual = Circle.normalizeAngle(twoPi * 8);
assertEquals(expected, actual, Math.ulp(expected));
// couple extra boundary cases
expected = 0;
actual = Circle.normalizeAngle( twoPi * 8 );
assertEquals( expected, actual, Math.ulp( expected ) );
testAngle = angleIncr + twoPi;
expected = angleIncr;
actual = Circle.normalizeAngle(testAngle);
assertEquals(expected, actual, Math.ulp(expected));
testAngle = angleIncr + twoPi;
expected = angleIncr;
actual = Circle.normalizeAngle( testAngle );
assertEquals( expected, actual, Math.ulp( expected ) );
testAngle = angleIncr - twoPi;
expected = angleIncr;
actual = Circle.normalizeAngle(testAngle);
assertEquals(expected, actual, Math.ulp(expected));
}
testAngle = angleIncr - twoPi;
expected = angleIncr;
actual = Circle.normalizeAngle( testAngle );
assertEquals( expected, actual, Math.ulp( expected ) );
}
@Test
public void testAngleDifference() {
double a1 = Math.PI / 8;
double a2 = Math.PI / 4;
@Test
public void testAngleDifference() {
double a1 = Math.PI / 8;
double a2 = Math.PI / 4;
double diff = Circle.subtractAngles(a1, a2);
assertTrue(diff < Math.PI);
double diff = Circle.subtractAngles( a1, a2 );
assertTrue( diff < Math.PI );
diff = Circle.subtractAngles(a2, a1);
assertTrue(diff > Math.PI);
}
diff = Circle.subtractAngles( a2, a1 );
assertTrue( diff > Math.PI );
}
@Test
public void testMajorArc() {
Coordinate expectedCenter = new Coordinate(3, 0);
double expectedRadius = 5;
Coordinate p1 = new Coordinate(0, 4);
Coordinate p2 = new Coordinate(8, 0);
Coordinate p3 = new Coordinate(0, -4);
Circle c = new Circle(p1, p2, p3);
@Test
public void testMajorArc() {
Coordinate expectedCenter = new Coordinate( 3, 0 );
double expectedRadius = 5;
Coordinate p1 = new Coordinate( 0, 4 );
Coordinate p2 = new Coordinate( 8, 0 );
Coordinate p3 = new Coordinate( 0, -4 );
Circle c = new Circle( p1, p2, p3 );
assertTrue(c.getCenter().equals2D(expectedCenter));
assertTrue(Double.compare(c.getRadius(), expectedRadius) == 0);
}
assertTrue( c.getCenter().equals2D( expectedCenter ) );
assertTrue( Double.compare( c.getRadius(), expectedRadius ) == 0 );
}
@Test
public void testArcDirection() {
Coordinate[] coords = new Coordinate[]{new Coordinate(0, 5),
new Coordinate(3, 4), new Coordinate(5, 0),
new Coordinate(3, -4), new Coordinate(0, -5),
new Coordinate(-3, -4), new Coordinate(-5, 0),
new Coordinate(-3, 4)};
for (int i = 0; i < coords.length; i++) {
Coordinate p1 = coords[i];
Coordinate p2 = coords[(i + 1) % coords.length];
Coordinate p3 = coords[(i + 2) % coords.length];
Circle c = new Circle(p1, p2, p3);
Circle.Arc a = c.createArc(p1, p2, p3);
assertTrue("Failed Points:" + p1 + ", " + p2 + ", " + p3, a
.isClockwise());
}
@Test
public void testArcDirection() {
Coordinate[] coords = new Coordinate[] {
new Coordinate( 0, 5 ),
new Coordinate( 3, 4 ), new Coordinate( 5, 0 ),
new Coordinate( 3, -4 ), new Coordinate( 0, -5 ),
new Coordinate( -3, -4 ), new Coordinate( -5, 0 ),
new Coordinate( -3, 4 )
};
for ( int i = 0; i < coords.length; i++ ) {
Coordinate p1 = coords[i];
Coordinate p2 = coords[( i + 1 ) % coords.length];
Coordinate p3 = coords[( i + 2 ) % coords.length];
Circle c = new Circle( p1, p2, p3 );
Circle.Arc a = c.createArc( p1, p2, p3 );
assertTrue(
"Failed Points:" + p1 + ", " + p2 + ", " + p3, a
.isClockwise()
);
}
for (int i = 0; i < coords.length; i++) {
Coordinate p3 = coords[i];
Coordinate p2 = coords[(i + 1) % coords.length];
Coordinate p1 = coords[(i + 2) % coords.length];
Circle c = new Circle(p1, p2, p3);
Circle.Arc a = c.createArc(p1, p2, p3);
assertFalse("Failed Points:" + p1 + ", " + p2 + ", " + p3, a
.isClockwise());
}
}
for ( int i = 0; i < coords.length; i++ ) {
Coordinate p3 = coords[i];
Coordinate p2 = coords[( i + 1 ) % coords.length];
Coordinate p1 = coords[( i + 2 ) % coords.length];
Circle c = new Circle( p1, p2, p3 );
Circle.Arc a = c.createArc( p1, p2, p3 );
assertFalse(
"Failed Points:" + p1 + ", " + p2 + ", " + p3, a
.isClockwise()
);
}
}
@Test
public void testLinearize() {
Coordinate p1 = new Coordinate(5, 0);
Coordinate p2 = new Coordinate(4, 3);
Coordinate p3 = new Coordinate(4, -3);
@Test
public void testLinearize() {
Coordinate p1 = new Coordinate( 5, 0 );
Coordinate p2 = 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);
assertTrue(results.length > 0);
for (Coordinate coord : results) {
double error = c.getRadius() - c.distanceFromCenter(coord);
assertTrue(Double.compare(error, 0.0001) < 0);
}
}
assertNotNull( results );
assertTrue( results.length > 0 );
for ( Coordinate coord : results ) {
double error = c.getRadius() - c.distanceFromCenter( coord );
assertTrue( Double.compare( error, 0.0001 ) < 0 );
}
}
@Test
public void testLinearizeCircle() {
Coordinate p1 = new Coordinate(5, 0);
Coordinate p2 = new Coordinate(4, 3);
Coordinate p3 = new Coordinate(4, -3);
@Test
public void testLinearizeCircle() {
Coordinate p1 = new Coordinate( 5, 0 );
Coordinate p2 = new Coordinate( 4, 3 );
Coordinate p3 = new Coordinate( 4, -3 );
Circle c = new Circle(p1, p2, p3);
Coordinate[] results = c.linearizeArc(p1, p2, p1,
(c.getRadius() * 0.01));
for (Coordinate coord : results) {
double error = c.getRadius() - c.distanceFromCenter(coord);
assertTrue(Double.compare(error, 0.0001) < 0);
}
Circle c = new Circle( p1, p2, p3 );
Coordinate[] results = c.linearizeArc(
p1, p2, p1,
( c.getRadius() * 0.01 )
);
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> {
private List<TestDataElement> testDataElements;
private InputStream in;
private List<TestDataElement> testDataElements;
private InputStream in;
protected TestData() {
}
protected TestData() {
}
;
;
public int size() {
return testDataElements.size();
}
public int size() {
return testDataElements.size();
}
public boolean isEmpty() {
return testDataElements.isEmpty();
}
public boolean isEmpty() {
return testDataElements.isEmpty();
}
public boolean contains(Object o) {
return testDataElements.contains(o);
}
public boolean contains(Object o) {
return testDataElements.contains( o );
}
public Iterator<TestDataElement> iterator() {
return testDataElements.iterator();
}
public Iterator<TestDataElement> iterator() {
return testDataElements.iterator();
}
public Object[] toArray() {
return testDataElements.toArray();
}
public Object[] toArray() {
return testDataElements.toArray();
}
public <T> T[] toArray(T[] a) {
return testDataElements.toArray(a);
}
public <T> T[] toArray(T[] a) {
return testDataElements.toArray( a );
}
public boolean add(TestDataElement testDataElement) {
return testDataElements.add(testDataElement);
}
public boolean add(TestDataElement testDataElement) {
return testDataElements.add( testDataElement );
}
public boolean remove(Object o) {
return testDataElements.remove(o);
}
public boolean remove(Object o) {
return testDataElements.remove( o );
}
public boolean containsAll(Collection<?> c) {
return testDataElements.containsAll(c);
}
public boolean containsAll(Collection<?> c) {
return testDataElements.containsAll( c );
}
public boolean addAll(Collection<? extends TestDataElement> c) {
return testDataElements.addAll(c);
}
public boolean addAll(Collection<? extends TestDataElement> c) {
return testDataElements.addAll( c );
}
public boolean addAll(int index, Collection<? extends TestDataElement> c) {
return testDataElements.addAll(index, c);
}
public boolean addAll(int index, Collection<? extends TestDataElement> c) {
return testDataElements.addAll( index, c );
}
public boolean removeAll(Collection<?> c) {
return testDataElements.removeAll(c);
}
public boolean removeAll(Collection<?> c) {
return testDataElements.removeAll( c );
}
public boolean retainAll(Collection<?> c) {
return testDataElements.retainAll(c);
}
public boolean retainAll(Collection<?> c) {
return testDataElements.retainAll( c );
}
public void clear() {
testDataElements.clear();
}
public void clear() {
testDataElements.clear();
}
public boolean equals(Object o) {
return testDataElements.equals(o);
}
public boolean equals(Object o) {
return testDataElements.equals( o );
}
public int hashCode() {
return testDataElements.hashCode();
}
public int hashCode() {
return testDataElements.hashCode();
}
public TestDataElement get(int index) {
return testDataElements.get(index);
}
public TestDataElement get(int index) {
return testDataElements.get( index );
}
public TestDataElement set(int index, TestDataElement element) {
return testDataElements.set(index, element);
}
public TestDataElement set(int index, TestDataElement element) {
return testDataElements.set( index, element );
}
public void add(int index, TestDataElement element) {
testDataElements.add(index, element);
}
public void add(int index, TestDataElement element) {
testDataElements.add( index, element );
}
public TestDataElement remove(int index) {
return testDataElements.remove(index);
}
public TestDataElement remove(int index) {
return testDataElements.remove( index );
}
public int indexOf(Object o) {
return testDataElements.indexOf(o);
}
public int indexOf(Object o) {
return testDataElements.indexOf( o );
}
public int lastIndexOf(Object o) {
return testDataElements.lastIndexOf(o);
}
public int lastIndexOf(Object o) {
return testDataElements.lastIndexOf( o );
}
public ListIterator<TestDataElement> listIterator() {
return testDataElements.listIterator();
}
public ListIterator<TestDataElement> listIterator() {
return testDataElements.listIterator();
}
public ListIterator<TestDataElement> listIterator(int index) {
return testDataElements.listIterator(index);
}
public ListIterator<TestDataElement> listIterator(int index) {
return testDataElements.listIterator( index );
}
public List<TestDataElement> subList(int fromIndex, int toIndex) {
return testDataElements.subList(fromIndex, toIndex);
}
public List<TestDataElement> subList(int fromIndex, int toIndex) {
return testDataElements.subList( fromIndex, toIndex );
}
public static TestData fromFile(String fileName) {
TestDataReader reader = new TestDataReader();
return fromFile(fileName, reader);
}
public static TestData fromFile(String fileName) {
TestDataReader reader = new TestDataReader();
return fromFile( fileName, reader );
}
public static TestData fromFile(String fileName, TestDataReader reader) {
List<TestDataElement> elements = reader.read(fileName);
TestData testData = new TestData();
testData.testDataElements = elements;
return testData;
}
public static TestData fromFile(String fileName, TestDataReader reader) {
List<TestDataElement> elements = reader.read( fileName );
TestData testData = new TestData();
testData.testDataElements = elements;
return testData;
}
}

View File

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

View File

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

View File

@ -11,12 +11,12 @@
*/
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 {
protected Configuration configuration;
protected Configuration configuration;
public DataSourceUtils createDataSourceUtil(Configuration configuration) {
this.configuration = configuration;
return new DataSourceUtils(driver(), url(), user(), passwd(), getSQLExpressionTemplate());
}
public DataSourceUtils createDataSourceUtil(Configuration configuration) {
this.configuration = configuration;
return new DataSourceUtils( driver(), url(), user(), passwd(), getSQLExpressionTemplate() );
}
public GeometryEquality createGeometryEquality() {
return new GeometryEquality();
}
public GeometryEquality createGeometryEquality() {
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() {
return configuration.getProperty("hibernate.connection.driver_class");
}
protected String driver() {
return configuration.getProperty( "hibernate.connection.driver_class" );
}
protected String url() {
return configuration.getProperty("hibernate.connection.url");
}
protected String url() {
return configuration.getProperty( "hibernate.connection.url" );
}
protected String user() {
return configuration.getProperty("hibernate.connection.username");
}
protected String user() {
return configuration.getProperty( "hibernate.connection.username" );
}
protected String passwd() {
return configuration.getProperty("hibernate.connection.password");
}
protected String passwd() {
return configuration.getProperty( "hibernate.connection.password" );
}
}

View File

@ -32,6 +32,7 @@
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.GeometryFactory;
import junit.framework.TestCase;
import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MCoordinateSequenceFactory;
import org.hibernate.spatial.mgeom.MLineString;
@ -42,144 +43,164 @@
*/
public class MultiMLineStringTest extends TestCase {
private final MCoordinateSequenceFactory mcfactory = MCoordinateSequenceFactory
.instance();
private final MCoordinateSequenceFactory mcfactory = MCoordinateSequenceFactory
.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) {
junit.textui.TestRunner.run(MultiMLineStringTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run( MultiMLineStringTest.class );
}
/*
* @see TestCase#setUp()
*/
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
protected void setUp() throws Exception {
super.setUp();
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 mc2 = new MCoordinate(1.0, 1.0, 0.0, 0.2);
MCoordinate mc3 = new MCoordinate(5.0, 1.0, 0.0, 0.3);
MCoordinate mc4 = new MCoordinate(5.0, 3.0, 0.0, 0.4);
lastco = mc4;
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 mc2 = new MCoordinate( 1.0, 1.0, 0.0, 0.2 );
MCoordinate mc3 = new MCoordinate( 5.0, 1.0, 0.0, 0.3 );
MCoordinate mc4 = new MCoordinate( 5.0, 3.0, 0.0, 0.4 );
lastco = mc4;
MCoordinate[] m1 = {mc0, mc1, mc2};
MCoordinate[] m2 = {mc3, mc4};
MCoordinate[] m1 = { mc0, mc1, mc2 };
MCoordinate[] m2 = { mc3, mc4 };
CoordinateSequence mseq1 = mcfactory.create(m1);
ml1 = new MLineString(mseq1, geomfactory);
CoordinateSequence mseq1 = mcfactory.create( m1 );
ml1 = new MLineString( mseq1, geomfactory );
CoordinateSequence mseq2 = mcfactory.create(m2);
ml2 = new MLineString(mseq2, geomfactory);
CoordinateSequence mseq2 = mcfactory.create( m2 );
ml2 = new MLineString( mseq2, geomfactory );
mmsimple = new MultiMLineString(new MLineString[]{ml1}, 0.1,
geomfactory);
mm1 = new MultiMLineString(new MLineString[]{ml1, ml2}, 0.1,
geomfactory);
mmsimple = new MultiMLineString(
new MLineString[] { ml1 }, 0.1,
geomfactory
);
mm1 = new MultiMLineString(
new MLineString[] { ml1, ml2 }, 0.1,
geomfactory
);
}
}
/*
* @see TestCase#tearDown()
*/
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testMaxM() {
assertEquals(0.4, mm1.getMaxM(), 0.000001);
}
public void testMaxM() {
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() {
assertTrue("wrong type reported", mm1.getGeometryType()
.equalsIgnoreCase("multimlinestring"));
}
public void testGetGeometryType() {
assertTrue(
"wrong type reported", mm1.getGeometryType()
.equalsIgnoreCase( "multimlinestring" )
);
}
public void testGetDimension() {
// TODO Implement getDimension().
}
public void testGetDimension() {
// TODO Implement getDimension().
}
public void testGetBoundary() {
// TODO Implement getBoundary().
}
public void testGetBoundary() {
// TODO Implement getBoundary().
}
public void testGetBoundaryDimension() {
// TODO Implement getBoundaryDimension().
}
public void testGetBoundaryDimension() {
// TODO Implement getBoundaryDimension().
}
/*
* Class under testsuite-suite for boolean
* equalsExact(com.vividsolutions.jts.geom.Geometry, double)
*/
/*
* Class under testsuite-suite for boolean
* equalsExact(com.vividsolutions.jts.geom.Geometry, double)
*/
public void testEqualsExactGeometrydouble() {
// TODO Implement equalsExact().
}
public void testEqualsExactGeometrydouble() {
// TODO Implement equalsExact().
}
/*
* Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.PrecisionModel, int)
*/
/*
* Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.PrecisionModel, int)
*/
public void testMultiLineStringLineStringArrayPrecisionModelint() {
// TODO Implement MultiLineString().
}
public void testMultiLineStringLineStringArrayPrecisionModelint() {
// TODO Implement MultiLineString().
}
/*
* Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.GeometryFactory)
*/
/*
* Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.GeometryFactory)
*/
public void testMultiLineStringLineStringArrayGeometryFactory() {
// TODO Implement MultiLineString().
}
public void testMultiLineStringLineStringArrayGeometryFactory() {
// TODO Implement MultiLineString().
}
public void testIsClosed() {
// TODO Implement isClosed().
}
public void testIsClosed() {
// TODO Implement isClosed().
}
public void testClone() {
// TODO implement
public void testClone() {
// TODO implement
}
}
public void testInterpolate() {
mm1.measureOnLength(false);
Coordinate[] ca = mm1.getCoordinates();
assertTrue("co 0 not OK", ((MCoordinate) ca[0]).m == 0.0);
assertTrue("co 1 not OK",
Math.abs(((MCoordinate) ca[1]).m - 1.0) < 0.00001);
assertTrue("co 2 not OK",
Math.abs(((MCoordinate) ca[2]).m - 2.0) < 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);
public void testInterpolate() {
mm1.measureOnLength( false );
Coordinate[] ca = mm1.getCoordinates();
assertTrue( "co 0 not OK", ( (MCoordinate) ca[0] ).m == 0.0 );
assertTrue(
"co 1 not OK",
Math.abs( ( (MCoordinate) ca[1] ).m - 1.0 ) < 0.00001
);
assertTrue(
"co 2 not OK",
Math.abs( ( (MCoordinate) ca[2] ).m - 2.0 ) < 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();
dist += (mm1.getNumGeometries() - 1) * mm1.getMGap();
assertTrue("interpolation not consistent with distance", Math
.abs(((MCoordinate) ca[4]).m - dist) < 0.00001);
double dist = mm1.getLength();
dist += ( mm1.getNumGeometries() - 1 ) * mm1.getMGap();
assertTrue(
"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.PrecisionModel;
import org.hibernate.spatial.mgeom.*;
import org.junit.Before;
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 org.junit.Assert.assertNotNull;
public class TestEventLocator {
private PrecisionModel prec = new PrecisionModel(PrecisionModel.FIXED);
private PrecisionModel prec = new PrecisionModel( PrecisionModel.FIXED );
private MGeometryFactory mgeomFactory = new MGeometryFactory(
MCoordinateSequenceFactory.instance());
private MGeometryFactory mgeomFactory = new MGeometryFactory(
MCoordinateSequenceFactory.instance()
);
private MultiMLineString incrML;
private MultiMLineString incrML;
@Before
public void setUp() {
@Before
public void setUp() {
MCoordinate[] coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0),
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0),
MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0),
MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0)
};
MLineString line1 = mgeomFactory.createMLineString(coordinates);
MCoordinate[] coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ),
MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ),
MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 )
};
MLineString line1 = mgeomFactory.createMLineString( coordinates );
MCoordinate[] coordinates2 = new MCoordinate[]{
MCoordinate.create2dWithMeasure(5.0, 0.0, 5.0),
MCoordinate.create2dWithMeasure(6.0, 0.0, 6.0),
MCoordinate.create2dWithMeasure(7.0, 0.0, 7.0),
};
MLineString line2 = mgeomFactory.createMLineString(coordinates2);
MCoordinate[] coordinates2 = new MCoordinate[] {
MCoordinate.create2dWithMeasure( 5.0, 0.0, 5.0 ),
MCoordinate.create2dWithMeasure( 6.0, 0.0, 6.0 ),
MCoordinate.create2dWithMeasure( 7.0, 0.0, 7.0 ),
};
MLineString line2 = mgeomFactory.createMLineString( coordinates2 );
MCoordinate[] coordinates3 = new MCoordinate[]{
MCoordinate.create2dWithMeasure(9.0, 0.0, 9.0),
MCoordinate.create2dWithMeasure(10.0, 0.0, 10.0),
MCoordinate.create2dWithMeasure(11.0, 0.0, 11.0),
};
MLineString line3 = mgeomFactory.createMLineString(coordinates2);
MCoordinate[] coordinates3 = new MCoordinate[] {
MCoordinate.create2dWithMeasure( 9.0, 0.0, 9.0 ),
MCoordinate.create2dWithMeasure( 10.0, 0.0, 10.0 ),
MCoordinate.create2dWithMeasure( 11.0, 0.0, 11.0 ),
};
MLineString line3 = mgeomFactory.createMLineString( coordinates2 );
incrML = mgeomFactory.createMultiMLineString(new MLineString[]{line1, line2});
incrML = mgeomFactory.createMultiMLineString( new MLineString[] { line1, line2 } );
}
}
@Test
public void test_event_starts_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.0, 5.5);
assertNotNull(result);
assertEquals(1, result.getNumGeometries());
assertEquals(2, result.getCoordinates().length);
Coordinate[] coordinates = result.getCoordinates();
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 5.0), (MCoordinate) coordinates[0]);
assertEquals(MCoordinate.create2dWithMeasure(5.5, 0.0, 5.5), (MCoordinate) coordinates[1]);
@Test
public void test_event_starts_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.0, 5.5 );
assertNotNull( result );
assertEquals( 1, result.getNumGeometries() );
assertEquals( 2, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates();
assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 5.0 ), (MCoordinate) coordinates[0] );
assertEquals( MCoordinate.create2dWithMeasure( 5.5, 0.0, 5.5 ), (MCoordinate) coordinates[1] );
}
}
@Test
public void test_event_ends_at_begin_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 3.0, 5.0);
assertNotNull(result);
assertEquals(1, result.getNumGeometries());
assertEquals(2, result.getCoordinates().length);
Coordinate[] coordinates = result.getCoordinates();
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), (MCoordinate) coordinates[0]);
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), (MCoordinate) coordinates[1]);
}
@Test
public void test_event_ends_at_begin_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry( incrML, 3.0, 5.0 );
assertNotNull( result );
assertEquals( 1, result.getNumGeometries() );
assertEquals( 2, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates();
assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ), (MCoordinate) coordinates[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), (MCoordinate) coordinates[1] );
}
@Test
public void test_event_ends_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.5, 7.0);
assertNotNull(result);
assertEquals(1, result.getNumGeometries());
assertEquals(3, result.getCoordinates().length);
Coordinate[] coordinates = result.getCoordinates();
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(7.0, 0.0, 7.0), (MCoordinate) coordinates[2]);
}
@Test
public void test_event_ends_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.5, 7.0 );
assertNotNull( result );
assertEquals( 1, result.getNumGeometries() );
assertEquals( 3, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates();
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( 7.0, 0.0, 7.0 ), (MCoordinate) coordinates[2] );
}
@Test
public void test_locator_result_has_same_srid_as_input_mgeometry() throws MGeometryException {
incrML.setSRID(123);
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.5, 7.0);
assertEquals(123, result.getSRID());
}
@Test
public void test_locator_result_has_same_srid_as_input_mgeometry() throws MGeometryException {
incrML.setSRID( 123 );
MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.5, 7.0 );
assertEquals( 123, result.getSRID() );
}
}

View File

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