idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
6,200
public static ResultSet createGridPoints ( Connection connection , Value value , double deltaX , double deltaY ) throws SQLException { if ( value == null ) { return null ; } if ( value instanceof ValueString ) { GridRowSet gridRowSet = new GridRowSet ( connection , deltaX , deltaY , value . getString ( ) ) ; gridRowSet . setCenterCell ( true ) ; return gridRowSet . getResultSet ( ) ; } else if ( value instanceof ValueGeometry ) { ValueGeometry geom = ( ValueGeometry ) value ; GridRowSet gridRowSet = new GridRowSet ( connection , deltaX , deltaY , geom . getGeometry ( ) . getEnvelopeInternal ( ) ) ; gridRowSet . setCenterCell ( true ) ; return gridRowSet . getResultSet ( ) ; } else { throw new SQLException ( "This function supports only table name or geometry as first argument." ) ; } }
Create a regular grid of points using the first input value to compute the full extent .
6,201
public void exportTable ( Connection connection , String tableReference , File fileName , ProgressVisitor progress , String encoding ) throws SQLException , IOException { JsonWriteDriver jsonDriver = new JsonWriteDriver ( connection ) ; jsonDriver . write ( progress , tableReference , fileName , encoding ) ; }
Save a table or a query to JSON file
6,202
private int getOrAppendVertex ( Coordinate newCoord , Quadtree ptQuad ) { Envelope queryEnv = new Envelope ( newCoord ) ; queryEnv . expandBy ( epsilon ) ; QuadTreeVisitor visitor = new QuadTreeVisitor ( epsilon , newCoord ) ; try { ptQuad . query ( queryEnv , visitor ) ; } catch ( RuntimeException ex ) { } if ( visitor . getNearest ( ) != null ) { return visitor . getNearest ( ) . index ; } EnvelopeWithIndex ret = new EnvelopeWithIndex ( triVertex . size ( ) , newCoord ) ; ptQuad . insert ( queryEnv , ret ) ; triVertex . add ( ret ) ; return ret . index ; }
Compute unique index for the coordinate Index count from 0 to n If the new vertex is closer than distMerge with an another vertex then it will return its index .
6,203
public Triple [ ] generateTriangleNeighbors ( Geometry geometry ) throws TopologyException { inputTriangles = geometry ; CoordinateSequenceDimensionFilter sequenceDimensionFilter = new CoordinateSequenceDimensionFilter ( ) ; geometry . apply ( sequenceDimensionFilter ) ; hasZ = sequenceDimensionFilter . getDimension ( ) == CoordinateSequenceDimensionFilter . XYZ ; Quadtree ptQuad = new Quadtree ( ) ; triangleVertex = new Triple [ geometry . getNumGeometries ( ) ] ; triVertex = new ArrayList < EnvelopeWithIndex > ( triangleVertex . length ) ; for ( int idgeom = 0 ; idgeom < triangleVertex . length ; idgeom ++ ) { Geometry geomItem = geometry . getGeometryN ( idgeom ) ; if ( geomItem instanceof Polygon ) { Coordinate [ ] coords = geomItem . getCoordinates ( ) ; if ( coords . length != 4 ) { throw new TopologyException ( "Voronoi method accept only triangles" ) ; } triangleVertex [ idgeom ] = new Triple ( getOrAppendVertex ( coords [ 0 ] , ptQuad ) , getOrAppendVertex ( coords [ 1 ] , ptQuad ) , getOrAppendVertex ( coords [ 2 ] , ptQuad ) ) ; for ( int triVertexIndex : triangleVertex [ idgeom ] . toArray ( ) ) { triVertex . get ( triVertexIndex ) . addSharingTriangle ( idgeom ) ; } } else { throw new TopologyException ( "Voronoi method accept only polygons" ) ; } } ptQuad = null ; triangleNeighbors = new Triple [ geometry . getNumGeometries ( ) ] ; for ( int triId = 0 ; triId < triangleVertex . length ; triId ++ ) { Triple triangleIndex = triangleVertex [ triId ] ; triangleNeighbors [ triId ] = new Triple ( commonEdge ( triId , triVertex . get ( triangleIndex . getB ( ) ) , triVertex . get ( triangleIndex . getC ( ) ) ) , commonEdge ( triId , triVertex . get ( triangleIndex . getA ( ) ) , triVertex . get ( triangleIndex . getC ( ) ) ) , commonEdge ( triId , triVertex . get ( triangleIndex . getB ( ) ) , triVertex . get ( triangleIndex . getA ( ) ) ) ) ; } triVertex . clear ( ) ; return triangleNeighbors ; }
Given the input TIN construct a graph of triangle .
6,204
public static void registerGeometryType ( Connection connection ) throws SQLException { Statement st = connection . createStatement ( ) ; for ( DomainInfo domainInfo : getBuiltInsType ( ) ) { st . execute ( "CREATE DOMAIN IF NOT EXISTS " + domainInfo . getDomainName ( ) + " AS " + GEOMETRY_BASE_TYPE + "(" + domainInfo . getGeometryTypeCode ( ) + ") CHECK (ST_GeometryTypeCode(VALUE) = " + domainInfo . getGeometryTypeCode ( ) + ");" ) ; } }
Register geometry type in an OSGi environment
6,205
public static void registerSpatialTables ( Connection connection ) throws SQLException { Statement st = connection . createStatement ( ) ; st . execute ( "drop view if exists geometry_columns" ) ; st . execute ( "create view geometry_columns as select TABLE_CATALOG f_table_catalog,TABLE_SCHEMA f_table_schema,TABLE_NAME f_table_name," + "COLUMN_NAME f_geometry_column,1 storage_type,_GeometryTypeFromConstraint(CHECK_CONSTRAINT || REMARKS, NUMERIC_PRECISION) geometry_type," + "_DimensionFromConstraint(TABLE_CATALOG,TABLE_SCHEMA, TABLE_NAME,COLUMN_NAME,CHECK_CONSTRAINT) coord_dimension," + "_ColumnSRID(TABLE_CATALOG,TABLE_SCHEMA, TABLE_NAME,COLUMN_NAME,CHECK_CONSTRAINT) srid," + " _GeometryTypeNameFromConstraint(CHECK_CONSTRAINT || REMARKS, NUMERIC_PRECISION) type" + " from INFORMATION_SCHEMA.COLUMNS WHERE TYPE_NAME = 'GEOMETRY'" ) ; ResultSet rs = connection . getMetaData ( ) . getTables ( "" , "PUBLIC" , "SPATIAL_REF_SYS" , null ) ; if ( ! rs . next ( ) ) { InputStreamReader reader = new InputStreamReader ( H2GISFunctions . class . getResourceAsStream ( "spatial_ref_sys.sql" ) ) ; RunScript . execute ( connection , reader ) ; try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } }
Register view in order to create GEOMETRY_COLUMNS standard table .
6,206
public static void unRegisterGeometryType ( Connection connection ) throws SQLException { Statement st = connection . createStatement ( ) ; DomainInfo [ ] domainInfos = getBuiltInsType ( ) ; for ( DomainInfo domainInfo : domainInfos ) { st . execute ( "DROP DOMAIN IF EXISTS " + domainInfo . getDomainName ( ) ) ; } }
Release geometry type
6,207
private static String getStringProperty ( Function function , String propertyKey ) { Object value = function . getProperty ( propertyKey ) ; return value instanceof String ? ( String ) value : "" ; }
Return a string property of the function
6,208
private static boolean getBooleanProperty ( Function function , String propertyKey , boolean defaultValue ) { Object value = function . getProperty ( propertyKey ) ; return value instanceof Boolean ? ( Boolean ) value : defaultValue ; }
Return a boolean property of the function
6,209
public static String getAlias ( Function function ) { String functionAlias = getStringProperty ( function , Function . PROP_NAME ) ; if ( ! functionAlias . isEmpty ( ) ) { return functionAlias ; } return function . getClass ( ) . getSimpleName ( ) ; }
Return the alias name of the function
6,210
public static void unRegisterFunction ( Statement st , Function function ) throws SQLException { String functionAlias = getStringProperty ( function , Function . PROP_NAME ) ; if ( functionAlias . isEmpty ( ) ) { functionAlias = function . getClass ( ) . getSimpleName ( ) ; } st . execute ( "DROP ALIAS IF EXISTS " + functionAlias ) ; }
Remove the specified function from the provided DataBase connection
6,211
private static void registerH2GISFunctions ( Connection connection , String packagePrepend ) throws SQLException { Statement st = connection . createStatement ( ) ; for ( Function function : getBuiltInsFunctions ( ) ) { try { registerFunction ( st , function , packagePrepend ) ; } catch ( SQLException ex ) { ex . printStackTrace ( System . err ) ; } } }
Register all H2GIS functions
6,212
public static void unRegisterH2GISFunctions ( Connection connection ) throws SQLException { Statement st = connection . createStatement ( ) ; for ( Function function : getBuiltInsFunctions ( ) ) { unRegisterFunction ( st , function ) ; } unRegisterGeometryType ( connection ) ; }
Unregister spatial type and H2GIS functions from the current connection .
6,213
public static String isValidReason ( Geometry geometry , int flag ) { if ( geometry != null ) { if ( flag == 0 ) { return validReason ( geometry , false ) ; } else if ( flag == 1 ) { return validReason ( geometry , true ) ; } else { throw new IllegalArgumentException ( "Supported arguments are 0 or 1." ) ; } } return "Null Geometry" ; }
Returns text stating whether a geometry is valid . If not returns a reason why .
6,214
public static Geometry polygonize ( Geometry geometry ) { if ( geometry == null ) { return null ; } Polygonizer polygonizer = new Polygonizer ( ) ; polygonizer . add ( geometry ) ; Collection pols = polygonizer . getPolygons ( ) ; if ( pols . isEmpty ( ) ) { return null ; } return FACTORY . createMultiPolygon ( GeometryFactory . toPolygonArray ( pols ) ) ; }
Creates a GeometryCollection containing possible polygons formed from the constituent linework of a set of geometries .
6,215
private void computeMaxDistance ( ) { HashSet < Coordinate > coordinatesA = new HashSet < Coordinate > ( Arrays . asList ( geomA . convexHull ( ) . getCoordinates ( ) ) ) ; Geometry fullHull = geomA . getFactory ( ) . createGeometryCollection ( new Geometry [ ] { geomA , geomB } ) . convexHull ( ) ; maxDistanceFilter = new MaxDistanceFilter ( coordinatesA ) ; fullHull . apply ( maxDistanceFilter ) ; }
Compute the max distance
6,216
public Double getDistance ( ) { if ( geomA == null || geomB == null ) { return null ; } if ( geomA . isEmpty ( ) || geomB . isEmpty ( ) ) { return 0.0 ; } if ( geomA . equals ( geomB ) ) { sameGeom = true ; } if ( maxDistanceFilter == null ) { computeMaxDistance ( ) ; } return maxDistanceFilter . getDistance ( ) ; }
Return the max distance
6,217
public Coordinate [ ] getCoordinatesDistance ( ) { if ( geomA == null || geomB == null ) { return null ; } if ( geomA . isEmpty ( ) || geomB . isEmpty ( ) ) { return null ; } if ( geomA . equals ( geomB ) ) { sameGeom = true ; } if ( maxDistanceFilter == null ) { computeMaxDistance ( ) ; } return maxDistanceFilter . getCoordinatesDistance ( ) ; }
Return the two coordinates to build the max distance line
6,218
public static Geometry toGeometry ( String gmlFile , int srid ) throws SAXException , IOException , ParserConfigurationException { if ( gmlFile == null ) { return null ; } if ( gf == null ) { gf = new GeometryFactory ( new PrecisionModel ( ) , srid ) ; } GMLReader gMLReader = new GMLReader ( ) ; return gMLReader . read ( gmlFile , gf ) ; }
Read the GML representation with a specified SRID
6,219
public void write ( ProgressVisitor progress , ResultSet rs , File fileName , String encoding ) throws SQLException , IOException { if ( FileUtil . isExtensionWellFormated ( fileName , "geojson" ) ) { FileOutputStream fos = null ; JsonEncoding jsonEncoding = JsonEncoding . UTF8 ; if ( encoding != null ) { try { jsonEncoding = JsonEncoding . valueOf ( encoding ) ; } catch ( IllegalArgumentException ex ) { throw new SQLException ( "Only UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE encoding is supported" ) ; } } try { fos = new FileOutputStream ( fileName ) ; int rowCount = 0 ; int type = rs . getType ( ) ; if ( type == ResultSet . TYPE_SCROLL_INSENSITIVE || type == ResultSet . TYPE_SCROLL_SENSITIVE ) { rs . last ( ) ; rowCount = rs . getRow ( ) ; rs . beforeFirst ( ) ; } ProgressVisitor copyProgress = progress . subProcess ( rowCount ) ; List < String > spatialFieldNames = SFSUtilities . getGeometryFields ( rs ) ; if ( spatialFieldNames . isEmpty ( ) ) { throw new SQLException ( "The resulset %s does not contain a geometry field" ) ; } JsonFactory jsonFactory = new JsonFactory ( ) ; JsonGenerator jsonGenerator = jsonFactory . createGenerator ( new BufferedOutputStream ( fos ) , jsonEncoding ) ; jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( "type" , "FeatureCollection" ) ; jsonGenerator . writeArrayFieldStart ( "features" ) ; try { ResultSetMetaData resultSetMetaData = rs . getMetaData ( ) ; int geoFieldIndex = JDBCUtilities . getFieldIndex ( resultSetMetaData , spatialFieldNames . get ( 0 ) ) ; cacheMetadata ( resultSetMetaData ) ; while ( rs . next ( ) ) { writeFeature ( jsonGenerator , rs , geoFieldIndex ) ; copyProgress . endStep ( ) ; } copyProgress . endOfProgress ( ) ; jsonGenerator . writeEndArray ( ) ; jsonGenerator . writeEndObject ( ) ; jsonGenerator . flush ( ) ; jsonGenerator . close ( ) ; } finally { rs . close ( ) ; } } catch ( FileNotFoundException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( fos != null ) { fos . close ( ) ; } } catch ( IOException ex ) { throw new SQLException ( ex ) ; } } } else { throw new SQLException ( "Only .geojson extension is supported" ) ; } }
Write a resulset to a geojson file
6,220
private void writeFeature ( JsonGenerator jsonGenerator , ResultSet rs , int geoFieldIndex ) throws IOException , SQLException { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( "type" , "Feature" ) ; writeGeometry ( ( Geometry ) rs . getObject ( geoFieldIndex ) , jsonGenerator ) ; writeProperties ( jsonGenerator , rs ) ; jsonGenerator . writeEndObject ( ) ; }
Write a GeoJSON feature .
6,221
private void cacheMetadata ( ResultSetMetaData resultSetMetaData ) throws SQLException { cachedColumnNames = new LinkedHashMap < String , Integer > ( ) ; for ( int i = 1 ; i <= resultSetMetaData . getColumnCount ( ) ; i ++ ) { final String fieldTypeName = resultSetMetaData . getColumnTypeName ( i ) ; if ( ! fieldTypeName . equalsIgnoreCase ( "geometry" ) && isSupportedPropertyType ( resultSetMetaData . getColumnType ( i ) , fieldTypeName ) ) { cachedColumnNames . put ( resultSetMetaData . getColumnName ( i ) . toUpperCase ( ) , i ) ; columnCountProperties ++ ; } } }
Cache the column name and its index .
6,222
private void writeGeometry ( Geometry geom , JsonGenerator gen ) throws IOException { if ( geom != null ) { gen . writeObjectFieldStart ( "geometry" ) ; if ( geom instanceof Point ) { write ( ( Point ) geom , gen ) ; } else if ( geom instanceof MultiPoint ) { write ( ( MultiPoint ) geom , gen ) ; } else if ( geom instanceof LineString ) { write ( ( LineString ) geom , gen ) ; } else if ( geom instanceof MultiLineString ) { write ( ( MultiLineString ) geom , gen ) ; } else if ( geom instanceof Polygon ) { write ( ( Polygon ) geom , gen ) ; } else if ( geom instanceof MultiPolygon ) { write ( ( MultiPolygon ) geom , gen ) ; } else if ( geom instanceof GeometryCollection ) { write ( ( GeometryCollection ) geom , gen ) ; } else { throw new RuntimeException ( "Unsupported Geomery type" ) ; } gen . writeEndObject ( ) ; } else { gen . writeNullField ( "geometry" ) ; } }
Write a JTS geometry to its GeoJSON geometry representation .
6,223
private void writeProperties ( JsonGenerator jsonGenerator , ResultSet rs ) throws IOException , SQLException { if ( columnCountProperties != - 1 ) { jsonGenerator . writeObjectFieldStart ( "properties" ) ; for ( Map . Entry < String , Integer > entry : cachedColumnNames . entrySet ( ) ) { String string = entry . getKey ( ) ; string = string . toLowerCase ( ) ; Integer fieldId = entry . getValue ( ) ; if ( rs . getObject ( fieldId ) instanceof Object [ ] ) { Object [ ] array = ( Object [ ] ) rs . getObject ( fieldId ) ; jsonGenerator . writeArrayFieldStart ( string ) ; writeArray ( jsonGenerator , array , true ) ; jsonGenerator . writeEndArray ( ) ; } else if ( rs . getObject ( fieldId ) != null && rs . getObject ( fieldId ) . equals ( "{}" ) ) { jsonGenerator . writeObjectFieldStart ( string ) ; jsonGenerator . writeEndObject ( ) ; } else if ( rs . getObject ( fieldId ) == "null" ) { jsonGenerator . writeFieldName ( string ) ; jsonGenerator . writeNull ( ) ; } else { jsonGenerator . writeObjectField ( string , rs . getObject ( fieldId ) ) ; } } jsonGenerator . writeEndObject ( ) ; } }
Write the GeoJSON properties .
6,224
public boolean isSupportedPropertyType ( int sqlTypeId , String sqlTypeName ) throws SQLException { switch ( sqlTypeId ) { case Types . BOOLEAN : case Types . DOUBLE : case Types . FLOAT : case Types . INTEGER : case Types . BIGINT : case Types . SMALLINT : case Types . DATE : case Types . VARCHAR : case Types . NCHAR : case Types . CHAR : case Types . ARRAY : case Types . OTHER : case Types . DECIMAL : case Types . REAL : case Types . TINYINT : case Types . NUMERIC : case Types . NULL : return true ; default : throw new SQLException ( "Field type not supported by GeoJSON driver: " + sqlTypeName ) ; } }
Return true is the SQL type is supported by the GeoJSON driver .
6,225
private void writeCRS ( JsonGenerator jsonGenerator , String [ ] authorityAndSRID ) throws IOException { if ( authorityAndSRID [ 1 ] != null ) { jsonGenerator . writeObjectFieldStart ( "crs" ) ; jsonGenerator . writeStringField ( "type" , "name" ) ; jsonGenerator . writeObjectFieldStart ( "properties" ) ; StringBuilder sb = new StringBuilder ( "urn:ogc:def:crs:" ) ; sb . append ( authorityAndSRID [ 0 ] ) . append ( "::" ) . append ( authorityAndSRID [ 1 ] ) ; jsonGenerator . writeStringField ( "name" , sb . toString ( ) ) ; jsonGenerator . writeEndObject ( ) ; jsonGenerator . writeEndObject ( ) ; } }
Write the CRS in the geojson
6,226
private void writeArray ( JsonGenerator jsonGenerator , Object [ ] array , boolean firstInHierarchy ) throws IOException , SQLException { if ( ! firstInHierarchy ) { jsonGenerator . writeStartArray ( ) ; } for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] instanceof Integer ) { jsonGenerator . writeNumber ( ( int ) array [ i ] ) ; } else if ( array [ i ] instanceof String ) { if ( array [ i ] . equals ( "{}" ) ) { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeEndObject ( ) ; } else { jsonGenerator . writeString ( ( String ) array [ i ] ) ; } } else if ( array [ i ] instanceof Double ) { jsonGenerator . writeNumber ( ( double ) array [ i ] ) ; } else if ( array [ i ] instanceof Boolean ) { jsonGenerator . writeBoolean ( ( boolean ) array [ i ] ) ; } else if ( array [ i ] instanceof Object [ ] ) { writeArray ( jsonGenerator , ( Object [ ] ) array [ i ] , false ) ; } } if ( ! firstInHierarchy ) { jsonGenerator . writeEndArray ( ) ; } }
Write the array in the geojson
6,227
public static Geometry singleSideBuffer ( Geometry geometry , double distance ) { if ( geometry == null ) { return null ; } return computeSingleSideBuffer ( geometry , distance , new BufferParameters ( ) ) ; }
Compute a single side buffer with default parameters
6,228
private static Geometry computeSingleSideBuffer ( Geometry geometry , double distance , BufferParameters bufferParameters ) { bufferParameters . setSingleSided ( true ) ; return BufferOp . bufferOp ( geometry , distance , bufferParameters ) ; }
Compute the buffer
6,229
public static Boolean geomEquals ( Geometry a , Geometry b ) { if ( a == null || b == null ) { return null ; } return a . equals ( b ) ; }
Return true if Geometry A is equal to Geometry B
6,230
private void addGeometry ( Geometry geom ) { if ( geom != null ) { if ( geom instanceof GeometryCollection ) { List < Geometry > toUnitTmp = new ArrayList < Geometry > ( geom . getNumGeometries ( ) ) ; for ( int i = 0 ; i < geom . getNumGeometries ( ) ; i ++ ) { toUnitTmp . add ( geom . getGeometryN ( i ) ) ; feedDim ( geom . getGeometryN ( i ) ) ; } toUnite . addAll ( toUnitTmp ) ; } else { toUnite . add ( geom ) ; feedDim ( geom ) ; } } }
Add geometry into an array to accumulate
6,231
public void exportTable ( Connection connection , String tableReference , File fileName , ProgressVisitor progress , String encoding ) throws SQLException , IOException { GeoJsonWriteDriver geoJsonDriver = new GeoJsonWriteDriver ( connection ) ; geoJsonDriver . write ( progress , tableReference , fileName , encoding ) ; }
Export a table or a query to a geojson file
6,232
public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { if ( localName . compareToIgnoreCase ( "osm" ) == 0 ) { version = attributes . getValue ( GPXTags . VERSION ) ; } else if ( localName . compareToIgnoreCase ( "node" ) == 0 ) { totalNode ++ ; } else if ( localName . compareToIgnoreCase ( "way" ) == 0 ) { totalWay ++ ; } else if ( localName . compareToIgnoreCase ( "relation" ) == 0 ) { totalRelation ++ ; } }
Fires whenever an XML start markup is encountered . It indicates which version of osm file is to be parsed .
6,233
public static Geometry addPoint ( Geometry geometry , Point point ) throws SQLException { return addPoint ( geometry , point , PRECISION ) ; }
Returns a new geometry based on an existing one with a specific point as a new vertex . A default distance 10E - 6 is used to snap the input point .
6,234
public static Geometry addPoint ( Geometry geometry , Point point , double tolerance ) throws SQLException { if ( geometry == null || point == null ) { return null ; } if ( geometry instanceof MultiPoint ) { return insertVertexInMultipoint ( geometry , point ) ; } else if ( geometry instanceof LineString ) { return insertVertexInLineString ( ( LineString ) geometry , point , tolerance ) ; } else if ( geometry instanceof MultiLineString ) { LineString [ ] linestrings = new LineString [ geometry . getNumGeometries ( ) ] ; boolean any = false ; for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { LineString line = ( LineString ) geometry . getGeometryN ( i ) ; LineString inserted = insertVertexInLineString ( line , point , tolerance ) ; if ( inserted != null ) { linestrings [ i ] = inserted ; any = true ; } else { linestrings [ i ] = line ; } } if ( any ) { return FACTORY . createMultiLineString ( linestrings ) ; } else { return null ; } } else if ( geometry instanceof Polygon ) { return insertVertexInPolygon ( ( Polygon ) geometry , point , tolerance ) ; } else if ( geometry instanceof MultiPolygon ) { Polygon [ ] polygons = new Polygon [ geometry . getNumGeometries ( ) ] ; boolean any = false ; for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Polygon polygon = ( Polygon ) geometry . getGeometryN ( i ) ; Polygon inserted = insertVertexInPolygon ( polygon , point , tolerance ) ; if ( inserted != null ) { any = true ; polygons [ i ] = inserted ; } else { polygons [ i ] = polygon ; } } if ( any ) { return FACTORY . createMultiPolygon ( polygons ) ; } else { return null ; } } else if ( geometry instanceof Point ) { return null ; } throw new SQLException ( "Unknown geometry type" + " : " + geometry . getGeometryType ( ) ) ; }
Returns a new geometry based on an existing one with a specific point as a new vertex .
6,235
private static Geometry insertVertexInMultipoint ( Geometry g , Point vertexPoint ) { ArrayList < Point > geoms = new ArrayList < Point > ( ) ; for ( int i = 0 ; i < g . getNumGeometries ( ) ; i ++ ) { Point geom = ( Point ) g . getGeometryN ( i ) ; geoms . add ( geom ) ; } geoms . add ( FACTORY . createPoint ( new Coordinate ( vertexPoint . getX ( ) , vertexPoint . getY ( ) ) ) ) ; return FACTORY . createMultiPoint ( GeometryFactory . toPointArray ( geoms ) ) ; }
Adds a Point into a MultiPoint geometry .
6,236
private static Polygon insertVertexInPolygon ( Polygon polygon , Point vertexPoint , double tolerance ) throws SQLException { Polygon geom = polygon ; LineString linearRing = polygon . getExteriorRing ( ) ; int index = - 1 ; for ( int i = 0 ; i < polygon . getNumInteriorRing ( ) ; i ++ ) { double distCurr = computeDistance ( polygon . getInteriorRingN ( i ) , vertexPoint , tolerance ) ; if ( distCurr < tolerance ) { index = i ; } } if ( index == - 1 ) { LinearRing inserted = insertVertexInLinearRing ( linearRing , vertexPoint , tolerance ) ; if ( inserted != null ) { LinearRing [ ] holes = new LinearRing [ polygon . getNumInteriorRing ( ) ] ; for ( int i = 0 ; i < holes . length ; i ++ ) { holes [ i ] = ( LinearRing ) polygon . getInteriorRingN ( i ) ; } geom = FACTORY . createPolygon ( inserted , holes ) ; } } else { LinearRing [ ] holes = new LinearRing [ polygon . getNumInteriorRing ( ) ] ; for ( int i = 0 ; i < holes . length ; i ++ ) { if ( i == index ) { holes [ i ] = insertVertexInLinearRing ( polygon . getInteriorRingN ( i ) , vertexPoint , tolerance ) ; } else { holes [ i ] = ( LinearRing ) polygon . getInteriorRingN ( i ) ; } } geom = FACTORY . createPolygon ( ( LinearRing ) linearRing , holes ) ; } if ( geom != null ) { if ( ! geom . isValid ( ) ) { throw new SQLException ( "Geometry not valid" ) ; } } return geom ; }
Adds a vertex into a Polygon with a given tolerance .
6,237
private static double computeDistance ( Geometry geometry , Point vertexPoint , double tolerance ) { DistanceOp distanceOp = new DistanceOp ( geometry , vertexPoint , tolerance ) ; return distanceOp . distance ( ) ; }
Return minimum distance between a geometry and a point .
6,238
private static LinearRing insertVertexInLinearRing ( LineString lineString , Point vertexPoint , double tolerance ) { GeometryLocation geomLocation = EditUtilities . getVertexToSnap ( lineString , vertexPoint , tolerance ) ; if ( geomLocation != null ) { Coordinate [ ] coords = lineString . getCoordinates ( ) ; int index = geomLocation . getSegmentIndex ( ) ; Coordinate coord = geomLocation . getCoordinate ( ) ; if ( ! CoordinateUtils . contains2D ( coords , coord ) ) { Coordinate [ ] ret = new Coordinate [ coords . length + 1 ] ; System . arraycopy ( coords , 0 , ret , 0 , index + 1 ) ; ret [ index + 1 ] = coord ; System . arraycopy ( coords , index + 1 , ret , index + 2 , coords . length - ( index + 1 ) ) ; return FACTORY . createLinearRing ( ret ) ; } return null ; } else { return null ; } }
Adds a vertex into a LinearRing with a given tolerance .
6,239
public static void openFile ( Connection connection , String fileName , String tableName ) throws SQLException { String ext = fileName . substring ( fileName . lastIndexOf ( '.' ) + 1 , fileName . length ( ) ) ; final boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; for ( DriverDef driverDef : DRIVERS ) { if ( driverDef . getFileExt ( ) . equalsIgnoreCase ( ext ) ) { try ( Statement st = connection . createStatement ( ) ) { st . execute ( String . format ( "CREATE TABLE %s COMMENT %s ENGINE %s WITH %s" , TableLocation . parse ( tableName , isH2 ) . toString ( isH2 ) , StringUtils . quoteStringSQL ( fileName ) , StringUtils . quoteJavaString ( driverDef . getClassName ( ) ) , StringUtils . quoteJavaString ( fileName ) ) ) ; } return ; } } throw new SQLException ( "No driver is available to open the " + ext + " file format" ) ; }
Create a new table
6,240
public static void exportTable ( Connection connection , String fileName , String tableReference , String encoding ) throws IOException , SQLException { SHPDriverFunction shpDriverFunction = new SHPDriverFunction ( ) ; shpDriverFunction . exportTable ( connection , tableReference , URIUtilities . fileFromString ( fileName ) , new EmptyProgressVisitor ( ) , encoding ) ; }
Read a table and write it into a shape file .
6,241
public static Geometry force ( Geometry geom , int dimension ) { if ( geom instanceof Point ) { return gf . createPoint ( convertSequence ( geom . getCoordinates ( ) , dimension ) ) ; } else if ( geom instanceof LineString ) { return gf . createLineString ( convertSequence ( geom . getCoordinates ( ) , dimension ) ) ; } else if ( geom instanceof Polygon ) { return GeometryCoordinateDimension . convert ( ( Polygon ) geom , dimension ) ; } else if ( geom instanceof MultiPoint ) { return gf . createMultiPoint ( convertSequence ( geom . getCoordinates ( ) , dimension ) ) ; } else if ( geom instanceof MultiLineString ) { return GeometryCoordinateDimension . convert ( ( MultiLineString ) geom , dimension ) ; } else if ( geom instanceof MultiPolygon ) { return GeometryCoordinateDimension . convert ( ( MultiPolygon ) geom , dimension ) ; } else if ( geom instanceof GeometryCollection ) { return GeometryCoordinateDimension . convert ( ( GeometryCollection ) geom , dimension ) ; } return geom ; }
Force the dimension of the geometry and update correctly the coordinate dimension
6,242
public static GeometryCollection convert ( GeometryCollection gc , int dimension ) { int nb = gc . getNumGeometries ( ) ; final Geometry [ ] geometries = new Geometry [ nb ] ; for ( int i = 0 ; i < nb ; i ++ ) { geometries [ i ] = force ( gc . getGeometryN ( i ) , dimension ) ; } return gf . createGeometryCollection ( geometries ) ; }
Force the dimension of the GeometryCollection and update correctly the coordinate dimension
6,243
public static MultiPolygon convert ( MultiPolygon multiPolygon , int dimension ) { int nb = multiPolygon . getNumGeometries ( ) ; final Polygon [ ] pl = new Polygon [ nb ] ; for ( int i = 0 ; i < nb ; i ++ ) { pl [ i ] = GeometryCoordinateDimension . convert ( ( Polygon ) multiPolygon . getGeometryN ( i ) , dimension ) ; } return gf . createMultiPolygon ( pl ) ; }
Force the dimension of the MultiPolygon and update correctly the coordinate dimension
6,244
public static MultiLineString convert ( MultiLineString multiLineString , int dimension ) { int nb = multiLineString . getNumGeometries ( ) ; final LineString [ ] ls = new LineString [ nb ] ; for ( int i = 0 ; i < nb ; i ++ ) { ls [ i ] = GeometryCoordinateDimension . convert ( ( LineString ) multiLineString . getGeometryN ( i ) , dimension ) ; } return gf . createMultiLineString ( ls ) ; }
Force the dimension of the MultiLineString and update correctly the coordinate dimension
6,245
public static Polygon convert ( Polygon polygon , int dimension ) { LinearRing shell = GeometryCoordinateDimension . convert ( polygon . getExteriorRing ( ) , dimension ) ; int nbOfHoles = polygon . getNumInteriorRing ( ) ; final LinearRing [ ] holes = new LinearRing [ nbOfHoles ] ; for ( int i = 0 ; i < nbOfHoles ; i ++ ) { holes [ i ] = GeometryCoordinateDimension . convert ( polygon . getInteriorRingN ( i ) , dimension ) ; } return gf . createPolygon ( shell , holes ) ; }
Force the dimension of the Polygon and update correctly the coordinate dimension
6,246
public static LinearRing convert ( LineString lineString , int dimension ) { return gf . createLinearRing ( convertSequence ( lineString . getCoordinates ( ) , dimension ) ) ; }
Force the dimension of the LineString and update correctly the coordinate dimension
6,247
public static LinearRing convert ( LinearRing linearRing , int dimension ) { return gf . createLinearRing ( convertSequence ( linearRing . getCoordinates ( ) , dimension ) ) ; }
Force the dimension of the LinearRing and update correctly the coordinate dimension
6,248
private static CoordinateArraySequence convertSequence ( Coordinate [ ] cs , int dimension ) { for ( int i = 0 ; i < cs . length ; i ++ ) { Coordinate coord = cs [ i ] ; switch ( dimension ) { case 2 : coord . z = Double . NaN ; cs [ i ] = coord ; break ; case 3 : { double z = coord . z ; if ( Double . isNaN ( z ) ) { coord . z = 0 ; cs [ i ] = coord ; } break ; } default : break ; } } return new CoordinateArraySequence ( cs , dimension ) ; }
Create a new CoordinateArraySequence and update its dimension
6,249
public static Double computeCompacity ( Geometry geom ) { if ( geom == null ) { return null ; } if ( geom instanceof Polygon ) { final double circleRadius = Math . sqrt ( geom . getArea ( ) / Math . PI ) ; final double circleCurcumference = 2 * Math . PI * circleRadius ; return circleCurcumference / geom . getLength ( ) ; } return null ; }
Returns the compactness ratio of the given polygon
6,250
public static Double st3darea ( Geometry geometry ) { if ( geometry == null ) { return null ; } double area = 0 ; for ( int idPoly = 0 ; idPoly < geometry . getNumGeometries ( ) ; idPoly ++ ) { Geometry subGeom = geometry . getGeometryN ( idPoly ) ; if ( subGeom instanceof Polygon ) { area += compute3DArea ( ( Polygon ) subGeom ) ; } } return area ; }
Compute the 3D area of a polygon a geometrycollection that contains polygons
6,251
private static Double compute3DArea ( Polygon geometry ) { DelaunayData delaunayData = new DelaunayData ( ) ; delaunayData . put ( geometry , DelaunayData . MODE . TESSELLATION ) ; delaunayData . triangulate ( ) ; return delaunayData . get3DArea ( ) ; }
Compute the 3D area of a polygon
6,252
public static Geometry setSRID ( Geometry geometry , Integer srid ) throws IllegalArgumentException { if ( geometry == null ) { return null ; } if ( srid == null ) { throw new IllegalArgumentException ( "The SRID code cannot be null." ) ; } Geometry geom = geometry . copy ( ) ; geom . setSRID ( srid ) ; return geom ; }
Set a new SRID to the geometry
6,253
public static void writeGeoJson ( Connection connection , String fileName , String tableReference , String encoding ) throws IOException , SQLException { JsonDriverFunction jsonDriver = new JsonDriverFunction ( ) ; jsonDriver . exportTable ( connection , tableReference , URIUtilities . fileFromString ( fileName ) , new EmptyProgressVisitor ( ) , encoding ) ; }
Write the JSON file .
6,254
public static int geometryTypeFromConstraint ( String constraint , int numericPrecision ) { if ( constraint . isEmpty ( ) && numericPrecision > GeometryTypeCodes . GEOMETRYZM ) { return GeometryTypeCodes . GEOMETRY ; } if ( numericPrecision <= GeometryTypeCodes . GEOMETRYZM ) { return numericPrecision ; } Matcher matcher = TYPE_CODE_PATTERN . matcher ( constraint ) ; if ( matcher . find ( ) ) { return Integer . valueOf ( matcher . group ( CODE_GROUP_ID ) ) ; } else { return GeometryTypeCodes . GEOMETRY ; } }
Convert H2 constraint string into a OGC geometry type index .
6,255
public static String getQuestionMark ( int count ) { StringBuilder qMark = new StringBuilder ( ) ; for ( int i = 0 ; i < count ; i ++ ) { if ( i > 0 ) { qMark . append ( ", " ) ; } qMark . append ( "?" ) ; } return qMark . toString ( ) ; }
Generate the concatenation of ? characters . Used by PreparedStatement .
6,256
public static String getSQLColumnTypes ( DbaseFileHeader header , boolean isH2Database ) throws IOException { StringBuilder stringBuilder = new StringBuilder ( ) ; for ( int idColumn = 0 ; idColumn < header . getNumFields ( ) ; idColumn ++ ) { if ( idColumn > 0 ) { stringBuilder . append ( ", " ) ; } String fieldName = TableLocation . capsIdentifier ( header . getFieldName ( idColumn ) , isH2Database ) ; stringBuilder . append ( TableLocation . quoteIdentifier ( fieldName , isH2Database ) ) ; stringBuilder . append ( " " ) ; switch ( header . getFieldType ( idColumn ) ) { case 'l' : case 'L' : stringBuilder . append ( "BOOLEAN" ) ; break ; case 'c' : case 'C' : stringBuilder . append ( "VARCHAR(" ) ; int length = header . getFieldLength ( idColumn ) ; stringBuilder . append ( String . valueOf ( length ) ) ; stringBuilder . append ( ")" ) ; break ; case 'd' : case 'D' : stringBuilder . append ( "DATE" ) ; break ; case 'n' : case 'N' : if ( ( header . getFieldDecimalCount ( idColumn ) == 0 ) ) { if ( ( header . getFieldLength ( idColumn ) >= 0 ) && ( header . getFieldLength ( idColumn ) < 10 ) ) { stringBuilder . append ( "INT4" ) ; } else { stringBuilder . append ( "INT8" ) ; } } else { stringBuilder . append ( "FLOAT8" ) ; } break ; case 'f' : case 'F' : case 'o' : case 'O' : stringBuilder . append ( "FLOAT8" ) ; break ; default : throw new IOException ( "Unknown DBF field type " + header . getFieldType ( idColumn ) ) ; } } return stringBuilder . toString ( ) ; }
Return SQL Columns declaration
6,257
public static DbaseFileHeader dBaseHeaderFromMetaData ( ResultSetMetaData metaData , List < Integer > retainedColumns ) throws SQLException { DbaseFileHeader dbaseFileHeader = new DbaseFileHeader ( ) ; for ( int fieldId = 1 ; fieldId <= metaData . getColumnCount ( ) ; fieldId ++ ) { final String fieldTypeName = metaData . getColumnTypeName ( fieldId ) ; if ( ! fieldTypeName . equalsIgnoreCase ( "geometry" ) ) { DBFType dbfType = getDBFType ( metaData . getColumnType ( fieldId ) , fieldTypeName , metaData . getColumnDisplaySize ( fieldId ) , metaData . getPrecision ( fieldId ) ) ; try { dbaseFileHeader . addColumn ( metaData . getColumnName ( fieldId ) , dbfType . type , dbfType . fieldLength , dbfType . decimalCount ) ; retainedColumns . add ( fieldId ) ; } catch ( DbaseFileException ex ) { throw new SQLException ( ex . getLocalizedMessage ( ) , ex ) ; } } } return dbaseFileHeader ; }
Create a DBF header from the columns specified in parameter .
6,258
public static Geometry removePoint ( Geometry geometry , Polygon polygon ) throws SQLException { if ( geometry == null ) { return null ; } GeometryEditor localGeometryEditor = new GeometryEditor ( ) ; PolygonDeleteVertexOperation localBoxDeleteVertexOperation = new PolygonDeleteVertexOperation ( geometry . getFactory ( ) , new PreparedPolygon ( polygon ) ) ; Geometry localGeometry = localGeometryEditor . edit ( geometry , localBoxDeleteVertexOperation ) ; if ( localGeometry . isEmpty ( ) ) { return null ; } return localGeometry ; }
Remove all vertices that are located within a polygon
6,259
public static Map < String , String > getQueryKeyValuePairs ( URI uri ) throws UnsupportedEncodingException { Map < String , String > queryParameters = new HashMap < String , String > ( ) ; String query = uri . getRawQuery ( ) ; if ( query == null ) { try { uri = URI . create ( uri . getRawSchemeSpecificPart ( ) ) ; query = uri . getRawQuery ( ) ; if ( query == null ) { return queryParameters ; } } catch ( IllegalArgumentException ex ) { return queryParameters ; } } StringTokenizer stringTokenizer = new StringTokenizer ( query , "&" ) ; while ( stringTokenizer . hasMoreTokens ( ) ) { String keyValue = stringTokenizer . nextToken ( ) . trim ( ) ; if ( ! keyValue . isEmpty ( ) ) { int equalPos = keyValue . indexOf ( "=" ) ; String key = URLDecoder . decode ( keyValue . substring ( 0 , equalPos != - 1 ? equalPos : keyValue . length ( ) ) , ENCODING ) ; if ( equalPos == - 1 || equalPos == keyValue . length ( ) - 1 ) { queryParameters . put ( key . toLowerCase ( ) , "" ) ; } else { String value = URLDecoder . decode ( keyValue . substring ( equalPos + 1 ) , ENCODING ) ; queryParameters . put ( key . toLowerCase ( ) , value ) ; } } } return queryParameters ; }
Read the Query part of an URI .
6,260
public static String getConcatenatedParameters ( Map < String , String > parameters , String ... keys ) { StringBuilder keyValues = new StringBuilder ( ) ; for ( String key : keys ) { String value = parameters . get ( key . toLowerCase ( ) . trim ( ) ) ; if ( value != null ) { if ( keyValues . length ( ) != 0 ) { keyValues . append ( "&" ) ; } keyValues . append ( key . toUpperCase ( ) ) ; keyValues . append ( "=" ) ; keyValues . append ( value ) ; } } return keyValues . toString ( ) ; }
Create the Query part of an URI
6,261
public static URI relativize ( URI base , URI target ) { if ( ! base . getScheme ( ) . equals ( target . getScheme ( ) ) ) { return target ; } StringBuilder rel = new StringBuilder ( ) ; String path = base . getPath ( ) ; String separator = "/" ; StringTokenizer tokenizer = new StringTokenizer ( target . getPath ( ) , separator ) ; String targetPart = "" ; if ( tokenizer . hasMoreTokens ( ) ) { targetPart = tokenizer . nextToken ( ) ; } if ( path . startsWith ( separator ) ) { path = path . substring ( 1 ) ; } StringTokenizer baseTokenizer = new StringTokenizer ( path , separator , true ) ; while ( baseTokenizer . hasMoreTokens ( ) ) { String basePart = baseTokenizer . nextToken ( ) ; if ( baseTokenizer . hasMoreTokens ( ) ) { baseTokenizer . nextToken ( ) ; if ( ! basePart . isEmpty ( ) ) { if ( ! basePart . equals ( targetPart ) ) { rel . append ( ".." ) ; rel . append ( separator ) ; } else if ( tokenizer . hasMoreTokens ( ) ) { targetPart = tokenizer . nextToken ( ) ; } } } } rel . append ( targetPart ) ; while ( tokenizer . hasMoreTokens ( ) ) { targetPart = tokenizer . nextToken ( ) ; rel . append ( separator ) ; rel . append ( targetPart ) ; } try { return new URI ( null , null , rel . toString ( ) , null , null ) ; } catch ( URISyntaxException ex ) { throw new IllegalArgumentException ( "Illegal URI provided:\n" + base . toString ( ) + "\n" + target . toString ( ) ) ; } }
Enhanced version of URI . relativize the target can now be in parent folder of base URI .
6,262
public static File fileFromString ( String fileName ) { try { return new File ( new URI ( fileName ) . getPath ( ) ) ; } catch ( URISyntaxException ex ) { return new File ( fileName ) ; } }
Get a File from the specified file name .
6,263
private static Geometry shadowLine ( LineString lineString , double [ ] shadowOffset , GeometryFactory factory , boolean doUnion ) { Coordinate [ ] coords = lineString . getCoordinates ( ) ; Collection < Polygon > shadows = new ArrayList < Polygon > ( ) ; createShadowPolygons ( shadows , coords , shadowOffset , factory ) ; if ( ! doUnion ) { return factory . buildGeometry ( shadows ) ; } else { if ( ! shadows . isEmpty ( ) ) { CascadedPolygonUnion union = new CascadedPolygonUnion ( shadows ) ; Geometry result = union . union ( ) ; result . apply ( new UpdateZCoordinateSequenceFilter ( 0 , 1 ) ) ; return result ; } return null ; } }
Compute the shadow for a linestring
6,264
private static Geometry shadowPolygon ( Polygon polygon , double [ ] shadowOffset , GeometryFactory factory , boolean doUnion ) { Coordinate [ ] shellCoords = polygon . getExteriorRing ( ) . getCoordinates ( ) ; Collection < Polygon > shadows = new ArrayList < Polygon > ( ) ; createShadowPolygons ( shadows , shellCoords , shadowOffset , factory ) ; final int nbOfHoles = polygon . getNumInteriorRing ( ) ; for ( int i = 0 ; i < nbOfHoles ; i ++ ) { createShadowPolygons ( shadows , polygon . getInteriorRingN ( i ) . getCoordinates ( ) , shadowOffset , factory ) ; } if ( ! doUnion ) { return factory . buildGeometry ( shadows ) ; } else { if ( ! shadows . isEmpty ( ) ) { Collection < Geometry > shadowParts = new ArrayList < Geometry > ( ) ; for ( Polygon shadowPolygon : shadows ) { shadowParts . add ( shadowPolygon . difference ( polygon ) ) ; } Geometry allShadowParts = factory . buildGeometry ( shadowParts ) ; Geometry union = allShadowParts . buffer ( 0 ) ; union . apply ( new UpdateZCoordinateSequenceFilter ( 0 , 1 ) ) ; return union ; } return null ; } }
Compute the shadow for a polygon
6,265
private static Geometry shadowPoint ( Point point , double [ ] shadowOffset , GeometryFactory factory ) { Coordinate startCoord = point . getCoordinate ( ) ; Coordinate offset = moveCoordinate ( startCoord , shadowOffset ) ; if ( offset . distance ( point . getCoordinate ( ) ) < 10E-3 ) { return point ; } else { startCoord . z = 0 ; return factory . createLineString ( new Coordinate [ ] { startCoord , offset } ) ; } }
Compute the shadow for a point
6,266
public static double [ ] shadowOffset ( double azimuth , double altitude , double height ) { double spread = 1 / Math . tan ( altitude ) ; return new double [ ] { - height * spread * Math . sin ( azimuth ) , - height * spread * Math . cos ( azimuth ) } ; }
Return the shadow offset in X and Y directions
6,267
private static Coordinate moveCoordinate ( Coordinate inputCoordinate , double [ ] shadowOffset ) { return new Coordinate ( inputCoordinate . x + shadowOffset [ 0 ] , inputCoordinate . y + shadowOffset [ 1 ] , 0 ) ; }
Move the input coordinate according X and Y offset
6,268
private static void createShadowPolygons ( Collection < Polygon > shadows , Coordinate [ ] coordinates , double [ ] shadow , GeometryFactory factory ) { for ( int i = 1 ; i < coordinates . length ; i ++ ) { Coordinate startCoord = coordinates [ i - 1 ] ; Coordinate endCoord = coordinates [ i ] ; Coordinate nextEnd = moveCoordinate ( endCoord , shadow ) ; Coordinate nextStart = moveCoordinate ( startCoord , shadow ) ; Polygon polygon = factory . createPolygon ( new Coordinate [ ] { startCoord , endCoord , nextEnd , nextStart , startCoord } ) ; if ( polygon . isValid ( ) ) { shadows . add ( polygon ) ; } } }
Create and collect shadow polygons .
6,269
public void exportTable ( Connection connection , String tableReference , File fileName , ProgressVisitor progress , String csvOptions ) throws SQLException , IOException { String regex = ".*(?i)\\b(select|from)\\b.*" ; Pattern pattern = Pattern . compile ( regex ) ; Matcher matcher = pattern . matcher ( tableReference ) ; if ( matcher . find ( ) ) { if ( tableReference . startsWith ( "(" ) && tableReference . endsWith ( ")" ) ) { try ( Statement st = connection . createStatement ( ) ) { JDBCUtilities . attachCancelResultSet ( st , progress ) ; Csv csv = new Csv ( ) ; if ( csvOptions != null && csvOptions . indexOf ( '=' ) >= 0 ) { csv . setOptions ( csvOptions ) ; } csv . write ( fileName . getPath ( ) , st . executeQuery ( tableReference ) , null ) ; } } else { throw new SQLException ( "The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'." ) ; } } else { if ( FileUtil . isExtensionWellFormated ( fileName , "csv" ) ) { final boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; TableLocation location = TableLocation . parse ( tableReference , isH2 ) ; try ( Statement st = connection . createStatement ( ) ) { JDBCUtilities . attachCancelResultSet ( st , progress ) ; Csv csv = new Csv ( ) ; if ( csvOptions != null && csvOptions . indexOf ( '=' ) >= 0 ) { csv . setOptions ( csvOptions ) ; } csv . write ( fileName . getPath ( ) , st . executeQuery ( "SELECT * FROM " + location . toString ( ) ) , null ) ; } } else { throw new SQLException ( "Only .csv extension is supported" ) ; } } }
Export a table or a query to a CSV file
6,270
public static GeometryCollection createDT ( Geometry geometry , int flag ) throws SQLException { if ( geometry != null ) { DelaunayTriangulationBuilder triangulationBuilder = new DelaunayTriangulationBuilder ( ) ; triangulationBuilder . setSites ( geometry ) ; if ( flag == 0 ) { return getTriangles ( geometry . getFactory ( ) , triangulationBuilder ) ; } else { return ( GeometryCollection ) triangulationBuilder . getEdges ( geometry . getFactory ( ) ) ; } } return null ; }
Build a delaunay triangulation based on all coordinates of the geometry
6,271
public static String toKml ( Geometry geometry ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; KMLGeometry . toKMLGeometry ( geometry , sb ) ; return sb . toString ( ) ; }
Generate a KML geometry
6,272
public static String toKml ( Geometry geometry , boolean extrude , int altitudeModeEnum ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; if ( extrude ) { KMLGeometry . toKMLGeometry ( geometry , ExtrudeMode . TRUE , altitudeModeEnum , sb ) ; } else { KMLGeometry . toKMLGeometry ( geometry , ExtrudeMode . FALSE , altitudeModeEnum , sb ) ; } return sb . toString ( ) ; }
Generates a KML geometry . Specifies the extrude and altitudeMode .
6,273
public static int getGeometryTypeFromGeometry ( Geometry geometry ) { Integer sfsGeomCode = GEOM_TYPE_TO_SFS_CODE . get ( geometry . getGeometryType ( ) . toLowerCase ( ) ) ; if ( sfsGeomCode == null ) { return GeometryTypeCodes . GEOMETRY ; } else { return sfsGeomCode ; } }
Return the sfs geometry type identifier of the provided Geometry
6,274
public static int getGeometryType ( Connection connection , TableLocation location , String fieldName ) throws SQLException { if ( fieldName == null || fieldName . isEmpty ( ) ) { List < String > geometryFields = getGeometryFields ( connection , location ) ; if ( geometryFields . isEmpty ( ) ) { throw new SQLException ( "The table " + location + " does not contain a Geometry field, " + "then geometry type cannot be computed" ) ; } fieldName = geometryFields . get ( 0 ) ; } ResultSet geomResultSet = getGeometryColumnsView ( connection , location . getCatalog ( ) , location . getSchema ( ) , location . getTable ( ) ) ; boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; while ( geomResultSet . next ( ) ) { if ( fieldName . isEmpty ( ) || geomResultSet . getString ( "F_GEOMETRY_COLUMN" ) . equalsIgnoreCase ( fieldName ) ) { if ( isH2 ) { return geomResultSet . getInt ( "GEOMETRY_TYPE" ) ; } else { return GEOM_TYPE_TO_SFS_CODE . get ( geomResultSet . getString ( "type" ) . toLowerCase ( ) ) ; } } } throw new SQLException ( "Field not found " + fieldName ) ; }
Return the sfs geometry type identifier of the provided field of the provided table .
6,275
public static Map < String , Integer > getGeometryTypes ( Connection connection , TableLocation location ) throws SQLException { Map < String , Integer > map = new HashMap < > ( ) ; ResultSet geomResultSet = getGeometryColumnsView ( connection , location . getCatalog ( ) , location . getSchema ( ) , location . getTable ( ) ) ; boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; while ( geomResultSet . next ( ) ) { String fieldName = geomResultSet . getString ( "F_GEOMETRY_COLUMN" ) ; int type ; if ( isH2 ) { type = geomResultSet . getInt ( "GEOMETRY_TYPE" ) ; } else { type = GEOM_TYPE_TO_SFS_CODE . get ( geomResultSet . getString ( "type" ) . toLowerCase ( ) ) ; } map . put ( fieldName , type ) ; } return map ; }
Returns a map containing the field names as key and the SFS geometry type as value from the given table .
6,276
public static Envelope getTableEnvelope ( Connection connection , TableLocation location , String geometryField ) throws SQLException { if ( geometryField == null || geometryField . isEmpty ( ) ) { List < String > geometryFields = getGeometryFields ( connection , location ) ; if ( geometryFields . isEmpty ( ) ) { throw new SQLException ( "The table " + location + " does not contain a Geometry field, then the extent " + "cannot be computed" ) ; } geometryField = geometryFields . get ( 0 ) ; } ResultSet rs = connection . createStatement ( ) . executeQuery ( "SELECT ST_Extent(" + TableLocation . quoteIdentifier ( geometryField ) + ") ext FROM " + location ) ; if ( rs . next ( ) ) { return ( ( Geometry ) rs . getObject ( 1 ) ) . getEnvelopeInternal ( ) ; } throw new SQLException ( "Unable to get the table extent it may be empty" ) ; }
Merge the bounding box of all geometries inside the provided table .
6,277
public static PreparedStatement prepareInformationSchemaStatement ( Connection connection , String catalog , String schema , String table , String informationSchemaTable , String endQuery , String catalog_field , String schema_field , String table_field ) throws SQLException { Integer catalogIndex = null ; Integer schemaIndex = null ; Integer tableIndex = 1 ; StringBuilder sb = new StringBuilder ( "SELECT * from " + informationSchemaTable + " where " ) ; if ( ! catalog . isEmpty ( ) ) { sb . append ( "UPPER(" ) ; sb . append ( catalog_field ) ; sb . append ( ") = ? AND " ) ; catalogIndex = 1 ; tableIndex ++ ; } if ( ! schema . isEmpty ( ) ) { sb . append ( "UPPER(" ) ; sb . append ( schema_field ) ; sb . append ( ") = ? AND " ) ; schemaIndex = tableIndex ; tableIndex ++ ; } sb . append ( "UPPER(" ) ; sb . append ( table_field ) ; sb . append ( ") = ? " ) ; sb . append ( endQuery ) ; PreparedStatement preparedStatement = connection . prepareStatement ( sb . toString ( ) ) ; if ( catalogIndex != null ) { preparedStatement . setString ( catalogIndex , catalog . toUpperCase ( ) ) ; } if ( schemaIndex != null ) { preparedStatement . setString ( schemaIndex , schema . toUpperCase ( ) ) ; } preparedStatement . setString ( tableIndex , table . toUpperCase ( ) ) ; return preparedStatement ; }
For table containing catalog schema and table name this function create a prepared statement with a filter on this combination .
6,278
public static PreparedStatement prepareInformationSchemaStatement ( Connection connection , String catalog , String schema , String table , String informationSchemaTable , String endQuery ) throws SQLException { return prepareInformationSchemaStatement ( connection , catalog , schema , table , informationSchemaTable , endQuery , "f_table_catalog" , "f_table_schema" , "f_table_name" ) ; }
For table containing catalog schema and table name this function create a prepared statement with a filter on this combination . Use f_table_catalog f_table_schema f_table_name as field names .
6,279
public static List < String > getGeometryFields ( ResultSet resultSet ) throws SQLException { List < String > fieldsName = new LinkedList < > ( ) ; ResultSetMetaData meta = resultSet . getMetaData ( ) ; int columnCount = meta . getColumnCount ( ) ; for ( int i = 1 ; i <= columnCount ; i ++ ) { if ( meta . getColumnTypeName ( i ) . equalsIgnoreCase ( "geometry" ) ) { fieldsName . add ( meta . getColumnName ( i ) ) ; } } return fieldsName ; }
Find geometry fields name of a resultSet .
6,280
public static boolean hasGeometryField ( ResultSet resultSet ) throws SQLException { ResultSetMetaData meta = resultSet . getMetaData ( ) ; int columnCount = meta . getColumnCount ( ) ; for ( int i = 1 ; i <= columnCount ; i ++ ) { if ( meta . getColumnTypeName ( i ) . equalsIgnoreCase ( "geometry" ) ) { return true ; } } return false ; }
Check if the ResultSet contains a geometry field
6,281
public static Envelope getResultSetEnvelope ( ResultSet resultSet ) throws SQLException { List < String > geometryFields = getGeometryFields ( resultSet ) ; if ( geometryFields . isEmpty ( ) ) { throw new SQLException ( "This ResultSet doesn't contain any geometry field." ) ; } else { return getResultSetEnvelope ( resultSet , geometryFields . get ( 0 ) ) ; } }
Compute the full extend of a ResultSet using the first geometry field . If the ResultSet does not contain any geometry field throw an exception
6,282
public static Envelope getResultSetEnvelope ( ResultSet resultSet , String fieldName ) throws SQLException { Envelope aggregatedEnvelope = null ; while ( resultSet . next ( ) ) { Geometry geom = ( Geometry ) resultSet . getObject ( fieldName ) ; if ( aggregatedEnvelope != null ) { aggregatedEnvelope . expandToInclude ( geom . getEnvelopeInternal ( ) ) ; } else { aggregatedEnvelope = geom . getEnvelopeInternal ( ) ; } } return aggregatedEnvelope ; }
Compute the full extend of a ResultSet using a specified geometry field . If the ResultSet does not contain this geometry field throw an exception
6,283
public static int getSRID ( Connection connection , TableLocation table ) throws SQLException { ResultSet geomResultSet = getGeometryColumnsView ( connection , table . getCatalog ( ) , table . getSchema ( ) , table . getTable ( ) ) ; int srid = 0 ; while ( geomResultSet . next ( ) ) { srid = geomResultSet . getInt ( "srid" ) ; break ; } geomResultSet . close ( ) ; return srid ; }
Return the SRID of the first geometry column of the input table
6,284
public static void addTableSRIDConstraint ( Connection connection , TableLocation tableLocation , int srid ) throws SQLException { if ( srid > 0 ) { connection . createStatement ( ) . execute ( String . format ( "ALTER TABLE %s ADD CHECK ST_SRID(the_geom)=%d" , tableLocation . toString ( ) , srid ) ) ; } }
Alter a table to add a SRID constraint . The srid must be greater than zero .
6,285
public MockInternetGateway createInternetGateway ( ) { MockInternetGateway ret = new MockInternetGateway ( ) ; ret . setInternetGatewayId ( "InternetGateway-" + UUID . randomUUID ( ) . toString ( ) . substring ( 0 , INTERNETGATEWAY_ID_POSTFIX_LENGTH ) ) ; allMockInternetGateways . put ( ret . getInternetGatewayId ( ) , ret ) ; return ret ; }
Create the mock InternetGateway .
6,286
public MockInternetGateway attachInternetGateway ( final String internetgatewayId , final String vpcId ) { if ( internetgatewayId == null ) { return null ; } MockInternetGateway ret = allMockInternetGateways . get ( internetgatewayId ) ; if ( ret != null ) { MockInternetGatewayAttachmentType internetGatewayAttachmentType = new MockInternetGatewayAttachmentType ( ) ; internetGatewayAttachmentType . setVpcId ( vpcId ) ; internetGatewayAttachmentType . setState ( "Available" ) ; List < MockInternetGatewayAttachmentType > internetGatewayAttachmentSet = new ArrayList < MockInternetGatewayAttachmentType > ( ) ; internetGatewayAttachmentSet . add ( internetGatewayAttachmentType ) ; ret . setAttachmentSet ( internetGatewayAttachmentSet ) ; allMockInternetGateways . put ( ret . getInternetGatewayId ( ) , ret ) ; } return ret ; }
Attach the mock InternetGateway .
6,287
public MockInternetGateway deleteInternetGateway ( final String internetgatewayId ) { if ( internetgatewayId != null && allMockInternetGateways . containsKey ( internetgatewayId ) ) { return allMockInternetGateways . remove ( internetgatewayId ) ; } return null ; }
Delete InternetGateway .
6,288
private static long getMsFromProperty ( final String propertyName , final String propertyNameInSeconds ) { String property = PropertiesUtils . getProperty ( propertyName ) ; if ( property != null ) { return Long . parseLong ( property ) ; } return Integer . parseInt ( PropertiesUtils . getProperty ( propertyNameInSeconds ) ) * MILLISECS_IN_A_SECOND ; }
Get millisecs from properties .
6,289
public final void initializeInternalTimer ( ) { if ( ! internalTimerInitialized ) { TimerTask internalTimerTask = new TimerTask ( ) { public void run ( ) { if ( terminated ) { running = false ; booting = false ; stopping = false ; pubDns = null ; this . cancel ( ) ; onTerminated ( ) ; return ; } if ( running ) { if ( booting ) { if ( MAX_BOOT_TIME_MILLS != 0 ) { try { Thread . sleep ( MIN_BOOT_TIME_MILLS + random . nextInt ( ( int ) ( MAX_BOOT_TIME_MILLS - MIN_BOOT_TIME_MILLS ) ) ) ; } catch ( InterruptedException e ) { throw new AwsMockException ( "InterruptedException caught when delaying a mock random 'boot time'" , e ) ; } } pubDns = generatePubDns ( ) ; booting = false ; onBooted ( ) ; } else if ( stopping ) { if ( MAX_SHUTDOWN_TIME_MILLS != 0 ) { try { Thread . sleep ( MIN_SHUTDOWN_TIME_MILLS + random . nextInt ( ( int ) ( MAX_SHUTDOWN_TIME_MILLS - MIN_SHUTDOWN_TIME_MILLS ) ) ) ; } catch ( InterruptedException e ) { throw new AwsMockException ( "InterruptedException caught when delaying a mock random 'shutdown time'" , e ) ; } } pubDns = null ; stopping = false ; running = false ; onStopped ( ) ; } onInternalTimer ( ) ; } } } ; timer = new SerializableTimer ( true ) ; timer . schedule ( internalTimerTask , 0L , TIMER_INTERVAL_MILLIS ) ; internalTimerInitialized = true ; } }
Start scheduling the internal timer that controls the behaviors and states of this mock ec2 instance .
6,290
public final boolean start ( ) { if ( running || booting || stopping || terminated ) { return false ; } else { booting = true ; running = true ; onStarted ( ) ; return true ; } }
Start a stopped mock ec2 instance .
6,291
public final boolean stop ( ) { if ( booting || running ) { stopping = true ; booting = false ; onStopping ( ) ; return true ; } else { return false ; } }
Stop this ec2 instance .
6,292
public final InstanceState getInstanceState ( ) { return isTerminated ( ) ? InstanceState . TERMINATED : ( isBooting ( ) ? InstanceState . PENDING : ( isStopping ( ) ? InstanceState . STOPPING : ( isRunning ( ) ? InstanceState . RUNNING : InstanceState . STOPPED ) ) ) ; }
Get state of this mock ec2 instance .
6,293
public static List < Instance > describeAllInstances ( ) { AWSCredentials credentials = new BasicAWSCredentials ( "foo" , "bar" ) ; AmazonEC2Client amazonEC2Client = new AmazonEC2Client ( credentials ) ; String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/" ; amazonEC2Client . setEndpoint ( ec2Endpoint ) ; DescribeInstancesResult response = amazonEC2Client . describeInstances ( ) ; List < Reservation > reservations = response . getReservations ( ) ; List < Instance > ret = new ArrayList < Instance > ( ) ; for ( Reservation reservation : reservations ) { List < Instance > instances = reservation . getInstances ( ) ; if ( null != instances ) { for ( Instance i : instances ) { ret . add ( i ) ; } } } return ret ; }
Describe all mock instances within aws - mock .
6,294
public MockSubnet createSubnet ( final String cidrBlock , final String vpcId ) { MockSubnet ret = new MockSubnet ( ) ; ret . setCidrBlock ( cidrBlock ) ; ret . setSubnetId ( "subnet-" + UUID . randomUUID ( ) . toString ( ) . substring ( 0 , SUBNET_ID_POSTFIX_LENGTH ) ) ; ret . setVpcId ( vpcId ) ; allMockSubnets . put ( ret . getSubnetId ( ) , ret ) ; return ret ; }
Create the mock Subnet .
6,295
public MockSubnet deleteSubnet ( final String subnetId ) { if ( subnetId != null && allMockSubnets . containsKey ( subnetId ) ) { return allMockSubnets . remove ( subnetId ) ; } return null ; }
Delete Subnet .
6,296
private Set < String > parseInstanceStates ( final Map < String , String [ ] > queryParams ) { Set < String > instanceStates = new TreeSet < String > ( ) ; for ( String queryKey : queryParams . keySet ( ) ) { if ( queryKey . startsWith ( "Filter.1.Value" ) ) { for ( String state : queryParams . get ( queryKey ) ) { instanceStates . add ( state ) ; } } } return instanceStates ; }
Parse instance states from query parameters .
6,297
private DescribeAvailabilityZonesResponseType describeAvailabilityZones ( ) { DescribeAvailabilityZonesResponseType ret = new DescribeAvailabilityZonesResponseType ( ) ; ret . setRequestId ( UUID . randomUUID ( ) . toString ( ) ) ; AvailabilityZoneSetType info = new AvailabilityZoneSetType ( ) ; AvailabilityZoneItemType item = new AvailabilityZoneItemType ( ) ; item . setRegionName ( currentRegion ) ; item . setZoneName ( currentRegion ) ; info . getItem ( ) . add ( item ) ; ret . setAvailabilityZoneInfo ( info ) ; return ret ; }
Handles describeAvailabilityZones request as simple as without any filters to use .
6,298
private Set < String > parseInstanceIDs ( final Map < String , String [ ] > queryParams ) { Set < String > ret = new TreeSet < String > ( ) ; Set < Map . Entry < String , String [ ] > > entries = queryParams . entrySet ( ) ; for ( Map . Entry < String , String [ ] > entry : entries ) { if ( null != entry && null != entry . getKey ( ) && entry . getKey ( ) . matches ( "InstanceId\\.(\\d)+" ) ) { if ( null != entry . getValue ( ) && entry . getValue ( ) . length > 0 ) { ret . add ( entry . getValue ( ) [ 0 ] ) ; } } } return ret ; }
Parse instance IDs from query parameters .
6,299
protected String generateToken ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < TOKEN_MIDDLE_LEN ; i ++ ) { sb . append ( TOKEN_DICT . charAt ( random . nextInt ( TOKEN_DICT . length ( ) ) ) ) ; } return TOKEN_PREFIX + sb . toString ( ) + TOKEN_SUFFIX ; }
Generate a new token used in describeInstanceResponse while paging enabled .