idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
6,000
public static void toGeojsonMultiPolygon ( MultiPolygon multiPolygon , StringBuilder sb ) { sb . append ( "{\"type\":\"MultiPolygon\",\"coordinates\":[" ) ; for ( int i = 0 ; i < multiPolygon . getNumGeometries ( ) ; i ++ ) { Polygon p = ( Polygon ) multiPolygon . getGeometryN ( i ) ; sb . append ( "[" ) ; toGeojsonCoordinates ( p . getExteriorRing ( ) . getCoordinates ( ) , sb ) ; for ( int j = 0 ; j < p . getNumInteriorRing ( ) ; j ++ ) { sb . append ( "," ) ; toGeojsonCoordinates ( p . getInteriorRingN ( j ) . getCoordinates ( ) , sb ) ; } sb . append ( "]" ) ; if ( i < multiPolygon . getNumGeometries ( ) - 1 ) { sb . append ( "," ) ; } } sb . append ( "]}" ) ; }
Coordinates of a MultiPolygon are an array of Polygon coordinate arrays .
6,001
public static void toGeojsonGeometryCollection ( GeometryCollection geometryCollection , StringBuilder sb ) { sb . append ( "{\"type\":\"GeometryCollection\",\"geometries\":[" ) ; for ( int i = 0 ; i < geometryCollection . getNumGeometries ( ) ; i ++ ) { Geometry geom = geometryCollection . getGeometryN ( i ) ; if ( geom instanceof Point ) { toGeojsonPoint ( ( Point ) geom , sb ) ; } else if ( geom instanceof LineString ) { toGeojsonLineString ( ( LineString ) geom , sb ) ; } else if ( geom instanceof Polygon ) { toGeojsonPolygon ( ( Polygon ) geom , sb ) ; } if ( i < geometryCollection . getNumGeometries ( ) - 1 ) { sb . append ( "," ) ; } } sb . append ( "]}" ) ; }
A GeoJSON object with type GeometryCollection is a geometry object which represents a collection of geometry objects .
6,002
public static void toGeojsonCoordinates ( Coordinate [ ] coords , StringBuilder sb ) { sb . append ( "[" ) ; for ( int i = 0 ; i < coords . length ; i ++ ) { toGeojsonCoordinate ( coords [ i ] , sb ) ; if ( i < coords . length - 1 ) { sb . append ( "," ) ; } } sb . append ( "]" ) ; }
Convert a jts array of coordinates to a GeoJSON coordinates representation .
6,003
public static void toGeojsonCoordinate ( Coordinate coord , StringBuilder sb ) { sb . append ( "[" ) ; sb . append ( coord . x ) . append ( "," ) . append ( coord . y ) ; if ( ! Double . isNaN ( coord . z ) ) { sb . append ( "," ) . append ( coord . z ) ; } sb . append ( "]" ) ; }
Convert a JTS coordinate to a GeoJSON representation .
6,004
public String toGeoJsonEnvelope ( Envelope e ) { return new StringBuffer ( ) . append ( "[" ) . append ( e . getMinX ( ) ) . append ( "," ) . append ( e . getMinY ( ) ) . append ( "," ) . append ( e . getMaxX ( ) ) . append ( "," ) . append ( e . getMaxY ( ) ) . append ( "]" ) . toString ( ) ; }
Convert a JTS Envelope to a GeoJSON representation .
6,005
public static void downloadOSMFile ( File file , Envelope geometryEnvelope ) throws IOException { HttpURLConnection urlCon = ( HttpURLConnection ) createOsmUrl ( geometryEnvelope ) . openConnection ( ) ; urlCon . setRequestMethod ( "GET" ) ; urlCon . connect ( ) ; switch ( urlCon . getResponseCode ( ) ) { case 400 : throw new IOException ( "Error : Cannot query the OSM API with the following bounding box" ) ; case 509 : throw new IOException ( "Error: You have downloaded too much data. Please try again later" ) ; default : InputStream in = urlCon . getInputStream ( ) ; OutputStream out = new FileOutputStream ( file ) ; try { byte [ ] data = new byte [ 4096 ] ; while ( true ) { int numBytes = in . read ( data ) ; if ( numBytes == - 1 ) { break ; } out . write ( data , 0 , numBytes ) ; } } finally { out . close ( ) ; in . close ( ) ; } break ; } }
Download OSM file from the official server
6,006
private static URL createOsmUrl ( Envelope geometryEnvelope ) { try { return new URL ( OSM_API_URL + "map?bbox=" + geometryEnvelope . getMinX ( ) + "," + geometryEnvelope . getMinY ( ) + "," + geometryEnvelope . getMaxX ( ) + "," + geometryEnvelope . getMaxY ( ) ) ; } catch ( MalformedURLException e ) { throw new IllegalStateException ( e ) ; } }
Build the OSM URL based on a given envelope
6,007
public static Boolean geomDisjoint ( Geometry a , Geometry b ) { if ( a == null || b == null ) { return null ; } return a . disjoint ( b ) ; }
Return true if the two Geometries are disjoint
6,008
public void write ( ProgressVisitor progress ) throws SQLException { if ( FileUtil . isExtensionWellFormated ( fileName , "kml" ) ) { writeKML ( progress ) ; } else if ( FileUtil . isExtensionWellFormated ( fileName , "kmz" ) ) { String name = fileName . getName ( ) ; int pos = name . lastIndexOf ( "." ) ; writeKMZ ( progress , name . substring ( 0 , pos ) + ".kml" ) ; } else { throw new SQLException ( "Please use the extensions .kml or kmz." ) ; } }
Write spatial table to kml or kmz file format .
6,009
private void writeKML ( ProgressVisitor progress ) throws SQLException { FileOutputStream fos = null ; try { fos = new FileOutputStream ( fileName ) ; writeKMLDocument ( progress , fos ) ; } catch ( FileNotFoundException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( fos != null ) { fos . close ( ) ; } } catch ( IOException ex ) { throw new SQLException ( ex ) ; } } }
Write the spatial table to a KML format
6,010
private void writeKMZ ( ProgressVisitor progress , String fileNameWithExtension ) throws SQLException { ZipOutputStream zos = null ; try { zos = new ZipOutputStream ( new FileOutputStream ( fileName ) ) ; zos . putNextEntry ( new ZipEntry ( fileNameWithExtension ) ) ; writeKMLDocument ( progress , zos ) ; } catch ( FileNotFoundException ex ) { throw new SQLException ( ex ) ; } catch ( IOException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( zos != null ) { zos . closeEntry ( ) ; zos . finish ( ) ; } } catch ( IOException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( zos != null ) { zos . close ( ) ; } } catch ( IOException ex ) { throw new SQLException ( ex ) ; } } } }
Write the spatial table to a KMZ format
6,011
private void writeKMLDocument ( ProgressVisitor progress , OutputStream outputStream ) throws SQLException { List < String > spatialFieldNames = SFSUtilities . getGeometryFields ( connection , TableLocation . parse ( tableName , JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ) ) ; if ( spatialFieldNames . isEmpty ( ) ) { throw new SQLException ( String . format ( "The table %s does not contain a geometry field" , tableName ) ) ; } try { final XMLOutputFactory streamWriterFactory = XMLOutputFactory . newFactory ( ) ; streamWriterFactory . setProperty ( "escapeCharacters" , false ) ; XMLStreamWriter xmlOut = streamWriterFactory . createXMLStreamWriter ( new BufferedOutputStream ( outputStream ) , "UTF-8" ) ; xmlOut . writeStartDocument ( "UTF-8" , "1.0" ) ; xmlOut . writeStartElement ( "kml" ) ; xmlOut . writeDefaultNamespace ( "http://www.opengis.net/kml/2.2" ) ; xmlOut . writeNamespace ( "atom" , "http://www.w3.org/2005/Atom" ) ; xmlOut . writeNamespace ( "kml" , "http://www.opengis.net/kml/2.2" ) ; xmlOut . writeNamespace ( "gx" , "http://www.google.com/kml/ext/2.2" ) ; xmlOut . writeNamespace ( "xal" , "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" ) ; xmlOut . writeStartElement ( "Document" ) ; try ( Statement st = connection . createStatement ( ) ) { ResultSet rs = st . executeQuery ( String . format ( "select * from %s" , tableName ) ) ; try { int recordCount = JDBCUtilities . getRowCount ( connection , tableName ) ; ProgressVisitor copyProgress = progress . subProcess ( recordCount ) ; ResultSetMetaData resultSetMetaData = rs . getMetaData ( ) ; int geoFieldIndex = JDBCUtilities . getFieldIndex ( resultSetMetaData , spatialFieldNames . get ( 0 ) ) ; writeSchema ( xmlOut , resultSetMetaData ) ; xmlOut . writeStartElement ( "Folder" ) ; xmlOut . writeStartElement ( "name" ) ; xmlOut . writeCharacters ( tableName ) ; xmlOut . writeEndElement ( ) ; while ( rs . next ( ) ) { writePlacemark ( xmlOut , rs , geoFieldIndex , spatialFieldNames . get ( 0 ) ) ; copyProgress . endStep ( ) ; } } finally { rs . close ( ) ; } } xmlOut . writeEndElement ( ) ; xmlOut . writeEndElement ( ) ; xmlOut . writeEndDocument ( ) ; xmlOut . close ( ) ; } catch ( XMLStreamException ex ) { throw new SQLException ( ex ) ; } }
Write the KML document Note the document stores only the first geometry column in the placeMark element . The other geomtry columns are ignored .
6,012
public void writePlacemark ( XMLStreamWriter xmlOut , ResultSet rs , int geoFieldIndex , String spatialFieldName ) throws XMLStreamException , SQLException { xmlOut . writeStartElement ( "Placemark" ) ; if ( columnCount > 1 ) { writeExtendedData ( xmlOut , rs ) ; } StringBuilder sb = new StringBuilder ( ) ; Geometry geom = ( Geometry ) rs . getObject ( geoFieldIndex ) ; int inputSRID = geom . getSRID ( ) ; if ( inputSRID == 0 ) { throw new SQLException ( "A coordinate reference system must be set to save the KML file" ) ; } else if ( inputSRID != 4326 ) { throw new SQLException ( "The kml format supports only the WGS84 projection. \n" + "Please use ST_Transform(" + spatialFieldName + "," + inputSRID + ")" ) ; } KMLGeometry . toKMLGeometry ( geom , ExtrudeMode . NONE , AltitudeMode . NONE , sb ) ; xmlOut . writeCharacters ( sb . toString ( ) ) ; xmlOut . writeEndElement ( ) ; }
A Placemark is a Feature with associated Geometry .
6,013
private static String getKMLType ( int sqlTypeId , String sqlTypeName ) throws SQLException { switch ( sqlTypeId ) { case Types . BOOLEAN : return "bool" ; case Types . DOUBLE : return "double" ; case Types . FLOAT : return "float" ; case Types . INTEGER : case Types . BIGINT : return "int" ; case Types . SMALLINT : return "short" ; case Types . DATE : case Types . VARCHAR : case Types . NCHAR : case Types . CHAR : return "string" ; default : throw new SQLException ( "Field type not supported by KML : " + sqlTypeName ) ; } }
Return the kml type representation from SQL data type
6,014
public static Boolean geomTouches ( Geometry a , Geometry b ) { if ( a == null || b == null ) { return null ; } return a . touches ( b ) ; }
Return true if the geometry A touches the geometry B
6,015
public static Geometry removeCoordinates ( Geometry geom ) { if ( geom == null ) { return null ; } else if ( geom . isEmpty ( ) ) { return geom ; } else if ( geom instanceof Point ) { return geom ; } else if ( geom instanceof MultiPoint ) { return removeCoordinates ( ( MultiPoint ) geom ) ; } else if ( geom instanceof LineString ) { return removeCoordinates ( ( LineString ) geom ) ; } else if ( geom instanceof MultiLineString ) { return removeCoordinates ( ( MultiLineString ) geom ) ; } else if ( geom instanceof Polygon ) { return removeCoordinates ( ( Polygon ) geom ) ; } else if ( geom instanceof MultiPolygon ) { return removeCoordinates ( ( MultiPolygon ) geom ) ; } else if ( geom instanceof GeometryCollection ) { return removeCoordinates ( ( GeometryCollection ) geom ) ; } return null ; }
Removes duplicated coordinates within a geometry .
6,016
public static MultiPoint removeCoordinates ( MultiPoint g ) { Coordinate [ ] coords = CoordinateUtils . removeDuplicatedCoordinates ( g . getCoordinates ( ) , false ) ; return FACTORY . createMultiPoint ( coords ) ; }
Removes duplicated coordinates within a MultiPoint .
6,017
public static void writeKML ( Connection connection , String fileName , String tableReference ) throws SQLException , IOException { KMLDriverFunction kMLDriverFunction = new KMLDriverFunction ( ) ; kMLDriverFunction . exportTable ( connection , tableReference , URIUtilities . fileFromString ( fileName ) , new EmptyProgressVisitor ( ) ) ; }
This method is used to write a spatial table into a KML file
6,018
public static GeometryLocation getVertexToSnap ( Geometry g , Point p , double tolerance ) { DistanceOp distanceOp = new DistanceOp ( g , p ) ; GeometryLocation snapedPoint = distanceOp . nearestLocations ( ) [ 0 ] ; if ( tolerance == 0 || snapedPoint . getCoordinate ( ) . distance ( p . getCoordinate ( ) ) <= tolerance ) { return snapedPoint ; } return null ; }
Gets the coordinate of a Geometry that is the nearest of a given Point with a distance tolerance .
6,019
public static Geometry computeBoundingCircle ( Geometry geometry ) { if ( geometry == null ) { return null ; } return new MinimumBoundingCircle ( geometry ) . getCircle ( ) ; }
Computes the bounding circle
6,020
public void write ( Object [ ] record ) throws IOException , DbaseFileException { if ( record . length != header . getNumFields ( ) ) { throw new DbaseFileException ( "Wrong number of fields " + record . length + " expected " + header . getNumFields ( ) ) ; } buffer . position ( 0 ) ; buffer . put ( ( byte ) ' ' ) ; for ( int i = 0 ; i < header . getNumFields ( ) ; i ++ ) { String fieldString = fieldString ( record [ i ] , i ) ; if ( header . getFieldLength ( i ) != fieldString . getBytes ( charset . name ( ) ) . length ) { buffer . put ( new byte [ header . getFieldLength ( i ) ] ) ; } else { buffer . put ( fieldString . getBytes ( charset . name ( ) ) ) ; } } write ( ) ; }
Write a single dbase record .
6,021
public static Double getMaxX ( Geometry geom ) { if ( geom != null ) { return geom . getEnvelopeInternal ( ) . getMaxX ( ) ; } else { return null ; } }
Returns the maximal x - value of the given geometry .
6,022
public void put ( Geometry geom , MODE mode ) throws IllegalArgumentException { gf = geom . getFactory ( ) ; convertedInput = null ; int dimension ; if ( geom . getClass ( ) . getName ( ) . equals ( GeometryCollection . class . getName ( ) ) ) { dimension = getMinDimension ( ( GeometryCollection ) geom ) ; } else { dimension = geom . getDimension ( ) ; } if ( mode != MODE . TESSELLATION ) { Geometry convexHull = new FullConvexHull ( geom ) . getConvexHull ( ) ; if ( convexHull instanceof Polygon && convexHull . isValid ( ) ) { if ( geom . getClass ( ) . getName ( ) . equals ( GeometryCollection . class . getName ( ) ) ) { if ( dimension > 0 ) { try { geom = ST_ToMultiLine . createMultiLineString ( geom ) . union ( ) ; } catch ( SQLException ex ) { throw new IllegalArgumentException ( ex ) ; } if ( geom . getClass ( ) . getName ( ) . equals ( GeometryCollection . class . getName ( ) ) ) { throw new IllegalArgumentException ( "Delaunay does not support mixed geometry type" ) ; } } } if ( dimension > 0 ) { geom = ( ( Polygon ) convexHull ) . getExteriorRing ( ) . union ( geom ) ; } else { ST_Accum accum = new ST_Accum ( ) ; try { accum . add ( geom ) ; accum . add ( convexHull ) ; geom = accum . getResult ( ) ; } catch ( SQLException ex ) { LOGGER . error ( ex . getLocalizedMessage ( ) , ex ) ; } } } else { return ; } } CoordinateSequenceDimensionFilter info = CoordinateSequenceDimensionFilter . apply ( geom ) ; isInput2D = info . is2D ( ) ; convertedInput = null ; if ( mode == MODE . TESSELLATION ) { if ( geom instanceof Polygon ) { convertedInput = makePolygon ( ( Polygon ) geom ) ; } else { throw new IllegalArgumentException ( "Only Polygon are accepted for tessellation" ) ; } } else { addGeometry ( geom ) ; } }
Put a geometry into the data array . Set true to populate the list of points and edges needed for the ContrainedDelaunayTriangulation . Set false to populate only the list of points . Note the z - value is forced to O when it s equal to NaN .
6,023
public double get3DArea ( ) { if ( convertedInput != null ) { List < DelaunayTriangle > delaunayTriangle = convertedInput . getTriangles ( ) ; double sum = 0 ; for ( DelaunayTriangle triangle : delaunayTriangle ) { sum += computeTriangleArea3D ( triangle ) ; } return sum ; } else { return 0 ; } }
Return the 3D area of all triangles
6,024
private double computeTriangleArea3D ( DelaunayTriangle triangle ) { TriangulationPoint [ ] points = triangle . points ; TriangulationPoint p1 = points [ 0 ] ; TriangulationPoint p2 = points [ 1 ] ; TriangulationPoint p3 = points [ 2 ] ; double ux = p2 . getX ( ) - p1 . getX ( ) ; double uy = p2 . getY ( ) - p1 . getY ( ) ; double uz = p2 . getZ ( ) - p1 . getZ ( ) ; double vx = p3 . getX ( ) - p1 . getX ( ) ; double vy = p3 . getY ( ) - p1 . getY ( ) ; double vz = p3 . getZ ( ) - p1 . getZ ( ) ; if ( Double . isNaN ( uz ) || Double . isNaN ( vz ) ) { uz = 1 ; vz = 1 ; } double crossx = uy * vz - uz * vy ; double crossy = uz * vx - ux * vz ; double crossz = ux * vy - uy * vx ; double absSq = crossx * crossx + crossy * crossy + crossz * crossz ; return Math . sqrt ( absSq ) / 2 ; }
Computes the 3D area of a triangle .
6,025
private void addGeometry ( Geometry geom ) throws IllegalArgumentException { if ( ! geom . isValid ( ) ) { throw new IllegalArgumentException ( "Provided geometry is not valid !" ) ; } if ( geom instanceof GeometryCollection ) { Map < TriangulationPoint , Integer > pts = new HashMap < TriangulationPoint , Integer > ( geom . getNumPoints ( ) ) ; List < Integer > segments = new ArrayList < Integer > ( pts . size ( ) ) ; AtomicInteger pointsCount = new AtomicInteger ( 0 ) ; PointHandler pointHandler = new PointHandler ( this , pts , pointsCount ) ; LineStringHandler lineStringHandler = new LineStringHandler ( this , pts , pointsCount , segments ) ; for ( int geomId = 0 ; geomId < geom . getNumGeometries ( ) ; geomId ++ ) { addSimpleGeometry ( geom . getGeometryN ( geomId ) , pointHandler , lineStringHandler ) ; } int [ ] index = new int [ segments . size ( ) ] ; for ( int i = 0 ; i < index . length ; i ++ ) { index [ i ] = segments . get ( i ) ; } TriangulationPoint [ ] ptsArray = new TriangulationPoint [ pointsCount . get ( ) ] ; for ( Map . Entry < TriangulationPoint , Integer > entry : pts . entrySet ( ) ) { ptsArray [ entry . getValue ( ) ] = entry . getKey ( ) ; } pts . clear ( ) ; convertedInput = new ConstrainedPointSet ( Arrays . asList ( ptsArray ) , index ) ; } else { addGeometry ( geom . getFactory ( ) . createGeometryCollection ( new Geometry [ ] { geom } ) ) ; } }
Add a geometry to the list of points and edges used by the triangulation .
6,026
public final void setAttribute ( String currentElement , StringBuilder contentBuffer ) { if ( currentElement . equalsIgnoreCase ( GPXTags . NAME ) ) { setName ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . CMT ) ) { setCmt ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . DESC ) ) { setDesc ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . SRC ) ) { setSrc ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . NUMBER ) ) { setNumber ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . TYPE ) ) { setType ( contentBuffer ) ; } else if ( currentElement . equalsIgnoreCase ( GPXTags . EXTENSIONS ) ) { setExtensions ( ) ; } }
Set an attribute for a line . The String currentElement gives the information of which attribute have to be setted . The attribute to set is given by the StringBuilder contentBuffer .
6,027
public final void setLink ( Attributes attributes ) { lineValues [ GpxMetadata . LINELINK_HREF ] = attributes . getValue ( GPXTags . HREF ) ; }
Set a link to additional information about the route or the track .
6,028
public final void setNumber ( StringBuilder contentBuffer ) { lineValues [ GpxMetadata . LINENUMBER ] = Integer . parseInt ( contentBuffer . toString ( ) ) ; }
Set the GPS number to additional information about the route or the track .
6,029
public static Geometry densify ( Geometry geometry , double tolerance ) { if ( geometry == null ) { return null ; } return Densifier . densify ( geometry , tolerance ) ; }
Densify a geometry using the given distance tolerance .
6,030
public static TableLocation parseInputTable ( Connection connection , String inputTable ) throws SQLException { return TableLocation . parse ( inputTable , JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ) ; }
Convert an input table String to a TableLocation
6,031
public static TableLocation suffixTableLocation ( TableLocation inputTable , String suffix ) { return new TableLocation ( inputTable . getCatalog ( ) , inputTable . getSchema ( ) , inputTable . getTable ( ) + suffix ) ; }
Suffix a TableLocation
6,032
public static String caseIdentifier ( TableLocation requestedTable , String tableName , boolean isH2 ) { return new TableLocation ( requestedTable . getCatalog ( ) , requestedTable . getSchema ( ) , TableLocation . parse ( tableName , isH2 ) . getTable ( ) ) . toString ( ) ; }
Return the table identifier in the best fit depending on database type
6,033
public static CoordinateSequenceDimensionFilter apply ( Geometry geometry ) { CoordinateSequenceDimensionFilter cd = new CoordinateSequenceDimensionFilter ( ) ; geometry . apply ( cd ) ; return cd ; }
Init CoordinateSequenceDimensionFilter object .
6,034
public int removeColumn ( String inFieldName ) { int retCol = - 1 ; int tempLength = 1 ; DbaseField [ ] tempFieldDescriptors = new DbaseField [ fields . length - 1 ] ; for ( int i = 0 , j = 0 ; i < fields . length ; i ++ ) { if ( ! inFieldName . equalsIgnoreCase ( fields [ i ] . fieldName . trim ( ) ) ) { if ( i == j && i == fields . length - 1 ) { throw new IllegalArgumentException ( "Could not find a field named '" + inFieldName + "' for removal" ) ; } tempFieldDescriptors [ j ] = fields [ i ] ; tempFieldDescriptors [ j ] . fieldDataAddress = tempLength ; tempLength += tempFieldDescriptors [ j ] . fieldLength ; j ++ ; } else { retCol = i ; } } fields = tempFieldDescriptors ; headerLength = 33 + 32 * fields . length ; recordLength = tempLength ; return retCol ; }
Remove a column from this DbaseFileHeader .
6,035
public boolean setEncoding ( String encoding ) { for ( Map . Entry < Byte , String > entry : CODE_PAGE_ENCODING . entrySet ( ) ) { if ( entry . getValue ( ) . equalsIgnoreCase ( encoding ) ) { this . fileEncoding = entry . getValue ( ) ; return true ; } } return false ; }
Set file encoding
6,036
public void writeHeader ( WritableByteChannel out ) throws IOException { if ( headerLength == - 1 ) { headerLength = MINIMUM_HEADER ; } ByteBuffer buffer = ByteBuffer . allocateDirect ( headerLength ) ; buffer . order ( ByteOrder . LITTLE_ENDIAN ) ; buffer . put ( MAGIC ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( new Date ( ) ) ; buffer . put ( ( byte ) ( c . get ( Calendar . YEAR ) % 100 ) ) ; buffer . put ( ( byte ) ( c . get ( Calendar . MONTH ) + 1 ) ) ; buffer . put ( ( byte ) ( c . get ( Calendar . DAY_OF_MONTH ) ) ) ; buffer . putInt ( recordCnt ) ; buffer . putShort ( ( short ) headerLength ) ; buffer . putShort ( ( short ) recordLength ) ; buffer . position ( buffer . position ( ) + 17 ) ; buffer . put ( getEncodingByte ( ) ) ; buffer . position ( buffer . position ( ) + 2 ) ; int tempOffset = 0 ; for ( DbaseField field : fields ) { byte [ ] fieldName = field . fieldName . getBytes ( fileEncoding ) ; for ( int j = 0 ; j < 11 ; j ++ ) { if ( fieldName . length > j ) { buffer . put ( fieldName [ j ] ) ; } else { buffer . put ( ( byte ) 0 ) ; } } buffer . put ( ( byte ) field . fieldType ) ; buffer . putInt ( tempOffset ) ; tempOffset += field . fieldLength ; buffer . put ( ( byte ) field . fieldLength ) ; buffer . put ( ( byte ) field . decimalCount ) ; buffer . position ( buffer . position ( ) + 14 ) ; } buffer . put ( ( byte ) 0x0D ) ; buffer . position ( 0 ) ; int r = buffer . remaining ( ) ; do { r -= out . write ( buffer ) ; } while ( r > 0 ) ; }
Write the header data to the DBF file .
6,037
public static Double getMaxZ ( Geometry geom ) { if ( geom != null ) { return CoordinateUtils . zMinMax ( geom . getCoordinates ( ) ) [ 1 ] ; } else { return null ; } }
Returns the maximal z - value of the given geometry .
6,038
public void exportTable ( Connection connection , String tableReference , File fileName , ProgressVisitor progress , String encoding ) throws SQLException , IOException { final boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; 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 ( ")" ) ) { if ( FileUtil . isExtensionWellFormated ( fileName , "shp" ) ) { PreparedStatement ps = connection . prepareStatement ( tableReference , ResultSet . TYPE_SCROLL_INSENSITIVE , ResultSet . CONCUR_READ_ONLY ) ; ResultSet resultSet = ps . executeQuery ( ) ; int recordCount = 0 ; resultSet . last ( ) ; recordCount = resultSet . getRow ( ) ; resultSet . beforeFirst ( ) ; ProgressVisitor copyProgress = progress . subProcess ( recordCount ) ; List < String > spatialFieldNames = SFSUtilities . getGeometryFields ( resultSet ) ; int srid = doExport ( tableReference , spatialFieldNames , resultSet , recordCount , fileName , progress , encoding ) ; String path = fileName . getAbsolutePath ( ) ; String nameWithoutExt = path . substring ( 0 , path . lastIndexOf ( '.' ) ) ; PRJUtil . writePRJ ( connection , srid , new File ( nameWithoutExt + ".prj" ) ) ; copyProgress . endOfProgress ( ) ; } else { throw new SQLException ( "Only .shp extension is supported" ) ; } } else { throw new SQLException ( "The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'." ) ; } } else { if ( FileUtil . isExtensionWellFormated ( fileName , "shp" ) ) { TableLocation location = TableLocation . parse ( tableReference , isH2 ) ; int recordCount = JDBCUtilities . getRowCount ( connection , tableReference ) ; ProgressVisitor copyProgress = progress . subProcess ( recordCount ) ; List < String > spatialFieldNames = SFSUtilities . getGeometryFields ( connection , TableLocation . parse ( tableReference , isH2 ) ) ; Statement st = connection . createStatement ( ) ; ResultSet rs = st . executeQuery ( String . format ( "select * from %s" , location . toString ( ) ) ) ; doExport ( tableReference , spatialFieldNames , rs , recordCount , fileName , copyProgress , encoding ) ; String path = fileName . getAbsolutePath ( ) ; String nameWithoutExt = path . substring ( 0 , path . lastIndexOf ( '.' ) ) ; PRJUtil . writePRJ ( connection , location , spatialFieldNames . get ( 0 ) , new File ( nameWithoutExt + ".prj" ) ) ; copyProgress . endOfProgress ( ) ; } else { throw new SQLException ( "Only .shp extension is supported" ) ; } } }
Save a table or a query to a shpfile
6,039
private int doExport ( String tableReference , List < String > spatialFieldNames , ResultSet rs , int recordCount , File fileName , ProgressVisitor progress , String encoding ) throws SQLException , IOException { if ( spatialFieldNames . isEmpty ( ) ) { throw new SQLException ( String . format ( "The table or the query %s does not contain a geometry field" , tableReference ) ) ; } int srid = 0 ; ShapeType shapeType = null ; try { ResultSetMetaData resultSetMetaData = rs . getMetaData ( ) ; int geoFieldIndex = JDBCUtilities . getFieldIndex ( resultSetMetaData , spatialFieldNames . get ( 0 ) ) ; ArrayList < Integer > columnIndexes = new ArrayList < Integer > ( ) ; DbaseFileHeader header = DBFDriverFunction . dBaseHeaderFromMetaData ( resultSetMetaData , columnIndexes ) ; columnIndexes . add ( 0 , geoFieldIndex ) ; if ( encoding != null ) { header . setEncoding ( encoding ) ; } header . setNumRecords ( recordCount ) ; SHPDriver shpDriver = null ; Object [ ] row = new Object [ header . getNumFields ( ) + 1 ] ; while ( rs . next ( ) ) { int i = 0 ; for ( Integer index : columnIndexes ) { row [ i ++ ] = rs . getObject ( index ) ; } if ( shpDriver == null ) { byte [ ] wkb = rs . getBytes ( geoFieldIndex ) ; if ( wkb != null ) { GeometryMetaData gm = GeometryMetaData . getMetaDataFromWKB ( wkb ) ; if ( srid == 0 ) { srid = gm . SRID ; } shapeType = getShapeTypeFromGeometryMetaData ( gm ) ; } if ( shapeType != null ) { shpDriver = new SHPDriver ( ) ; shpDriver . setGeometryFieldIndex ( 0 ) ; shpDriver . initDriver ( fileName , shapeType , header ) ; } else { throw new SQLException ( "Unsupported geometry type." ) ; } } if ( shpDriver != null ) { shpDriver . insertRow ( row ) ; } progress . endStep ( ) ; } if ( shpDriver != null ) { shpDriver . close ( ) ; } } finally { rs . close ( ) ; } return srid ; }
Method to export a resulset into a shapefile
6,040
private static ShapeType getShapeTypeFromGeometryMetaData ( GeometryMetaData meta ) throws SQLException { ShapeType shapeType ; switch ( meta . geometryType ) { case GeometryTypeCodes . MULTILINESTRING : case GeometryTypeCodes . LINESTRING : case GeometryTypeCodes . MULTILINESTRINGM : case GeometryTypeCodes . LINESTRINGM : case GeometryTypeCodes . MULTILINESTRINGZ : case GeometryTypeCodes . LINESTRINGZ : shapeType = meta . hasZ ? ShapeType . ARCZ : ShapeType . ARC ; break ; case GeometryTypeCodes . POINT : shapeType = meta . hasZ ? ShapeType . POINTZ : ShapeType . POINT ; break ; case GeometryTypeCodes . MULTIPOINT : shapeType = meta . hasZ ? ShapeType . MULTIPOINTZ : ShapeType . MULTIPOINT ; break ; case GeometryTypeCodes . POLYGON : case GeometryTypeCodes . MULTIPOLYGON : shapeType = meta . hasZ ? ShapeType . POLYGONZ : ShapeType . POLYGON ; break ; default : return null ; } return shapeType ; }
Return the shape type supported by the shapefile format
6,041
private void parseGeoJson ( ProgressVisitor progress ) throws SQLException , IOException { this . progress = progress . subProcess ( 100 ) ; init ( ) ; if ( parseMetadata ( ) ) { GF = new GeometryFactory ( new PrecisionModel ( ) , parsedSRID ) ; parseData ( ) ; setGeometryTypeConstraints ( ) ; } else { throw new SQLException ( "Cannot create the table " + tableLocation + " to import the GeoJSON data" ) ; } }
Parses a GeoJSON 1 . 0 file and writes it to a table .
6,042
private boolean parseMetadata ( ) throws SQLException , IOException { FileInputStream fis = null ; try { fis = new FileInputStream ( fileName ) ; this . fc = fis . getChannel ( ) ; this . fileSize = fc . size ( ) ; readFileSizeEachNode = Math . max ( 1 , ( this . fileSize / AVERAGE_NODE_SIZE ) / 100 ) ; nodeCountProgress = 0 ; cachedColumnNames = new LinkedHashMap < String , String > ( ) ; finalGeometryTypes = new HashSet < String > ( ) ; try ( JsonParser jp = jsFactory . createParser ( fis ) ) { jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; String geomType = jp . getText ( ) ; if ( geomType . equalsIgnoreCase ( GeoJsonField . FEATURECOLLECTION ) ) { parseFeaturesMetadata ( jp ) ; } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'FeatureCollection', found '" + geomType + "'" ) ; } } } catch ( FileNotFoundException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( fis != null ) { fis . close ( ) ; } } catch ( IOException ex ) { throw new IOException ( ex ) ; } } if ( hasGeometryField ) { StringBuilder createTable = new StringBuilder ( ) ; createTable . append ( "CREATE TABLE " ) ; createTable . append ( tableLocation ) ; createTable . append ( " (" ) ; if ( isH2 ) { createTable . append ( "THE_GEOM GEOMETRY" ) ; } else { createTable . append ( "THE_GEOM GEOMETRY(geometry," ) . append ( parsedSRID ) . append ( ")" ) ; } cachedColumnIndex = new HashMap < String , Integer > ( ) ; StringBuilder insertTable = new StringBuilder ( "INSERT INTO " ) ; insertTable . append ( tableLocation ) . append ( " VALUES(?" ) ; int i = 1 ; for ( Map . Entry < String , String > columns : cachedColumnNames . entrySet ( ) ) { String columnName = columns . getKey ( ) ; cachedColumnIndex . put ( columnName , i ++ ) ; createTable . append ( "," ) . append ( columns . getKey ( ) ) . append ( " " ) . append ( columns . getValue ( ) ) ; insertTable . append ( "," ) . append ( "?" ) ; } createTable . append ( ")" ) ; insertTable . append ( ")" ) ; try ( Statement stmt = connection . createStatement ( ) ) { stmt . execute ( createTable . toString ( ) ) ; } preparedStatement = connection . prepareStatement ( insertTable . toString ( ) ) ; return true ; } else { throw new SQLException ( "The geojson file does not contain any geometry." ) ; } }
Parses the all GeoJSON feature to create the PreparedStatement .
6,043
private void parseFeaturesMetadata ( JsonParser jp ) throws IOException , SQLException { jp . nextToken ( ) ; while ( ! jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . FEATURES ) && ! jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . CRS ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; } if ( jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . CRS ) ) { parsedSRID = readCRS ( jp ) ; } if ( jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . FEATURES ) ) { jp . nextToken ( ) ; JsonToken token = jp . nextToken ( ) ; while ( token != JsonToken . END_ARRAY ) { jp . nextToken ( ) ; jp . nextToken ( ) ; String geomType = jp . getText ( ) ; if ( geomType . equalsIgnoreCase ( GeoJsonField . FEATURE ) ) { if ( progress . isCanceled ( ) ) { throw new SQLException ( "Canceled by user" ) ; } parseFeatureMetadata ( jp ) ; token = jp . nextToken ( ) ; featureCounter ++ ; if ( nodeCountProgress ++ % readFileSizeEachNode == 0 ) { try { progress . setStep ( ( int ) ( ( ( double ) fc . position ( ) / fileSize ) * 100 ) ) ; } catch ( IOException ex ) { } } } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'" ) ; } } } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'features', found '" + jp . getText ( ) + "'" ) ; } }
Parses the featureCollection to collect the field properties
6,044
private void parseFeatureMetadata ( JsonParser jp ) throws IOException , SQLException { jp . nextToken ( ) ; String field = jp . getText ( ) ; while ( ! field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) && ! field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) && ! jp . getCurrentToken ( ) . equals ( JsonToken . END_OBJECT ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; field = jp . getText ( ) ; } if ( field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) ) { parseParentGeometryMetadata ( jp ) ; hasGeometryField = true ; jp . nextToken ( ) ; } else if ( field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) ) { parsePropertiesMetadata ( jp ) ; jp . nextToken ( ) ; } field = jp . getText ( ) ; while ( ! field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) && ! field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) && ! jp . getCurrentToken ( ) . equals ( JsonToken . END_OBJECT ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; field = jp . getText ( ) ; } if ( jp . getCurrentToken ( ) != JsonToken . END_OBJECT ) { String secondParam = jp . getText ( ) ; if ( secondParam . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) ) { parseParentGeometryMetadata ( jp ) ; hasGeometryField = true ; } else if ( secondParam . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) ) { parsePropertiesMetadata ( jp ) ; } while ( jp . nextToken ( ) != JsonToken . END_OBJECT ) ; } }
Features in GeoJSON contain a geometry object and additional properties This method is used to collect metadata
6,045
private void parseParentGeometryMetadata ( JsonParser jp ) throws IOException , SQLException { if ( jp . nextToken ( ) != JsonToken . VALUE_NULL ) { jp . nextToken ( ) ; jp . nextToken ( ) ; String geometryType = jp . getText ( ) ; parseGeometryMetadata ( jp , geometryType ) ; } }
Parses the geometries to return its properties
6,046
private void parseGeometryMetadata ( JsonParser jp , String geometryType ) throws IOException , SQLException { if ( geometryType . equalsIgnoreCase ( GeoJsonField . POINT ) ) { parsePointMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . POINT ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . MULTIPOINT ) ) { parseMultiPointMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . MULTIPOINT ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . LINESTRING ) ) { parseLinestringMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . LINESTRING ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . MULTILINESTRING ) ) { parseMultiLinestringMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . MULTILINESTRING ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . POLYGON ) ) { parsePolygonMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . POLYGON ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . MULTIPOLYGON ) ) { parseMultiPolygonMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . MULTIPOLYGON ) ; } else if ( geometryType . equalsIgnoreCase ( GeoJsonField . GEOMETRYCOLLECTION ) ) { parseGeometryCollectionMetadata ( jp ) ; finalGeometryTypes . add ( GeoJsonField . GEOMETRYCOLLECTION ) ; } else { throw new SQLException ( "Unsupported geometry : " + geometryType ) ; } }
Parses a all type of geometries and check if the geojson is wellformed .
6,047
private void parsePointMetadata ( JsonParser jp ) throws IOException , SQLException { jp . nextToken ( ) ; String coordinatesField = jp . getText ( ) ; if ( coordinatesField . equalsIgnoreCase ( GeoJsonField . COORDINATES ) ) { jp . nextToken ( ) ; parseCoordinateMetadata ( jp ) ; } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'" ) ; } }
Parses a point and check if it s wellformated
6,048
private void parseCoordinateMetadata ( JsonParser jp ) throws IOException { jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) != JsonToken . END_ARRAY ) { jp . nextToken ( ) ; } jp . nextToken ( ) ; }
Parses a GeoJSON coordinate array and check if it s wellformed . The first token corresponds to the first X value . The last token correponds to the end of the coordinate array ] .
6,049
private void init ( ) { jsFactory = new JsonFactory ( ) ; jsFactory . configure ( JsonParser . Feature . ALLOW_COMMENTS , true ) ; jsFactory . configure ( JsonParser . Feature . ALLOW_SINGLE_QUOTES , true ) ; jsFactory . configure ( JsonParser . Feature . ALLOW_NON_NUMERIC_NUMBERS , true ) ; }
Creates the JsonFactory .
6,050
private Object [ ] parseFeature ( JsonParser jp ) throws IOException , SQLException { jp . nextToken ( ) ; String field = jp . getText ( ) ; while ( ! field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) && ! field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) && ! jp . getCurrentToken ( ) . equals ( JsonToken . END_OBJECT ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; field = jp . getText ( ) ; } Object [ ] values = new Object [ cachedColumnIndex . size ( ) + 1 ] ; if ( field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) ) { setGeometry ( jp , values ) ; jp . nextToken ( ) ; } else if ( field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) ) { parseProperties ( jp , values ) ; jp . nextToken ( ) ; } field = jp . getText ( ) ; while ( ! field . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) && ! field . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) && ! jp . getCurrentToken ( ) . equals ( JsonToken . END_OBJECT ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; field = jp . getText ( ) ; } if ( jp . getCurrentToken ( ) != JsonToken . END_OBJECT ) { String secondParam = jp . getText ( ) ; if ( secondParam . equalsIgnoreCase ( GeoJsonField . GEOMETRY ) ) { setGeometry ( jp , values ) ; } else if ( secondParam . equalsIgnoreCase ( GeoJsonField . PROPERTIES ) ) { parseProperties ( jp , values ) ; } while ( jp . nextToken ( ) != JsonToken . END_OBJECT ) ; } return values ; }
Features in GeoJSON contain a geometry object and additional properties This method returns all values stored in a feature .
6,051
private void parseFeatures ( JsonParser jp ) throws IOException , SQLException { jp . nextToken ( ) ; while ( ! jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . FEATURES ) && ! jp . getText ( ) . equalsIgnoreCase ( GeoJsonField . CRS ) ) { jp . nextToken ( ) ; if ( jp . getCurrentToken ( ) . equals ( JsonToken . START_ARRAY ) || jp . getCurrentToken ( ) . equals ( JsonToken . START_OBJECT ) ) { jp . skipChildren ( ) ; } jp . nextToken ( ) ; } String firstParam = jp . getText ( ) ; if ( firstParam . equalsIgnoreCase ( GeoJsonField . CRS ) ) { firstParam = skipCRS ( jp ) ; } if ( firstParam . equalsIgnoreCase ( GeoJsonField . FEATURES ) ) { jp . nextToken ( ) ; JsonToken token = jp . nextToken ( ) ; long batchSize = 0 ; while ( token != JsonToken . END_ARRAY ) { jp . nextToken ( ) ; jp . nextToken ( ) ; String geomType = jp . getText ( ) ; if ( geomType . equalsIgnoreCase ( GeoJsonField . FEATURE ) ) { if ( progress . isCanceled ( ) ) { throw new SQLException ( "Canceled by user" ) ; } Object [ ] values = parseFeature ( jp ) ; for ( int i = 0 ; i < values . length ; i ++ ) { preparedStatement . setObject ( i + 1 , values [ i ] ) ; } preparedStatement . addBatch ( ) ; batchSize ++ ; if ( batchSize >= BATCH_MAX_SIZE ) { preparedStatement . executeBatch ( ) ; preparedStatement . clearBatch ( ) ; batchSize = 0 ; } token = jp . nextToken ( ) ; featureCounter ++ ; if ( nodeCountProgress ++ % readFileSizeEachNode == 0 ) { try { progress . setStep ( ( int ) ( ( ( double ) fc . position ( ) / fileSize ) * 100 ) ) ; } catch ( IOException ex ) { } } if ( batchSize > 0 ) { preparedStatement . executeBatch ( ) ; } } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'" ) ; } } log . info ( featureCounter + " geojson features have been imported." ) ; } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'features', found '" + firstParam + "'" ) ; } }
Parses the featureCollection
6,052
private void parseData ( ) throws IOException , SQLException { FileInputStream fis = null ; try { fis = new FileInputStream ( fileName ) ; try ( JsonParser jp = jsFactory . createParser ( fis ) ) { jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; String geomType = jp . getText ( ) ; if ( geomType . equalsIgnoreCase ( GeoJsonField . FEATURECOLLECTION ) ) { parseFeatures ( jp ) ; } else { throw new SQLException ( "Malformed GeoJSON file. Expected 'FeatureCollection', found '" + geomType + "'" ) ; } } } catch ( FileNotFoundException ex ) { throw new SQLException ( ex ) ; } finally { try { if ( fis != null ) { fis . close ( ) ; } } catch ( IOException ex ) { throw new SQLException ( ex ) ; } } }
Parses the GeoJSON data and set the values to the table .
6,053
private int readCRS ( JsonParser jp ) throws IOException , SQLException { int srid = 0 ; jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; String firstField = jp . getText ( ) ; if ( firstField . equalsIgnoreCase ( GeoJsonField . NAME ) ) { jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; String crsURI = jp . getText ( ) ; String [ ] split = crsURI . toLowerCase ( ) . split ( GeoJsonField . CRS_URN_EPSG ) ; if ( split != null ) { srid = Integer . valueOf ( split [ 1 ] ) ; } else { log . warn ( "The CRS URN " + crsURI + " is not supported." ) ; } jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; } else if ( firstField . equalsIgnoreCase ( GeoJsonField . LINK ) ) { log . warn ( "Linked CRS is not supported." ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; jp . nextToken ( ) ; } else { throw new SQLException ( "Malformed GeoJSON CRS element." ) ; } return srid ; }
Reads the CRS element and return the database SRID .
6,054
private String skipCRS ( JsonParser jp ) throws IOException { jp . nextToken ( ) ; jp . skipChildren ( ) ; jp . nextToken ( ) ; return jp . getText ( ) ; }
We skip the CRS because it has been already parsed .
6,055
private void setGeometryTypeConstraints ( ) throws SQLException { String finalGeometryType = GeoJsonField . GEOMETRY ; if ( finalGeometryTypes . size ( ) == 1 ) { finalGeometryType = ( String ) finalGeometryTypes . iterator ( ) . next ( ) ; } if ( isH2 ) { finalGeometryType = GeoJsonField . GEOMETRY ; connection . createStatement ( ) . execute ( String . format ( "ALTER TABLE %s ALTER COLUMN the_geom %s" , tableLocation . toString ( ) , finalGeometryType ) ) ; } else { connection . createStatement ( ) . execute ( String . format ( "ALTER TABLE %s ALTER COLUMN the_geom SET DATA TYPE geometry(%s,%d)" , tableLocation . toString ( ) , finalGeometryType , parsedSRID ) ) ; } }
Adds the geometry type constraint and the SRID
6,056
public static Geometry split ( Geometry geomA , Geometry geomB , double tolerance ) throws SQLException { if ( geomA instanceof Polygon ) { throw new SQLException ( "Split a Polygon by a line is not supported using a tolerance. \n" + "Please used ST_Split(geom1, geom2)" ) ; } else if ( geomA instanceof LineString ) { if ( geomB instanceof LineString ) { throw new SQLException ( "Split a line by a line is not supported using a tolerance. \n" + "Please used ST_Split(geom1, geom2)" ) ; } else if ( geomB instanceof Point ) { return splitLineWithPoint ( ( LineString ) geomA , ( Point ) geomB , tolerance ) ; } } else if ( geomA instanceof MultiLineString ) { if ( geomB instanceof LineString ) { throw new SQLException ( "Split a multiline by a line is not supported using a tolerance. \n" + "Please used ST_Split(geom1, geom2)" ) ; } else if ( geomB instanceof Point ) { return splitMultiLineStringWithPoint ( ( MultiLineString ) geomA , ( Point ) geomB , tolerance ) ; } } throw new SQLException ( "Split a " + geomA . getGeometryType ( ) + " by a " + geomB . getGeometryType ( ) + " is not supported." ) ; }
Split a geometry a according a geometry b using a snapping tolerance .
6,057
private static MultiLineString splitLineWithPoint ( LineString line , Point pointToSplit , double tolerance ) { return FACTORY . createMultiLineString ( splitLineStringWithPoint ( line , pointToSplit , tolerance ) ) ; }
Split a linestring with a point The point must be on the linestring
6,058
private static LineString [ ] splitLineStringWithPoint ( LineString line , Point pointToSplit , double tolerance ) { Coordinate [ ] coords = line . getCoordinates ( ) ; Coordinate firstCoord = coords [ 0 ] ; Coordinate lastCoord = coords [ coords . length - 1 ] ; Coordinate coordToSplit = pointToSplit . getCoordinate ( ) ; if ( ( coordToSplit . distance ( firstCoord ) <= PRECISION ) || ( coordToSplit . distance ( lastCoord ) <= PRECISION ) ) { return new LineString [ ] { line } ; } else { ArrayList < Coordinate > firstLine = new ArrayList < Coordinate > ( ) ; firstLine . add ( coords [ 0 ] ) ; ArrayList < Coordinate > secondLine = new ArrayList < Coordinate > ( ) ; GeometryLocation geometryLocation = EditUtilities . getVertexToSnap ( line , pointToSplit , tolerance ) ; if ( geometryLocation != null ) { int segmentIndex = geometryLocation . getSegmentIndex ( ) ; Coordinate coord = geometryLocation . getCoordinate ( ) ; int index = - 1 ; for ( int i = 1 ; i < coords . length ; i ++ ) { index = i - 1 ; if ( index < segmentIndex ) { firstLine . add ( coords [ i ] ) ; } else if ( index == segmentIndex ) { coord . z = CoordinateUtils . interpolate ( coords [ i - 1 ] , coords [ i ] , coord ) ; firstLine . add ( coord ) ; secondLine . add ( coord ) ; if ( ! coord . equals2D ( coords [ i ] ) ) { secondLine . add ( coords [ i ] ) ; } } else { secondLine . add ( coords [ i ] ) ; } } LineString lineString1 = FACTORY . createLineString ( firstLine . toArray ( new Coordinate [ 0 ] ) ) ; LineString lineString2 = FACTORY . createLineString ( secondLine . toArray ( new Coordinate [ 0 ] ) ) ; return new LineString [ ] { lineString1 , lineString2 } ; } } return null ; }
Splits a LineString using a Point with a distance tolerance .
6,059
private static MultiLineString splitMultiLineStringWithPoint ( MultiLineString multiLineString , Point pointToSplit , double tolerance ) { ArrayList < LineString > linestrings = new ArrayList < LineString > ( ) ; boolean notChanged = true ; int nb = multiLineString . getNumGeometries ( ) ; for ( int i = 0 ; i < nb ; i ++ ) { LineString subGeom = ( LineString ) multiLineString . getGeometryN ( i ) ; LineString [ ] result = splitLineStringWithPoint ( subGeom , pointToSplit , tolerance ) ; if ( result != null ) { Collections . addAll ( linestrings , result ) ; notChanged = false ; } else { linestrings . add ( subGeom ) ; } } if ( ! notChanged ) { return FACTORY . createMultiLineString ( linestrings . toArray ( new LineString [ 0 ] ) ) ; } return null ; }
Splits a MultilineString using a point .
6,060
private static Collection < Polygon > splitPolygonizer ( Polygon polygon , LineString lineString ) throws SQLException { LinkedList < LineString > result = new LinkedList < LineString > ( ) ; ST_ToMultiSegments . createSegments ( polygon . getExteriorRing ( ) , result ) ; result . add ( lineString ) ; int holes = polygon . getNumInteriorRing ( ) ; for ( int i = 0 ; i < holes ; i ++ ) { ST_ToMultiSegments . createSegments ( polygon . getInteriorRingN ( i ) , result ) ; } UnaryUnionOp uOp = new UnaryUnionOp ( result ) ; Geometry union = uOp . union ( ) ; Polygonizer polygonizer = new Polygonizer ( ) ; polygonizer . add ( union ) ; Collection < Polygon > polygons = polygonizer . getPolygons ( ) ; if ( polygons . size ( ) > 1 ) { return polygons ; } return null ; }
Splits a Polygon with a LineString .
6,061
private static Geometry splitMultiPolygonWithLine ( MultiPolygon multiPolygon , LineString lineString ) throws SQLException { ArrayList < Polygon > allPolygons = new ArrayList < Polygon > ( ) ; for ( int i = 0 ; i < multiPolygon . getNumGeometries ( ) ; i ++ ) { Collection < Polygon > polygons = splitPolygonizer ( ( Polygon ) multiPolygon . getGeometryN ( i ) , lineString ) ; if ( polygons != null ) { allPolygons . addAll ( polygons ) ; } } if ( ! allPolygons . isEmpty ( ) ) { return FACTORY . buildGeometry ( allPolygons ) ; } return null ; }
Splits a MultiPolygon using a LineString .
6,062
private static Geometry splitMultiLineStringWithLine ( MultiLineString input , LineString cut ) { Geometry lines = input . difference ( cut ) ; if ( lines instanceof LineString ) { return FACTORY . createMultiLineString ( new LineString [ ] { ( LineString ) lines . getGeometryN ( 0 ) } ) ; } return lines ; }
Splits the specified MultiLineString with another lineString .
6,063
public static Integer getHoles ( Geometry g ) { if ( g == null ) { return null ; } if ( g instanceof MultiPolygon ) { Polygon p = ( Polygon ) g . getGeometryN ( 0 ) ; if ( p != null ) { return p . getNumInteriorRing ( ) ; } } else if ( g instanceof Polygon ) { return ( ( Polygon ) g ) . getNumInteriorRing ( ) ; } return null ; }
Return the number of holes in a Polygon or MultiPolygon
6,064
private void checkOSMTables ( Connection connection , boolean isH2 , TableLocation requestedTable , String osmTableName ) throws SQLException { String [ ] omsTables = new String [ ] { OSMTablesFactory . TAG , OSMTablesFactory . NODE , OSMTablesFactory . NODE_TAG , OSMTablesFactory . WAY , OSMTablesFactory . WAY_NODE , OSMTablesFactory . WAY_TAG , OSMTablesFactory . RELATION , OSMTablesFactory . RELATION_TAG , OSMTablesFactory . NODE_MEMBER , OSMTablesFactory . WAY_MEMBER , OSMTablesFactory . RELATION_MEMBER } ; for ( String omsTableSuffix : omsTables ) { String osmTable = TableUtilities . caseIdentifier ( requestedTable , osmTableName + omsTableSuffix , isH2 ) ; if ( JDBCUtilities . tableExists ( connection , osmTable ) ) { throw new SQLException ( "The table " + osmTable + " already exists." ) ; } } }
Check if one table already exists
6,065
private void createOSMDatabaseModel ( Connection connection , boolean isH2 , TableLocation requestedTable , String osmTableName ) throws SQLException { String tagTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . TAG , isH2 ) ; tagPreparedStmt = OSMTablesFactory . createTagTable ( connection , tagTableName ) ; String nodeTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . NODE , isH2 ) ; nodePreparedStmt = OSMTablesFactory . createNodeTable ( connection , nodeTableName , isH2 ) ; String nodeTagTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . NODE_TAG , isH2 ) ; nodeTagPreparedStmt = OSMTablesFactory . createNodeTagTable ( connection , nodeTagTableName , tagTableName ) ; String wayTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . WAY , isH2 ) ; wayPreparedStmt = OSMTablesFactory . createWayTable ( connection , wayTableName , isH2 ) ; String wayTagTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . WAY_TAG , isH2 ) ; wayTagPreparedStmt = OSMTablesFactory . createWayTagTable ( connection , wayTagTableName , tagTableName ) ; String wayNodeTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . WAY_NODE , isH2 ) ; wayNodePreparedStmt = OSMTablesFactory . createWayNodeTable ( connection , wayNodeTableName ) ; String relationTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . RELATION , isH2 ) ; relationPreparedStmt = OSMTablesFactory . createRelationTable ( connection , relationTableName ) ; String relationTagTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . RELATION_TAG , isH2 ) ; relationTagPreparedStmt = OSMTablesFactory . createRelationTagTable ( connection , relationTagTableName , tagTableName ) ; String nodeMemberTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . NODE_MEMBER , isH2 ) ; nodeMemberPreparedStmt = OSMTablesFactory . createNodeMemberTable ( connection , nodeMemberTableName ) ; String wayMemberTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . WAY_MEMBER , isH2 ) ; wayMemberPreparedStmt = OSMTablesFactory . createWayMemberTable ( connection , wayMemberTableName ) ; String relationMemberTableName = TableUtilities . caseIdentifier ( requestedTable , osmTableName + OSMTablesFactory . RELATION_MEMBER , isH2 ) ; relationMemberPreparedStmt = OSMTablesFactory . createRelationMemberTable ( connection , relationMemberTableName ) ; }
Create the OMS data model to store the content of the file
6,066
private static List < SegmentString > fixSegments ( List < SegmentString > segments ) { MCIndexNoder mCIndexNoder = new MCIndexNoder ( ) ; RobustLineIntersector robustLineIntersector = new RobustLineIntersector ( ) ; mCIndexNoder . setSegmentIntersector ( new IntersectionAdder ( robustLineIntersector ) ) ; mCIndexNoder . computeNodes ( segments ) ; Collection nodedSubstring = mCIndexNoder . getNodedSubstrings ( ) ; ArrayList < SegmentString > ret = new ArrayList < > ( nodedSubstring . size ( ) ) ; for ( Object aNodedSubstring : nodedSubstring ) { ret . add ( ( SegmentString ) aNodedSubstring ) ; } return ret ; }
Split originalSegments that intersects . Run this method after calling the last addSegment before calling getIsoVist
6,067
public void addSegment ( Coordinate p0 , Coordinate p1 ) { if ( p0 . distance ( p1 ) < epsilon ) { return ; } addSegment ( originalSegments , p0 , p1 ) ; }
Add occlusion segment in isovist
6,068
public void addGeometry ( Geometry geometry ) { if ( geometry instanceof LineString ) { addLineString ( originalSegments , ( LineString ) geometry ) ; } else if ( geometry instanceof Polygon ) { addPolygon ( originalSegments , ( Polygon ) geometry ) ; } else if ( geometry instanceof GeometryCollection ) { addGeometry ( originalSegments , ( GeometryCollection ) geometry ) ; } }
Explode geometry and add occlusion segments in isovist
6,069
public static String geth2gisVersion ( ) { try ( InputStream fs = H2GISFunctions . class . getResourceAsStream ( "/org/h2gis/functions/system/version.txt" ) ) { BufferedReader bufRead = new BufferedReader ( new InputStreamReader ( fs ) ) ; StringBuilder builder = new StringBuilder ( ) ; String line = null ; while ( ( line = bufRead . readLine ( ) ) != null ) { builder . append ( line ) . append ( " " ) ; } return builder . toString ( ) ; } catch ( IOException ex ) { return "unknown" ; } }
Return the H2GIS version available in the version txt file Otherwise return unknown
6,070
private static void firstFirstLastLast ( Statement st , TableLocation tableName , String pkCol , String geomCol , double tolerance ) throws SQLException { LOGGER . info ( "Selecting the first coordinate of the first geometry and " + "the last coordinate of the last geometry..." ) ; final String numGeoms = "ST_NumGeometries(" + geomCol + ")" ; final String firstGeom = "ST_GeometryN(" + geomCol + ", 1)" ; final String firstPointFirstGeom = "ST_PointN(" + firstGeom + ", 1)" ; final String lastGeom = "ST_GeometryN(" + geomCol + ", " + numGeoms + ")" ; final String lastPointLastGeom = "ST_PointN(" + lastGeom + ", ST_NumPoints(" + lastGeom + "))" ; st . execute ( "drop TABLE if exists " + COORDS_TABLE ) ; if ( tolerance > 0 ) { st . execute ( "CREATE TABLE " + COORDS_TABLE + " AS " + "SELECT " + pkCol + " EDGE_ID, " + firstPointFirstGeom + " START_POINT, " + expand ( firstPointFirstGeom , tolerance ) + " START_POINT_EXP, " + lastPointLastGeom + " END_POINT, " + expand ( lastPointLastGeom , tolerance ) + " END_POINT_EXP " + "FROM " + tableName ) ; } else { st . execute ( "CREATE TABLE " + COORDS_TABLE + " AS " + "SELECT " + pkCol + " EDGE_ID, " + firstPointFirstGeom + " START_POINT, " + lastPointLastGeom + " END_POINT " + "FROM " + tableName ) ; } }
Return the first and last coordinates table
6,071
private static void makeEnvelopes ( Statement st , double tolerance , boolean isH2 , int srid ) throws SQLException { st . execute ( "DROP TABLE IF EXISTS" + PTS_TABLE + ";" ) ; if ( tolerance > 0 ) { LOGGER . info ( "Calculating envelopes around coordinates..." ) ; if ( isH2 ) { st . execute ( "CREATE TABLE " + PTS_TABLE + "( " + "ID SERIAL PRIMARY KEY, " + "THE_GEOM POINT, " + "AREA POLYGON " + ") AS " + "SELECT NULL, START_POINT, START_POINT_EXP FROM " + COORDS_TABLE + " UNION ALL " + "SELECT NULL, END_POINT, END_POINT_EXP FROM " + COORDS_TABLE + ";" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + PTS_TABLE + "(AREA);" ) ; } else { st . execute ( "CREATE TABLE " + PTS_TABLE + "( ID SERIAL PRIMARY KEY, " + "THE_GEOM GEOMETRY(POINT," + srid + ")," + "AREA GEOMETRY(POLYGON, " + srid + ")" + ") " ) ; st . execute ( "INSERT INTO " + PTS_TABLE + " (SELECT (row_number() over())::int , a.THE_GEOM, A.AREA FROM " + "(SELECT START_POINT AS THE_GEOM, START_POINT_EXP as AREA FROM " + COORDS_TABLE + " UNION ALL " + "SELECT END_POINT AS THE_GEOM, END_POINT_EXP as AREA FROM " + COORDS_TABLE + ") as a);" ) ; st . execute ( "CREATE INDEX ON " + PTS_TABLE + " USING GIST(AREA);" ) ; } } else { LOGGER . info ( "Preparing temporary nodes table from coordinates..." ) ; if ( isH2 ) { st . execute ( "CREATE TABLE " + PTS_TABLE + "( " + "ID SERIAL PRIMARY KEY, " + "THE_GEOM POINT" + ") AS " + "SELECT NULL, START_POINT FROM " + COORDS_TABLE + " UNION ALL " + "SELECT NULL, END_POINT FROM " + COORDS_TABLE + ";" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + PTS_TABLE + "(THE_GEOM);" ) ; } else { st . execute ( "CREATE TABLE " + PTS_TABLE + "( " + "ID SERIAL PRIMARY KEY, " + "THE_GEOM GEOMETRY(POINT," + srid + ")" + ")" ) ; st . execute ( "INSERT INTO " + PTS_TABLE + " (SELECT (row_number() over())::int , a.the_geom FROM " + "(SELECT START_POINT as THE_GEOM FROM " + COORDS_TABLE + " UNION ALL " + "SELECT END_POINT as THE_GEOM FROM " + COORDS_TABLE + ") as a);" ) ; st . execute ( "CREATE INDEX ON " + PTS_TABLE + " USING GIST(THE_GEOM);" ) ; } } }
Make a big table of all points in the coords table with an envelope around each point . We will use this table to remove duplicate points .
6,072
private static void nodesTable ( Statement st , TableLocation nodesName , double tolerance , boolean isH2 , int srid ) throws SQLException { LOGGER . info ( "Creating the nodes table..." ) ; if ( tolerance > 0 ) { if ( isH2 ) { st . execute ( "CREATE TABLE " + nodesName + "(" + "NODE_ID SERIAL PRIMARY KEY, " + "THE_GEOM POINT, " + "EXP POLYGON" + ") AS " + "SELECT NULL, A.THE_GEOM, A.AREA FROM " + PTS_TABLE + " as A," + PTS_TABLE + " as B " + "WHERE A.AREA && B.AREA " + "GROUP BY A.ID " + "HAVING A.ID=MIN(B.ID);" ) ; } else { st . execute ( "CREATE TABLE " + nodesName + "(" + "NODE_ID SERIAL PRIMARY KEY, " + "THE_GEOM GEOMETRY(POINT, " + srid + "), " + "EXP GEOMETRY(POLYGON," + srid + ")" + ") " ) ; st . execute ( "INSERT INTO " + nodesName + " (SELECT (row_number() over())::int , c.the_geom, c.area FROM (SELECT A.THE_GEOM, A.AREA FROM " + PTS_TABLE + " as A, " + PTS_TABLE + " as B " + "WHERE A.AREA && B.AREA " + "GROUP BY A.ID " + "HAVING A.ID=MIN(B.ID)) as c);" ) ; } } else { if ( isH2 ) { st . execute ( "CREATE TABLE " + nodesName + "(" + "NODE_ID SERIAL PRIMARY KEY, " + "THE_GEOM POINT" + ") AS " + "SELECT NULL, A.THE_GEOM FROM " + PTS_TABLE + " as A," + PTS_TABLE + " as B " + "WHERE A.THE_GEOM && B.THE_GEOM AND A.THE_GEOM=B.THE_GEOM " + "GROUP BY A.ID " + "HAVING A.ID=MIN(B.ID);" ) ; } else { st . execute ( "CREATE TABLE " + nodesName + "(" + "NODE_ID SERIAL PRIMARY KEY, " + "THE_GEOM GEOMETRY(POINT, " + srid + ")" + ") " ) ; st . execute ( "INSERT INTO " + nodesName + " (SELECT (row_number() over())::int , c.the_geom FROM (SELECT A.THE_GEOM FROM " + PTS_TABLE + " as A," + PTS_TABLE + " as B " + "WHERE A.THE_GEOM && B.THE_GEOM AND A.THE_GEOM=B.THE_GEOM " + "GROUP BY A.ID " + "HAVING A.ID=MIN(B.ID)) as c);" ) ; } } }
Create the nodes table .
6,073
private static void edgesTable ( Statement st , TableLocation nodesName , TableLocation edgesName , double tolerance , boolean isH2 ) throws SQLException { LOGGER . info ( "Creating the edges table..." ) ; if ( tolerance > 0 ) { if ( isH2 ) { st . execute ( "CREATE SPATIAL INDEX ON " + nodesName + "(EXP);" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + COORDS_TABLE + "(START_POINT_EXP);" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + COORDS_TABLE + "(END_POINT_EXP);" ) ; } else { st . execute ( "CREATE INDEX ON " + nodesName + " USING GIST(EXP);" ) ; st . execute ( "CREATE INDEX ON " + COORDS_TABLE + " USING GIST(START_POINT_EXP);" ) ; st . execute ( "CREATE INDEX ON " + COORDS_TABLE + " USING GIST(END_POINT_EXP);" ) ; } st . execute ( "CREATE TABLE " + edgesName + " AS " + "SELECT EDGE_ID, " + "(SELECT NODE_ID FROM " + nodesName + " WHERE " + nodesName + ".EXP && " + COORDS_TABLE + ".START_POINT_EXP LIMIT 1) START_NODE, " + "(SELECT NODE_ID FROM " + nodesName + " WHERE " + nodesName + ".EXP && " + COORDS_TABLE + ".END_POINT_EXP LIMIT 1) END_NODE " + "FROM " + COORDS_TABLE + ";" ) ; st . execute ( "ALTER TABLE " + nodesName + " DROP COLUMN EXP;" ) ; } else { if ( isH2 ) { st . execute ( "CREATE SPATIAL INDEX ON " + nodesName + "(THE_GEOM);" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + COORDS_TABLE + "(START_POINT);" ) ; st . execute ( "CREATE SPATIAL INDEX ON " + COORDS_TABLE + "(END_POINT);" ) ; } else { st . execute ( "CREATE INDEX ON " + nodesName + " USING GIST(THE_GEOM);" ) ; st . execute ( "CREATE INDEX ON " + COORDS_TABLE + " USING GIST(START_POINT);" ) ; st . execute ( "CREATE INDEX ON " + COORDS_TABLE + " USING GIST(END_POINT);" ) ; } st . execute ( "CREATE TABLE " + edgesName + " AS " + "SELECT EDGE_ID, " + "(SELECT NODE_ID FROM " + nodesName + " WHERE " + nodesName + ".THE_GEOM && " + COORDS_TABLE + ".START_POINT " + "AND " + nodesName + ".THE_GEOM=" + COORDS_TABLE + ".START_POINT LIMIT 1) START_NODE, " + "(SELECT NODE_ID FROM " + nodesName + " WHERE " + nodesName + ".THE_GEOM && " + COORDS_TABLE + ".END_POINT " + "AND " + nodesName + ".THE_GEOM=" + COORDS_TABLE + ".END_POINT LIMIT 1) END_NODE " + "FROM " + COORDS_TABLE + ";" ) ; } }
Create the edges table .
6,074
public static double [ ] zMinMax ( final Coordinate [ ] cs ) { double zmin ; double zmax ; boolean validZFound = false ; double [ ] result = new double [ 2 ] ; zmin = Double . NaN ; zmax = Double . NaN ; double z ; for ( int t = cs . length - 1 ; t >= 0 ; t -- ) { z = cs [ t ] . z ; if ( ! ( Double . isNaN ( z ) ) ) { if ( validZFound ) { if ( z < zmin ) { zmin = z ; } if ( z > zmax ) { zmax = z ; } } else { validZFound = true ; zmin = z ; zmax = z ; } } } result [ 0 ] = ( zmin ) ; result [ 1 ] = ( zmax ) ; return result ; }
Determine the min and max z values in an array of Coordinates .
6,075
public static boolean contains2D ( Coordinate [ ] coords , Coordinate coord ) { for ( Coordinate coordinate : coords ) { if ( coordinate . equals2D ( coord ) ) { return true ; } } return false ; }
Checks if a coordinate array contains a specific coordinate .
6,076
public static Coordinate vectorIntersection ( Coordinate p1 , Vector3D v1 , Coordinate p2 , Vector3D v2 ) { double delta ; Coordinate i = null ; delta = v1 . getX ( ) * ( - v2 . getY ( ) ) - ( - v1 . getY ( ) ) * v2 . getX ( ) ; if ( delta != 0 ) { double k = ( ( p2 . x - p1 . x ) * ( - v2 . getY ( ) ) - ( p2 . y - p1 . y ) * ( - v2 . getX ( ) ) ) / delta ; i = new Coordinate ( p1 . x + k * v1 . getX ( ) , p1 . y + k * v1 . getY ( ) , p1 . z + k * v1 . getZ ( ) ) ; if ( new LineSegment ( p1 , new Coordinate ( p1 . x + v1 . getX ( ) , p1 . y + v1 . getY ( ) ) ) . projectionFactor ( i ) < 0 || new LineSegment ( p2 , new Coordinate ( p2 . x + v2 . getX ( ) , p2 . y + v2 . getY ( ) ) ) . projectionFactor ( i ) < 0 ) { return null ; } } return i ; }
Compute intersection point of two vectors
6,077
public static Coordinate [ ] removeRepeatedCoordinates ( Coordinate [ ] coords , double tolerance , boolean duplicateFirstLast ) { ArrayList < Coordinate > finalCoords = new ArrayList < Coordinate > ( ) ; Coordinate prevCoord = coords [ 0 ] ; finalCoords . add ( prevCoord ) ; Coordinate firstCoord = prevCoord ; int nbCoords = coords . length ; for ( int i = 1 ; i < nbCoords ; i ++ ) { Coordinate currentCoord = coords [ i ] ; if ( currentCoord . distance ( prevCoord ) <= tolerance ) { continue ; } finalCoords . add ( currentCoord ) ; prevCoord = currentCoord ; } if ( ! duplicateFirstLast ) { if ( firstCoord . distance ( prevCoord ) <= tolerance ) { finalCoords . remove ( finalCoords . size ( ) - 1 ) ; } } else { finalCoords . add ( firstCoord ) ; } return finalCoords . toArray ( new Coordinate [ 0 ] ) ; }
Remove repeated coordinates according a given tolerance
6,078
public void exportTable ( Connection connection , String tableReference , File fileName , ProgressVisitor progress , String encoding ) 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 ( ")" ) ) { if ( FileUtil . isExtensionWellFormated ( fileName , "tsv" ) ) { try ( Statement st = connection . createStatement ( ) ) { JDBCUtilities . attachCancelResultSet ( st , progress ) ; exportFromResultSet ( connection , st . executeQuery ( tableReference ) , fileName , new EmptyProgressVisitor ( ) , encoding ) ; } } else { throw new SQLException ( "Only .tsv extension is supported" ) ; } } else { throw new SQLException ( "The select query must be enclosed in parenthesis: '(SELECT * FROM ORDERS)'." ) ; } } else { if ( FileUtil . isExtensionWellFormated ( fileName , "tsv" ) ) { final boolean isH2 = JDBCUtilities . isH2DataBase ( connection . getMetaData ( ) ) ; TableLocation location = TableLocation . parse ( tableReference , isH2 ) ; try ( Statement st = connection . createStatement ( ) ) { JDBCUtilities . attachCancelResultSet ( st , progress ) ; exportFromResultSet ( connection , st . executeQuery ( "SELECT * FROM " + location . toString ( ) ) , fileName , new EmptyProgressVisitor ( ) , encoding ) ; } } else { throw new SQLException ( "Only .tsv extension is supported" ) ; } } }
Export a table or a query to as TSV file
6,079
public void exportFromResultSet ( Connection connection , ResultSet res , File fileName , ProgressVisitor progress , String encoding ) throws SQLException { Csv csv = new Csv ( ) ; String csvOptions = "charset=UTF-8 fieldSeparator=\t fieldDelimiter=\t" ; if ( encoding != null ) { csvOptions = String . format ( "charset=%s fieldSeparator=\t fieldDelimiter=\t" , encoding ) ; } csv . setOptions ( csvOptions ) ; csv . write ( fileName . getPath ( ) , res , null ) ; }
Export a resultset to a TSV file
6,080
public static String generateLink ( Geometry geom , boolean withMarker ) { if ( geom == null ) { return null ; } Envelope env = geom . getEnvelopeInternal ( ) ; StringBuilder sb = new StringBuilder ( "http://www.openstreetmap.org/?" ) ; sb . append ( "minlon=" ) . append ( env . getMinX ( ) ) ; sb . append ( "&minlat=" ) . append ( env . getMinY ( ) ) ; sb . append ( "&maxlon=" ) . append ( env . getMaxX ( ) ) ; sb . append ( "&maxlat=" ) . append ( env . getMaxY ( ) ) ; if ( withMarker ) { Coordinate centre = env . centre ( ) ; sb . append ( "&mlat=" ) . append ( centre . y ) ; sb . append ( "&mlon=" ) . append ( centre . x ) ; } return sb . toString ( ) ; }
Create the OSM map link based on the bounding box of the geometry .
6,081
public static Polygon makePolygon ( Geometry shell ) throws IllegalArgumentException { if ( shell == null ) { return null ; } LinearRing outerLine = checkLineString ( shell ) ; return shell . getFactory ( ) . createPolygon ( outerLine , null ) ; }
Creates a Polygon formed by the given shell .
6,082
public static Polygon makePolygon ( Geometry shell , Geometry ... holes ) throws IllegalArgumentException { if ( shell == null ) { return null ; } LinearRing outerLine = checkLineString ( shell ) ; LinearRing [ ] interiorlinestrings = new LinearRing [ holes . length ] ; for ( int i = 0 ; i < holes . length ; i ++ ) { interiorlinestrings [ i ] = checkLineString ( holes [ i ] ) ; } return shell . getFactory ( ) . createPolygon ( outerLine , interiorlinestrings ) ; }
Creates a Polygon formed by the given shell and holes .
6,083
private static LinearRing checkLineString ( Geometry geometry ) throws IllegalArgumentException { if ( geometry instanceof LinearRing ) { return ( LinearRing ) geometry ; } else if ( geometry instanceof LineString ) { LineString lineString = ( LineString ) geometry ; if ( lineString . isClosed ( ) ) { return geometry . getFactory ( ) . createLinearRing ( lineString . getCoordinateSequence ( ) ) ; } else { throw new IllegalArgumentException ( "The linestring must be closed." ) ; } } else { throw new IllegalArgumentException ( "Only support linestring." ) ; } }
Check if a geometry is a linestring and if its closed .
6,084
public static Geometry ST_Transform ( Connection connection , Geometry geom , Integer codeEpsg ) throws SQLException , CoordinateOperationException { if ( geom == null ) { return null ; } if ( codeEpsg == null ) { throw new IllegalArgumentException ( "The SRID code cannot be null." ) ; } if ( crsf == null ) { crsf = new CRSFactory ( ) ; crsf . getRegistryManager ( ) . addRegistry ( srr ) ; } srr . setConnection ( connection ) ; try { int inputSRID = geom . getSRID ( ) ; if ( inputSRID == 0 ) { throw new SQLException ( "Cannot find a CRS" ) ; } else { CoordinateReferenceSystem inputCRS = crsf . getCRS ( srr . getRegistryName ( ) + ":" + String . valueOf ( inputSRID ) ) ; CoordinateReferenceSystem targetCRS = crsf . getCRS ( srr . getRegistryName ( ) + ":" + String . valueOf ( codeEpsg ) ) ; if ( inputCRS . equals ( targetCRS ) ) { return geom ; } EPSGTuple epsg = new EPSGTuple ( inputSRID , codeEpsg ) ; CoordinateOperation op = copPool . get ( epsg ) ; if ( op != null ) { Geometry outPutGeom = geom . copy ( ) ; outPutGeom . geometryChanged ( ) ; outPutGeom . apply ( new CRSTransformFilter ( op ) ) ; outPutGeom . setSRID ( codeEpsg ) ; return outPutGeom ; } else { if ( inputCRS instanceof GeodeticCRS && targetCRS instanceof GeodeticCRS ) { Set < CoordinateOperation > ops = CoordinateOperationFactory . createCoordinateOperations ( ( GeodeticCRS ) inputCRS , ( GeodeticCRS ) targetCRS ) ; if ( ! ops . isEmpty ( ) ) { op = CoordinateOperationFactory . getMostPrecise ( ops ) ; Geometry outPutGeom = ( Geometry ) geom . copy ( ) ; outPutGeom . geometryChanged ( ) ; outPutGeom . apply ( new CRSTransformFilter ( op ) ) ; copPool . put ( epsg , op ) ; outPutGeom . setSRID ( codeEpsg ) ; return outPutGeom ; } } else { throw new SQLException ( "The transformation from " + inputCRS + " to " + codeEpsg + " is not yet supported." ) ; } } } } catch ( CRSException ex ) { throw new SQLException ( "Cannot create the CRS" , ex ) ; } finally { srr . setConnection ( null ) ; } return null ; }
Returns a new geometry transformed to the SRID referenced by the integer parameter available in the spatial_ref_sys table
6,085
public static Geometry node ( Geometry geom ) { if ( geom == null ) { return null ; } Noder noder = new MCIndexNoder ( new IntersectionAdder ( new RobustLineIntersector ( ) ) ) ; noder . computeNodes ( SegmentStringUtil . extractNodedSegmentStrings ( geom ) ) ; return SegmentStringUtil . toGeometry ( noder . getNodedSubstrings ( ) , geom . getFactory ( ) ) ; }
Nodes a geometry using a monotone chain and a spatial index
6,086
public void initialise ( XMLReader reader , AbstractGpxParserDefault parent ) { setReader ( reader ) ; setParent ( parent ) ; setContentBuffer ( parent . getContentBuffer ( ) ) ; setWptPreparedStmt ( parent . getWptPreparedStmt ( ) ) ; setElementNames ( parent . getElementNames ( ) ) ; setCurrentPoint ( parent . getCurrentPoint ( ) ) ; }
Create a new specific parser . It has in memory the default parser the contentBuffer the elementNames and the currentPoint .
6,087
public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { getContentBuffer ( ) . delete ( 0 , getContentBuffer ( ) . length ( ) ) ; getElementNames ( ) . push ( qName ) ; }
Fires whenever an XML start markup is encountered .
6,088
public static Geometry removeRepeatedPoints ( Geometry geometry ) throws SQLException , SQLException , SQLException , SQLException { return removeDuplicateCoordinates ( geometry , 0 ) ; }
Returns a version of the given geometry with duplicated points removed .
6,089
public static Geometry removeDuplicateCoordinates ( Geometry geom , double tolerance ) throws SQLException { if ( geom == null ) { return null ; } else if ( geom . isEmpty ( ) ) { return geom ; } else if ( geom instanceof Point ) { return geom ; } else if ( geom instanceof MultiPoint ) { return geom ; } else if ( geom instanceof LineString ) { return removeDuplicateCoordinates ( ( LineString ) geom , tolerance ) ; } else if ( geom instanceof MultiLineString ) { return removeDuplicateCoordinates ( ( MultiLineString ) geom , tolerance ) ; } else if ( geom instanceof Polygon ) { return removeDuplicateCoordinates ( ( Polygon ) geom , tolerance ) ; } else if ( geom instanceof MultiPolygon ) { return removeDuplicateCoordinates ( ( MultiPolygon ) geom , tolerance ) ; } else if ( geom instanceof GeometryCollection ) { return removeDuplicateCoordinates ( ( GeometryCollection ) geom , tolerance ) ; } return null ; }
Removes duplicated points within a geometry .
6,090
public static Connection openSpatialDataBase ( String dbName ) throws SQLException , ClassNotFoundException { String dbFilePath = getDataBasePath ( dbName ) ; String databasePath = "jdbc:h2:" + dbFilePath + H2_PARAMETERS ; org . h2 . Driver . load ( ) ; return DriverManager . getConnection ( databasePath , "sa" , "sa" ) ; }
Open the connection to an existing database
6,091
private static String getDataBasePath ( String dbName ) { if ( dbName . startsWith ( "file://" ) ) { return new File ( URI . create ( dbName ) ) . getAbsolutePath ( ) ; } else { return new File ( "target/test-resources/dbH2" + dbName ) . getAbsolutePath ( ) ; } }
Return the path of the file database
6,092
public static Connection createSpatialDataBase ( String dbName , boolean initSpatial , String h2Parameters ) throws SQLException , ClassNotFoundException { String databasePath = initDBFile ( dbName , h2Parameters ) ; org . h2 . Driver . load ( ) ; Connection connection = DriverManager . getConnection ( databasePath , "sa" , "sa" ) ; if ( initSpatial ) { H2GISFunctions . load ( connection ) ; } return connection ; }
Create a spatial database
6,093
public static Connection createSpatialDataBase ( String dbName , boolean initSpatial ) throws SQLException , ClassNotFoundException { return createSpatialDataBase ( dbName , initSpatial , H2_PARAMETERS ) ; }
Create a spatial database and register all H2GIS functions
6,094
public static Point closestPoint ( Geometry geomA , Geometry geomB ) { if ( geomA == null || geomB == null ) { return null ; } return geomA . getFactory ( ) . createPoint ( DistanceOp . nearestPoints ( geomA , geomB ) [ 0 ] ) ; }
Returns the 2D point on geometry A that is closest to geometry B .
6,095
public static MultiLineString createSegments ( Geometry geom ) throws SQLException { if ( geom != null ) { List < LineString > result ; if ( geom . getDimension ( ) > 0 ) { result = new LinkedList < LineString > ( ) ; createSegments ( geom , result ) ; return GEOMETRY_FACTORY . createMultiLineString ( result . toArray ( new LineString [ 0 ] ) ) ; } else { return GEOMETRY_FACTORY . createMultiLineString ( null ) ; } } return null ; }
Converts a geometry into a set of distinct segments stored in a MultiLineString .
6,096
public static void writeGeoJson ( Connection connection , String fileName , String tableReference , String encoding ) throws IOException , SQLException { GeoJsonDriverFunction geoJsonDriver = new GeoJsonDriverFunction ( ) ; geoJsonDriver . exportTable ( connection , tableReference , URIUtilities . fileFromString ( fileName ) , new EmptyProgressVisitor ( ) , encoding ) ; }
Write the GeoJSON file .
6,097
public static Geometry removeHoles ( Geometry geometry ) { if ( geometry == null ) { return null ; } if ( geometry instanceof Polygon ) { return removeHolesPolygon ( ( Polygon ) geometry ) ; } else if ( geometry instanceof MultiPolygon ) { return removeHolesMultiPolygon ( ( MultiPolygon ) geometry ) ; } else if ( geometry instanceof GeometryCollection ) { Geometry [ ] geometries = new Geometry [ geometry . getNumGeometries ( ) ] ; for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry geom = geometry . getGeometryN ( i ) ; if ( geometry instanceof Polygon ) { geometries [ i ] = removeHolesPolygon ( ( Polygon ) geom ) ; } else if ( geometry instanceof MultiPolygon ) { geometries [ i ] = removeHolesMultiPolygon ( ( MultiPolygon ) geom ) ; } else { geometries [ i ] = geom ; } } return FACTORY . createGeometryCollection ( geometries ) ; } return null ; }
Remove any holes from the geometry . If the geometry doesn t contain any holes return it unchanged .
6,098
public static MultiPolygon removeHolesMultiPolygon ( MultiPolygon multiPolygon ) { int num = multiPolygon . getNumGeometries ( ) ; Polygon [ ] polygons = new Polygon [ num ] ; for ( int i = 0 ; i < num ; i ++ ) { polygons [ i ] = removeHolesPolygon ( ( Polygon ) multiPolygon . getGeometryN ( i ) ) ; } return multiPolygon . getFactory ( ) . createMultiPolygon ( polygons ) ; }
Create a new multiPolygon without hole .
6,099
public static Polygon removeHolesPolygon ( Polygon polygon ) { return new Polygon ( ( LinearRing ) polygon . getExteriorRing ( ) , null , polygon . getFactory ( ) ) ; }
Create a new polygon without hole .