idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
6,100 | private static LineString linearZInterpolation ( LineString lineString ) { double startz = lineString . getStartPoint ( ) . getCoordinate ( ) . z ; double endz = lineString . getEndPoint ( ) . getCoordinate ( ) . z ; if ( Double . isNaN ( startz ) || Double . isNaN ( endz ) ) { return lineString ; } else { double length = lineString . getLength ( ) ; lineString . apply ( new LinearZInterpolationFilter ( startz , endz , length ) ) ; return lineString ; } } | Interpolate a linestring according the start and the end coordinates z value . If the start or the end z is NaN return the input linestring |
6,101 | private static MultiLineString linearZInterpolation ( MultiLineString multiLineString ) { int nbGeom = multiLineString . getNumGeometries ( ) ; LineString [ ] lines = new LineString [ nbGeom ] ; for ( int i = 0 ; i < nbGeom ; i ++ ) { LineString subGeom = ( LineString ) multiLineString . getGeometryN ( i ) ; double startz = subGeom . getStartPoint ( ) . getCoordinates ( ) [ 0 ] . z ; double endz = subGeom . getEndPoint ( ) . getCoordinates ( ) [ 0 ] . z ; double length = subGeom . getLength ( ) ; subGeom . apply ( new LinearZInterpolationFilter ( startz , endz , length ) ) ; lines [ i ] = subGeom ; } return FACTORY . createMultiLineString ( lines ) ; } | Interpolate each linestring of the multilinestring . |
6,102 | public boolean isMultiPoint ( ) { boolean mp = true ; if ( this == UNDEFINED ) { mp = false ; } else if ( this == NULL ) { mp = false ; } else if ( this == POINT ) { mp = false ; } return mp ; } | Is this a multipoint shape? Hint - all shapes are multipoint except NULL UNDEFINED and the POINTs . |
6,103 | public static ShapeType forID ( int id ) { ShapeType t ; switch ( id ) { case 0 : t = NULL ; break ; case 1 : t = POINT ; break ; case 11 : t = POINTZ ; break ; case 21 : t = POINTM ; break ; case 3 : t = ARC ; break ; case 13 : t = ARCZ ; break ; case 23 : t = ARCM ; break ; case 5 : t = POLYGON ; break ; case 15 : t = POLYGONZ ; break ; case 25 : t = POLYGONM ; break ; case 8 : t = MULTIPOINT ; break ; case 18 : t = MULTIPOINTZ ; break ; case 28 : t = MULTIPOINTM ; break ; default : t = UNDEFINED ; break ; } return t ; } | Determine the ShapeType for the id . |
6,104 | public ShapeHandler getShapeHandler ( ) throws ShapefileException { ShapeHandler handler ; switch ( id ) { case 1 : case 11 : case 21 : handler = new PointHandler ( this ) ; break ; case 3 : case 13 : case 23 : handler = new MultiLineHandler ( this ) ; break ; case 5 : case 15 : case 25 : handler = new PolygonHandler ( this ) ; break ; case 8 : case 18 : case 28 : handler = new MultiPointHandler ( this ) ; break ; default : handler = null ; } return handler ; } | Each ShapeType corresponds to a handler . In the future this should probably go else where to allow different handlers or something ... |
6,105 | public static PreparedStatement createTagTable ( Connection connection , String tagTableName ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { stmt . execute ( "CREATE TABLE " + tagTableName + "(ID_TAG SERIAL PRIMARY KEY, TAG_KEY VARCHAR UNIQUE);" ) ; } return connection . prepareStatement ( "INSERT INTO " + tagTableName + " (TAG_KEY) VALUES (?)" ) ; } | Create the tag table to store all key and value |
6,106 | public static PreparedStatement createWayTagTable ( Connection connection , String wayTagTableName , String tagTableName ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( wayTagTableName ) ; sb . append ( "(ID_WAY BIGINT, ID_TAG BIGINT, VALUE VARCHAR);" ) ; stmt . execute ( sb . toString ( ) ) ; } StringBuilder insert = new StringBuilder ( "INSERT INTO " ) ; insert . append ( wayTagTableName ) ; insert . append ( "VALUES ( ?, " ) ; insert . append ( "(SELECT ID_TAG FROM " ) . append ( tagTableName ) . append ( " WHERE TAG_KEY = ? LIMIT 1)" ) ; insert . append ( ", ?);" ) ; return connection . prepareStatement ( insert . toString ( ) ) ; } | Create a table to store the way tags . |
6,107 | public static PreparedStatement createWayNodeTable ( Connection connection , String wayNodeTableName ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( wayNodeTableName ) ; sb . append ( "(ID_WAY BIGINT, ID_NODE BIGINT, NODE_ORDER INT);" ) ; stmt . execute ( sb . toString ( ) ) ; } return connection . prepareStatement ( "INSERT INTO " + wayNodeTableName + " VALUES ( ?, ?,?);" ) ; } | Create a table to store the list of nodes for each way . |
6,108 | public static PreparedStatement createRelationTable ( Connection connection , String relationTable ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( relationTable ) ; sb . append ( "(ID_RELATION BIGINT PRIMARY KEY," + "USER_NAME VARCHAR," + "UID BIGINT," + "VISIBLE BOOLEAN," + "VERSION INTEGER," + "CHANGESET INTEGER," + "LAST_UPDATE TIMESTAMP);" ) ; stmt . execute ( sb . toString ( ) ) ; } return connection . prepareStatement ( "INSERT INTO " + relationTable + " VALUES ( ?,?,?,?,?,?,?);" ) ; } | Create the relation table . |
6,109 | public static PreparedStatement createNodeMemberTable ( Connection connection , String nodeMemberTable ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( nodeMemberTable ) ; sb . append ( "(ID_RELATION BIGINT,ID_NODE BIGINT, ROLE VARCHAR, NODE_ORDER INT);" ) ; stmt . execute ( sb . toString ( ) ) ; } return connection . prepareStatement ( "INSERT INTO " + nodeMemberTable + " VALUES ( ?,?,?,?);" ) ; } | Create the node members table |
6,110 | public static PreparedStatement createWayMemberTable ( Connection connection , String wayMemberTable ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( wayMemberTable ) ; sb . append ( "(ID_RELATION BIGINT, ID_WAY BIGINT, ROLE VARCHAR, WAY_ORDER INT);" ) ; stmt . execute ( sb . toString ( ) ) ; } return connection . prepareStatement ( "INSERT INTO " + wayMemberTable + " VALUES ( ?,?,?,?);" ) ; } | Create a table to store all way members . |
6,111 | public static PreparedStatement createRelationMemberTable ( Connection connection , String relationMemberTable ) throws SQLException { try ( Statement stmt = connection . createStatement ( ) ) { StringBuilder sb = new StringBuilder ( "CREATE TABLE " ) ; sb . append ( relationMemberTable ) ; sb . append ( "(ID_RELATION BIGINT, ID_SUB_RELATION BIGINT, ROLE VARCHAR, RELATION_ORDER INT);" ) ; stmt . execute ( sb . toString ( ) ) ; } return connection . prepareStatement ( "INSERT INTO " + relationMemberTable + " VALUES ( ?,?,?,?);" ) ; } | Store all relation members |
6,112 | public static void dropOSMTables ( Connection connection , boolean isH2 , String tablePrefix ) throws SQLException { TableLocation requestedTable = TableLocation . parse ( tablePrefix , isH2 ) ; String osmTableName = requestedTable . getTable ( ) ; String [ ] omsTables = new String [ ] { TAG , NODE , NODE_TAG , WAY , WAY_NODE , WAY_TAG , RELATION , RELATION_TAG , NODE_MEMBER , WAY_MEMBER , RELATION_MEMBER } ; StringBuilder sb = new StringBuilder ( "drop table if exists " ) ; String omsTableSuffix = omsTables [ 0 ] ; String osmTable = TableUtilities . caseIdentifier ( requestedTable , osmTableName + omsTableSuffix , isH2 ) ; sb . append ( osmTable ) ; for ( int i = 1 ; i < omsTables . length ; i ++ ) { omsTableSuffix = omsTables [ i ] ; osmTable = TableUtilities . caseIdentifier ( requestedTable , osmTableName + omsTableSuffix , isH2 ) ; sb . append ( "," ) . append ( osmTable ) ; } try ( Statement stmt = connection . createStatement ( ) ) { stmt . execute ( sb . toString ( ) ) ; } } | Drop the existing OSM tables used to store the imported OSM data |
6,113 | public static Triangle createTriangle ( Geometry geom ) throws IllegalArgumentException { Coordinate [ ] coordinates = geom . getCoordinates ( ) ; if ( coordinates . length != 4 ) { throw new IllegalArgumentException ( "The geometry must be a triangle" ) ; } return new Triangle ( coordinates [ 0 ] , coordinates [ 1 ] , coordinates [ 2 ] ) ; } | A factory to create a DTriangle from a Geometry |
6,114 | public static void toKMLLineString ( LineString lineString , ExtrudeMode extrude , int altitudeModeEnum , StringBuilder sb ) { sb . append ( "<LineString>" ) ; appendExtrude ( extrude , sb ) ; appendAltitudeMode ( altitudeModeEnum , sb ) ; appendKMLCoordinates ( lineString . getCoordinates ( ) , sb ) ; sb . append ( "</LineString>" ) ; } | Defines a connected set of line segments . |
6,115 | public static void toKMLPolygon ( Polygon polygon , ExtrudeMode extrude , int altitudeModeEnum , StringBuilder sb ) { sb . append ( "<Polygon>" ) ; appendExtrude ( extrude , sb ) ; appendAltitudeMode ( altitudeModeEnum , sb ) ; sb . append ( "<outerBoundaryIs>" ) ; toKMLLinearRing ( polygon . getExteriorRing ( ) , extrude , altitudeModeEnum , sb ) ; sb . append ( "</outerBoundaryIs>" ) ; for ( int i = 0 ; i < polygon . getNumInteriorRing ( ) ; i ++ ) { sb . append ( "<innerBoundaryIs>" ) ; toKMLLinearRing ( polygon . getInteriorRingN ( i ) , extrude , altitudeModeEnum , sb ) ; sb . append ( "</innerBoundaryIs>" ) ; } sb . append ( "</Polygon>" ) ; } | A Polygon is defined by an outer boundary and 0 or more inner boundaries . The boundaries in turn are defined by LinearRings . |
6,116 | public static void appendKMLCoordinates ( Coordinate [ ] coords , StringBuilder sb ) { sb . append ( "<coordinates>" ) ; for ( int i = 0 ; i < coords . length ; i ++ ) { Coordinate coord = coords [ i ] ; sb . append ( coord . x ) . append ( "," ) . append ( coord . y ) ; if ( ! Double . isNaN ( coord . z ) ) { sb . append ( "," ) . append ( coord . z ) ; } if ( i < coords . length - 1 ) { sb . append ( " " ) ; } } sb . append ( "</coordinates>" ) ; } | Build a string represention to kml coordinates |
6,117 | private static void appendExtrude ( ExtrudeMode extrude , StringBuilder sb ) { if ( extrude . equals ( ExtrudeMode . TRUE ) ) { sb . append ( "<extrude>" ) . append ( 1 ) . append ( "</extrude>" ) ; } else if ( extrude . equals ( ExtrudeMode . FALSE ) ) { sb . append ( "<extrude>" ) . append ( 0 ) . append ( "</extrude>" ) ; } } | Append the extrude value |
6,118 | public static String getGeometryTypeNameFromConstraint ( String constraint , int numericPrecision ) { int geometryTypeCode = GeometryTypeFromConstraint . geometryTypeFromConstraint ( constraint , numericPrecision ) ; return SFSUtilities . getGeometryTypeNameFromCode ( geometryTypeCode ) ; } | Parse the constraint and return the Geometry type name . |
6,119 | public static Integer getCoordinateDimension ( byte [ ] geom ) throws IOException { if ( geom == null ) { return null ; } return GeometryMetaData . getMetaDataFromWKB ( geom ) . dimension ; } | Returns the dimension of the coordinates of the given geometry . |
6,120 | public static Point getCircumCenter ( Geometry geometry ) { if ( geometry == null || geometry . getNumPoints ( ) == 0 ) { return null ; } return geometry . getFactory ( ) . createPoint ( new MinimumBoundingCircle ( geometry ) . getCentre ( ) ) ; } | Compute the minimum bounding circle center of a geometry |
6,121 | public void initDriverFromFile ( File dbfFile , String forceEncoding ) throws IOException { this . dbfFile = dbfFile ; FileInputStream fis = new FileInputStream ( dbfFile ) ; dbaseFileReader = new DbaseFileReader ( fis . getChannel ( ) , forceEncoding ) ; } | Init file header for DBF File |
6,122 | public void insertRow ( Object [ ] values ) throws IOException { checkWriter ( ) ; if ( values . length != getDbaseFileHeader ( ) . getNumFields ( ) ) { throw new IllegalArgumentException ( "Incorrect field count " + values . length + " expected " + getFieldCount ( ) ) ; } try { dbaseFileWriter . write ( values ) ; } catch ( DbaseFileException ex ) { throw new IOException ( ex . getLocalizedMessage ( ) , ex ) ; } } | Write a row |
6,123 | public static Geometry computePositiveRingBuffer ( Geometry geom , double bufferDistance , int numBuffer , BufferParameters bufferParameters , boolean doDifference ) throws SQLException { Polygon [ ] buffers = new Polygon [ numBuffer ] ; if ( geom instanceof Polygon ) { geom = geom . getFactory ( ) . createPolygon ( ( ( Polygon ) geom ) . getExteriorRing ( ) . getCoordinateSequence ( ) ) ; } Geometry previous = geom ; double distance = 0 ; for ( int i = 0 ; i < numBuffer ; i ++ ) { distance += bufferDistance ; Geometry newBuffer = runBuffer ( geom , distance , bufferParameters ) ; if ( doDifference ) { buffers [ i ] = ( Polygon ) newBuffer . difference ( previous ) ; } else { buffers [ i ] = ( Polygon ) newBuffer ; } previous = newBuffer ; } return geom . getFactory ( ) . createMultiPolygon ( buffers ) ; } | Compute a ring buffer with a positive offset |
6,124 | public static Geometry computeNegativeRingBuffer ( Geometry geom , double bufferDistance , int numBuffer , BufferParameters bufferParameters , boolean doDifference ) throws SQLException { Polygon [ ] buffers = new Polygon [ numBuffer ] ; Geometry previous = geom ; double distance = 0 ; if ( geom instanceof Polygon ) { geom = ( ( Polygon ) geom ) . getExteriorRing ( ) ; bufferParameters . setSingleSided ( true ) ; } for ( int i = 0 ; i < numBuffer ; i ++ ) { distance += bufferDistance ; Geometry newBuffer = runBuffer ( geom , distance , bufferParameters ) ; if ( i == 0 ) { buffers [ i ] = ( Polygon ) newBuffer ; } else { if ( doDifference ) { buffers [ i ] = ( Polygon ) newBuffer . difference ( previous ) ; } else { buffers [ i ] = ( Polygon ) newBuffer ; } } previous = newBuffer ; } return geom . getFactory ( ) . createMultiPolygon ( buffers ) ; } | Compute a ring buffer with a negative offset |
6,125 | public static Geometry runBuffer ( final Geometry geom , final double bufferSize , final BufferParameters bufferParameters ) throws SQLException { return BufferOp . bufferOp ( geom , bufferSize , bufferParameters ) ; } | Calculate the ring buffer |
6,126 | public static Boolean covers ( Geometry geomA , Geometry geomB ) { if ( geomA == null || geomB == null ) { return null ; } return geomA . covers ( geomB ) ; } | Returns true if no point in geometry B is outside geometry A . |
6,127 | public static Vector3D getNormalVector ( Triangle t ) throws IllegalArgumentException { if ( Double . isNaN ( t . p0 . z ) || Double . isNaN ( t . p1 . z ) || Double . isNaN ( t . p2 . z ) ) { throw new IllegalArgumentException ( "Z is required, cannot compute triangle normal of " + t ) ; } double dx1 = t . p0 . x - t . p1 . x ; double dy1 = t . p0 . y - t . p1 . y ; double dz1 = t . p0 . z - t . p1 . z ; double dx2 = t . p1 . x - t . p2 . x ; double dy2 = t . p1 . y - t . p2 . y ; double dz2 = t . p1 . z - t . p2 . z ; return Vector3D . create ( dy1 * dz2 - dz1 * dy2 , dz1 * dx2 - dx1 * dz2 , dx1 * dy2 - dy1 * dx2 ) . normalize ( ) ; } | Get the normal vector to this triangle of length 1 . |
6,128 | public static Vector3D getSteepestVector ( final Vector3D normal , final double epsilon ) { if ( Math . abs ( normal . getX ( ) ) < epsilon && Math . abs ( normal . getY ( ) ) < epsilon ) { return new Vector3D ( 0 , 0 , 0 ) ; } Vector3D slope ; if ( Math . abs ( normal . getX ( ) ) < epsilon ) { slope = new Vector3D ( 0 , 1 , - normal . getY ( ) / normal . getZ ( ) ) ; } else if ( Math . abs ( normal . getY ( ) ) < epsilon ) { slope = new Vector3D ( 1 , 0 , - normal . getX ( ) / normal . getZ ( ) ) ; } else { slope = new Vector3D ( normal . getX ( ) / normal . getY ( ) , 1 , - 1 / normal . getZ ( ) * ( normal . getX ( ) * normal . getX ( ) / normal . getY ( ) + normal . getY ( ) ) ) ; } if ( slope . getZ ( ) > epsilon ) { slope = new Vector3D ( - slope . getX ( ) , - slope . getY ( ) , - slope . getZ ( ) ) ; } return slope . normalize ( ) ; } | Get the vector with the highest down slope in the plan . |
6,129 | public static Geometry scale ( Geometry geom , double xFactor , double yFactor ) { return scale ( geom , xFactor , yFactor , 1.0 ) ; } | Scales the given geometry by multiplying the coordinates by the indicated x and y scale factors leaving the z - coordinate untouched . |
6,130 | public static Geometry scale ( Geometry geom , double xFactor , double yFactor , double zFactor ) { if ( geom != null ) { Geometry scaledGeom = geom . copy ( ) ; for ( Coordinate c : scaledGeom . getCoordinates ( ) ) { c . setOrdinate ( Coordinate . X , c . getOrdinate ( Coordinate . X ) * xFactor ) ; c . setOrdinate ( Coordinate . Y , c . getOrdinate ( Coordinate . Y ) * yFactor ) ; c . setOrdinate ( Coordinate . Z , c . getOrdinate ( Coordinate . Z ) * zFactor ) ; } return scaledGeom ; } else { return null ; } } | Scales the given geometry by multiplying the coordinates by the indicated x y and z scale factors . |
6,131 | public static Geometry lineIntersector ( Geometry inputLines , Geometry clipper ) throws IllegalArgumentException { if ( inputLines == null || clipper == null ) { return null ; } if ( inputLines . getDimension ( ) == 1 ) { MCIndexNoder mCIndexNoder = new MCIndexNoder ( ) ; mCIndexNoder . setSegmentIntersector ( new IntersectionAdder ( ROBUST_INTERSECTOR ) ) ; mCIndexNoder . computeNodes ( getSegments ( inputLines , clipper ) ) ; Collection nodedSubstring = mCIndexNoder . getNodedSubstrings ( ) ; GeometryFactory gf = inputLines . getFactory ( ) ; ArrayList < LineString > linestrings = new ArrayList < LineString > ( nodedSubstring . size ( ) ) ; for ( Iterator it = nodedSubstring . iterator ( ) ; it . hasNext ( ) ; ) { SegmentString segment = ( SegmentString ) it . next ( ) ; if ( ( Integer ) segment . getData ( ) == 0 ) { Coordinate [ ] cc = segment . getCoordinates ( ) ; cc = CoordinateArrays . atLeastNCoordinatesOrNothing ( 2 , cc ) ; if ( cc . length > 1 ) { linestrings . add ( gf . createLineString ( cc ) ) ; } } } if ( linestrings . isEmpty ( ) ) { return inputLines ; } else { return gf . createMultiLineString ( linestrings . toArray ( new LineString [ 0 ] ) ) ; } } throw new IllegalArgumentException ( "Split a " + inputLines . getGeometryType ( ) + " by a " + clipper . getGeometryType ( ) + " is not supported." ) ; } | Split a lineal geometry by a another geometry |
6,132 | public static void addGeometryToSegments ( Geometry geometry , int flag , ArrayList < SegmentString > segments ) { for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry component = geometry . getGeometryN ( i ) ; if ( component instanceof Polygon ) { add ( ( Polygon ) component , flag , segments ) ; } else if ( component instanceof LineString ) { add ( ( LineString ) component , flag , segments ) ; } } } | Convert the a geometry as a list of segments and mark it with a flag |
6,133 | private static void add ( Polygon poly , int flag , ArrayList < SegmentString > segments ) { add ( poly . getExteriorRing ( ) , flag , segments ) ; for ( int j = 0 ; j < poly . getNumInteriorRing ( ) ; j ++ ) { add ( poly . getInteriorRingN ( j ) , flag , segments ) ; } } | Convert a polygon as a list of segments and mark it with a flag |
6,134 | private static void add ( LineString line , int flag , ArrayList < SegmentString > segments ) { SegmentString ss = new NodedSegmentString ( line . getCoordinates ( ) , flag ) ; segments . add ( ss ) ; } | Convert a linestring as a list of segments and mark it with a flag |
6,135 | public static MultiPoint locateAlong ( Geometry geom , double segmentLengthFraction , double offsetDistance ) { if ( geom == null ) { return null ; } if ( geom . getDimension ( ) == 0 ) { return null ; } Set < Coordinate > result = new HashSet < Coordinate > ( ) ; for ( int i = 0 ; i < geom . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geom . getGeometryN ( i ) ; if ( subGeom instanceof Polygon ) { result . addAll ( computePoints ( ( ( Polygon ) subGeom ) . getExteriorRing ( ) . getCoordinates ( ) , segmentLengthFraction , offsetDistance ) ) ; } else if ( subGeom instanceof LineString ) { result . addAll ( computePoints ( subGeom . getCoordinates ( ) , segmentLengthFraction , offsetDistance ) ) ; } } return geom . getFactory ( ) . createMultiPoint ( result . toArray ( new Coordinate [ 0 ] ) ) ; } | Returns a MULTIPOINT containing points along the line segments of the given geometry matching the specified segment length fraction and offset distance . |
6,136 | public static void load ( Connection connection ) throws SQLException { Statement st = connection . createStatement ( ) ; for ( Function function : getBuiltInsFunctions ( ) ) { try { H2GISFunctions . registerFunction ( st , function , "" ) ; } catch ( SQLException ex ) { LOGGER . error ( ex . getLocalizedMessage ( ) , ex ) ; } } } | Init H2 DataBase with the network functions |
6,137 | public void close ( ) throws IOException { if ( channel != null && channel . isOpen ( ) ) { channel . close ( ) ; } channel = null ; header = null ; } | Clean up any resources . Closes the channel . |
6,138 | public Geometry geomAt ( int offset ) throws IOException { buffer . position ( offset ) ; buffer . skip ( 8 ) ; buffer . order ( ByteOrder . LITTLE_ENDIAN ) ; ShapeType recordType = ShapeType . forID ( buffer . getInt ( ) ) ; if ( recordType != ShapeType . NULL && recordType != fileShapeType ) { throw new IllegalStateException ( "ShapeType changed illegally from " + fileShapeType + " to " + recordType ) ; } return handler . read ( buffer , recordType ) ; } | Fetch the next record information . |
6,139 | public static Double st3Dperimeter ( Geometry geometry ) { if ( geometry == null ) { return null ; } if ( geometry . getDimension ( ) < 2 ) { return 0d ; } return compute3DPerimeter ( geometry ) ; } | Compute the 3D perimeter of a polygon or a multipolygon . |
6,140 | private static double compute3DPerimeter ( Geometry geometry ) { double sum = 0 ; for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geometry . getGeometryN ( i ) ; if ( subGeom instanceof Polygon ) { sum += ST_3DLength . length3D ( ( ( Polygon ) subGeom ) . getExteriorRing ( ) ) ; } } return sum ; } | Compute the 3D perimeter |
6,141 | public static int dimensionFromConstraint ( String constraint , String columnName ) { Matcher matcher = Z_CONSTRAINT_PATTERN . matcher ( constraint ) ; if ( matcher . find ( ) ) { String extractedColumnName = matcher . group ( 1 ) . replace ( "\"" , "" ) . replace ( "`" , "" ) ; if ( extractedColumnName . equalsIgnoreCase ( columnName ) ) { int constraint_value = Integer . valueOf ( matcher . group ( 8 ) ) ; String sign = matcher . group ( 5 ) ; if ( "<>" . equals ( sign ) || "!=" . equals ( sign ) ) { constraint_value = constraint_value == 3 ? 2 : 3 ; } if ( "<" . equals ( sign ) ) { constraint_value = 2 ; } if ( ">" . equals ( sign ) ) { constraint_value = constraint_value == 2 ? 3 : 2 ; } return constraint_value ; } } return 2 ; } | Public for Unit test |
6,142 | public static double length3D ( Geometry geom ) { double sum = 0 ; for ( int i = 0 ; i < geom . getNumGeometries ( ) ; i ++ ) { sum += length3D ( ( LineString ) geom . getGeometryN ( i ) ) ; } return sum ; } | Returns the 3D length of the given geometry . |
6,143 | public static double length3D ( Polygon polygon ) { double length = 0.0 ; length += length3D ( polygon . getExteriorRing ( ) . getCoordinateSequence ( ) ) ; for ( int i = 0 ; i < polygon . getNumInteriorRing ( ) ; i ++ ) { length += length3D ( polygon . getInteriorRingN ( i ) ) ; } return length ; } | Returns the 3D perimeter of the given polygon . |
6,144 | public static double length3D ( CoordinateSequence points ) { int numberOfCoords = points . size ( ) ; if ( numberOfCoords < 2 ) { return 0.0 ; } Coordinate currentCoord = new Coordinate ( ) ; points . getCoordinate ( 0 , currentCoord ) ; double x0 = currentCoord . x ; double y0 = currentCoord . y ; double z0 = currentCoord . z ; double length = 0.0 ; for ( int i = 1 ; i < numberOfCoords ; i ++ ) { points . getCoordinate ( i , currentCoord ) ; double x1 = currentCoord . x ; double y1 = currentCoord . y ; double z1 = currentCoord . z ; double dx = x1 - x0 ; double dy = y1 - y0 ; double dz ; if ( Double . isNaN ( z0 ) || Double . isNaN ( z1 ) ) { dz = 0.0 ; } else { dz = z1 - z0 ; } length += Math . sqrt ( dx * dx + dy * dy + dz * dz ) ; x0 = x1 ; y0 = y1 ; z0 = z1 ; } return length ; } | Computes the length of a LineString specified by a sequence of coordinates . |
6,145 | public static Geometry sunPosition ( Geometry point , Date date ) throws IllegalArgumentException { if ( point == null ) { return null ; } if ( point instanceof Point ) { Coordinate coord = point . getCoordinate ( ) ; return point . getFactory ( ) . createPoint ( SunCalc . getPosition ( date , coord . y , coord . x ) ) ; } else { throw new IllegalArgumentException ( "The sun position is computed according a point location." ) ; } } | Return the sun position for a given date |
6,146 | public static Geometry offsetCurve ( Geometry geometry , double offset , String parameters ) { if ( geometry == null ) { return null ; } String [ ] buffParemeters = parameters . split ( "\\s+" ) ; BufferParameters bufferParameters = new BufferParameters ( ) ; for ( String params : buffParemeters ) { String [ ] keyValue = params . split ( "=" ) ; if ( keyValue [ 0 ] . equalsIgnoreCase ( "endcap" ) ) { String param = keyValue [ 1 ] ; if ( param . equalsIgnoreCase ( "round" ) ) { bufferParameters . setEndCapStyle ( BufferParameters . CAP_ROUND ) ; } else if ( param . equalsIgnoreCase ( "flat" ) || param . equalsIgnoreCase ( "butt" ) ) { bufferParameters . setEndCapStyle ( BufferParameters . CAP_FLAT ) ; } else if ( param . equalsIgnoreCase ( "square" ) ) { bufferParameters . setEndCapStyle ( BufferParameters . CAP_SQUARE ) ; } else { throw new IllegalArgumentException ( "Supported join values are round, flat, butt or square." ) ; } } else if ( keyValue [ 0 ] . equalsIgnoreCase ( "join" ) ) { String param = keyValue [ 1 ] ; if ( param . equalsIgnoreCase ( "bevel" ) ) { bufferParameters . setJoinStyle ( BufferParameters . JOIN_BEVEL ) ; } else if ( param . equalsIgnoreCase ( "mitre" ) || param . equalsIgnoreCase ( "miter" ) ) { bufferParameters . setJoinStyle ( BufferParameters . JOIN_MITRE ) ; } else if ( param . equalsIgnoreCase ( "round" ) ) { bufferParameters . setJoinStyle ( BufferParameters . JOIN_ROUND ) ; } else { throw new IllegalArgumentException ( "Supported join values are bevel, mitre, miter or round." ) ; } } else if ( keyValue [ 0 ] . equalsIgnoreCase ( "mitre_limit" ) || keyValue [ 0 ] . equalsIgnoreCase ( "miter_limit" ) ) { bufferParameters . setMitreLimit ( Double . valueOf ( keyValue [ 1 ] ) ) ; } else if ( keyValue [ 0 ] . equalsIgnoreCase ( "quad_segs" ) ) { bufferParameters . setQuadrantSegments ( Integer . valueOf ( keyValue [ 1 ] ) ) ; } else { throw new IllegalArgumentException ( "Unknown parameters. Please read the documentation." ) ; } } return computeOffsetCurve ( geometry , offset , bufferParameters ) ; } | Return an offset line at a given distance and side from an input geometry |
6,147 | public static Geometry computeOffsetCurve ( Geometry geometry , double offset , BufferParameters bufferParameters ) { ArrayList < LineString > lineStrings = new ArrayList < LineString > ( ) ; for ( int i = 0 ; i < geometry . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geometry . getGeometryN ( i ) ; if ( subGeom . getDimension ( ) == 1 ) { lineStringOffSetCurve ( lineStrings , ( LineString ) subGeom , offset , bufferParameters ) ; } else { geometryOffSetCurve ( lineStrings , subGeom , offset , bufferParameters ) ; } } if ( ! lineStrings . isEmpty ( ) ) { if ( lineStrings . size ( ) == 1 ) { return lineStrings . get ( 0 ) ; } else { return geometry . getFactory ( ) . createMultiLineString ( lineStrings . toArray ( new LineString [ 0 ] ) ) ; } } return null ; } | Method to compute the offset line |
6,148 | public static void lineStringOffSetCurve ( ArrayList < LineString > list , LineString lineString , double offset , BufferParameters bufferParameters ) { list . add ( lineString . getFactory ( ) . createLineString ( new OffsetCurveBuilder ( lineString . getPrecisionModel ( ) , bufferParameters ) . getOffsetCurve ( lineString . getCoordinates ( ) , offset ) ) ) ; } | Compute the offset curve for a linestring |
6,149 | public static void geometryOffSetCurve ( ArrayList < LineString > list , Geometry geometry , double offset , BufferParameters bufferParameters ) { final List curves = new OffsetCurveSetBuilder ( geometry , offset , new OffsetCurveBuilder ( geometry . getFactory ( ) . getPrecisionModel ( ) , bufferParameters ) ) . getCurves ( ) ; final Iterator < SegmentString > iterator = curves . iterator ( ) ; while ( iterator . hasNext ( ) ) { list . add ( geometry . getFactory ( ) . createLineString ( iterator . next ( ) . getCoordinates ( ) ) ) ; } } | Compute the offset curve for a polygon a point or a collection of geometries |
6,150 | public static Geometry longestLine ( Geometry geomA , Geometry geomB ) { Coordinate [ ] coords = new MaxDistanceOp ( geomA , geomB ) . getCoordinatesDistance ( ) ; if ( coords != null ) { return geomA . getFactory ( ) . createLineString ( coords ) ; } return null ; } | Return the longest line between the points of two geometries . |
6,151 | public static Geometry force2D ( Geometry geom ) { if ( geom == null ) { return null ; } return GeometryCoordinateDimension . force ( geom , 2 ) ; } | Converts a XYZ geometry to XY . |
6,152 | public static GeometryMetaData getMetaDataFromWKB ( byte [ ] bytes ) throws IOException { ByteOrderDataInStream dis = new ByteOrderDataInStream ( ) ; dis . setInStream ( new ByteArrayInStream ( bytes ) ) ; byte byteOrderWKB = dis . readByte ( ) ; int byteOrder = byteOrderWKB == WKBConstants . wkbNDR ? ByteOrderValues . LITTLE_ENDIAN : ByteOrderValues . BIG_ENDIAN ; dis . setOrder ( byteOrder ) ; int typeInt = dis . readInt ( ) ; int geometryType = typeInt & 0xff ; boolean hasZ = ( typeInt & 0x80000000 ) != 0 ; int inputDimension = hasZ ? 3 : 2 ; boolean hasSRID = ( typeInt & 0x20000000 ) != 0 ; int SRID = 0 ; if ( hasSRID ) { SRID = dis . readInt ( ) ; } return new GeometryMetaData ( inputDimension , hasSRID , hasZ , geometryType , SRID ) ; } | Read the first bytes of Geometry WKB . |
6,153 | public void writeHeaders ( ShapeType type ) throws IOException { try { handler = type . getShapeHandler ( ) ; } catch ( ShapefileException se ) { throw new IOException ( "Error with type " + type , se ) ; } if ( indexBuffer != null ) { indexBuffer . flush ( ) ; } if ( shapeBuffer != null ) { shapeBuffer . flush ( ) ; } long fileLength = shpChannel . position ( ) ; shpChannel . position ( 0 ) ; shxChannel . position ( 0 ) ; ShapefileHeader header = new ShapefileHeader ( ) ; Envelope writeBounds = bounds ; if ( writeBounds == null ) { writeBounds = new Envelope ( ) ; } indexBuffer = new WriteBufferManager ( shxChannel ) ; shapeBuffer = new WriteBufferManager ( shpChannel ) ; header . write ( shapeBuffer , type , cnt , ( int ) ( fileLength / 2 ) , writeBounds . getMinX ( ) , writeBounds . getMinY ( ) , writeBounds . getMaxX ( ) , writeBounds . getMaxY ( ) ) ; header . write ( indexBuffer , type , cnt , 50 + 4 * cnt , writeBounds . getMinX ( ) , writeBounds . getMinY ( ) , writeBounds . getMaxX ( ) , writeBounds . getMaxY ( ) ) ; offset = 50 ; this . type = type ; } | Write the headers for this shapefile . Use this function before inserting the first geometry then when all geometries are inserted . |
6,154 | public void writeGeometry ( Geometry g ) throws IOException { if ( type == null ) { throw new IllegalStateException ( "Header must be written before writeGeometry" ) ; } if ( bounds != null ) { if ( g != null ) { bounds . expandToInclude ( g . getEnvelopeInternal ( ) ) ; } } else { bounds = g . getEnvelopeInternal ( ) ; } int length ; if ( g == null ) { length = 4 ; } else { length = handler . getLength ( g ) ; } length /= 2 ; shapeBuffer . order ( ByteOrder . BIG_ENDIAN ) ; shapeBuffer . putInt ( ++ cnt ) ; shapeBuffer . putInt ( length ) ; shapeBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ; if ( g == null ) { shapeBuffer . putInt ( 0 ) ; } else { shapeBuffer . putInt ( type . id ) ; handler . write ( shapeBuffer , g ) ; } indexBuffer . putInt ( offset ) ; indexBuffer . putInt ( length ) ; offset += length + 4 ; } | Write a single Geometry to this shapefile . The Geometry must be compatable with the ShapeType assigned during the writing of the headers . |
6,155 | public void close ( ) throws IOException { indexBuffer . flush ( ) ; shapeBuffer . flush ( ) ; if ( shpChannel != null && shpChannel . isOpen ( ) ) { shpChannel . close ( ) ; } if ( shxChannel != null && shxChannel . isOpen ( ) ) { shxChannel . close ( ) ; } shpChannel = null ; shxChannel = null ; handler = null ; indexBuffer = null ; shapeBuffer = null ; } | Close the underlying Channels . |
6,156 | protected KeyedGraph < V , E > prepareGraph ( ) throws SQLException { LOGGER . info ( "Loading graph into memory..." ) ; final long start = System . currentTimeMillis ( ) ; KeyedGraph < V , E > graph ; if ( ! globalOrientation . equals ( GraphFunctionParser . Orientation . UNDIRECTED ) ) { if ( weightColumn != null ) { graph = new DirectedWeightedPseudoG < V , E > ( vertexClass , edgeClass ) ; } else { graph = new DirectedPseudoG < V , E > ( vertexClass , edgeClass ) ; } } else { if ( weightColumn != null ) { graph = new WeightedPseudoG < V , E > ( vertexClass , edgeClass ) ; } else { graph = new PseudoG < V , E > ( vertexClass , edgeClass ) ; } } final Statement st = connection . createStatement ( ) ; final ResultSet edges = st . executeQuery ( "SELECT * FROM " + TableUtilities . parseInputTable ( connection , inputTable ) ) ; initIndices ( edges ) ; try { while ( edges . next ( ) ) { loadEdge ( graph , edges ) ; } logTime ( LOGGER , start ) ; return graph ; } catch ( SQLException e ) { LOGGER . error ( "Could not store edges in graph." , e ) ; return null ; } finally { edges . close ( ) ; st . close ( ) ; } } | Prepares a graph . |
6,157 | private void initIndices ( ResultSet edges ) { try { ResultSetMetaData metaData = edges . getMetaData ( ) ; for ( int i = 1 ; i <= metaData . getColumnCount ( ) ; i ++ ) { final String columnName = metaData . getColumnName ( i ) ; if ( columnName . equalsIgnoreCase ( START_NODE ) ) startNodeIndex = i ; if ( columnName . equalsIgnoreCase ( END_NODE ) ) endNodeIndex = i ; if ( columnName . equalsIgnoreCase ( EDGE_ID ) ) edgeIDIndex = i ; if ( columnName . equalsIgnoreCase ( edgeOrientationColumnName ) ) edgeOrientationIndex = i ; if ( columnName . equalsIgnoreCase ( weightColumn ) ) weightColumnIndex = i ; } } catch ( SQLException e ) { LOGGER . error ( "Problem accessing edge table metadata." , e ) ; } verifyIndex ( startNodeIndex , START_NODE ) ; verifyIndex ( endNodeIndex , END_NODE ) ; verifyIndex ( edgeIDIndex , EDGE_ID ) ; if ( ! globalOrientation . equals ( GraphFunctionParser . Orientation . UNDIRECTED ) ) { verifyIndex ( edgeOrientationIndex , edgeOrientationColumnName ) ; } if ( weightColumn != null ) { verifyIndex ( weightColumnIndex , weightColumn ) ; } } | Recovers the indices from the metadata . |
6,158 | private E loadEdge ( KeyedGraph < V , E > graph , ResultSet edges ) throws SQLException { final int startNode = edges . getInt ( startNodeIndex ) ; final int endNode = edges . getInt ( endNodeIndex ) ; final int edgeID = edges . getInt ( edgeIDIndex ) ; double weight = WeightedGraph . DEFAULT_EDGE_WEIGHT ; if ( weightColumnIndex != - 1 ) { weight = edges . getDouble ( weightColumnIndex ) ; } E edge ; if ( globalOrientation . equals ( GraphFunctionParser . Orientation . UNDIRECTED ) ) { edge = graph . addEdge ( endNode , startNode , edgeID ) ; } else { int edgeOrientation = ( edgeOrientationIndex == - 1 ) ? DIRECTED_EDGE : edges . getInt ( edgeOrientationIndex ) ; if ( edges . wasNull ( ) ) { throw new IllegalArgumentException ( "Invalid edge orientation: NULL." ) ; } if ( edgeOrientation == UNDIRECTED_EDGE ) { if ( globalOrientation . equals ( GraphFunctionParser . Orientation . DIRECTED ) ) { edge = loadDoubleEdge ( graph , startNode , endNode , edgeID , weight ) ; } else { edge = loadDoubleEdge ( graph , endNode , startNode , edgeID , weight ) ; } } else if ( edgeOrientation == DIRECTED_EDGE ) { if ( globalOrientation . equals ( GraphFunctionParser . Orientation . REVERSED ) ) { edge = graph . addEdge ( endNode , startNode , edgeID ) ; } else { edge = graph . addEdge ( startNode , endNode , edgeID ) ; } } else if ( edgeOrientation == REVERSED_EDGE ) { if ( globalOrientation . equals ( GraphFunctionParser . Orientation . REVERSED ) ) { edge = graph . addEdge ( startNode , endNode , edgeID ) ; } else { edge = graph . addEdge ( endNode , startNode , edgeID ) ; } } else { throw new IllegalArgumentException ( "Invalid edge orientation: " + edgeOrientation ) ; } } setEdgeWeight ( edge , weight ) ; return edge ; } | Loads an edge into the graph from the current row . |
6,159 | private E loadDoubleEdge ( KeyedGraph < V , E > graph , final int startNode , final int endNode , final int edgeID , final double weight ) throws SQLException { final E edgeTo = graph . addEdge ( startNode , endNode , edgeID ) ; setEdgeWeight ( edgeTo , weight ) ; final E edgeFrom = graph . addEdge ( endNode , startNode , - edgeID ) ; setEdgeWeight ( edgeFrom , weight ) ; return edgeFrom ; } | In directed graphs undirected edges are represented by directed edges in both directions . The edges are assigned ids with opposite signs . |
6,160 | private void setEdgeWeight ( E edge , final double weight ) throws SQLException { if ( edge != null && weightColumnIndex != - 1 ) { edge . setWeight ( weight ) ; } } | Set this edge s weight to the weight contained in the current row . |
6,161 | public static Geometry getGeometryN ( Geometry geometry , Integer n ) throws SQLException { if ( geometry == null ) { return null ; } if ( n >= 1 && n <= geometry . getNumGeometries ( ) ) { return geometry . getGeometryN ( n - 1 ) ; } else { throw new SQLException ( OUT_OF_BOUNDS_ERR_MESSAGE ) ; } } | Return Geometry number n from the given GeometryCollection . |
6,162 | public static GeometryCollection getHoles ( Geometry geom ) throws SQLException { if ( geom != null ) { if ( geom . getDimension ( ) >= 2 ) { ArrayList < Geometry > holes = new ArrayList < Geometry > ( ) ; for ( int i = 0 ; i < geom . getNumGeometries ( ) ; i ++ ) { Geometry subgeom = geom . getGeometryN ( i ) ; if ( subgeom instanceof Polygon ) { Polygon polygon = ( Polygon ) subgeom ; for ( int j = 0 ; j < polygon . getNumInteriorRing ( ) ; j ++ ) { holes . add ( GEOMETRY_FACTORY . createPolygon ( GEOMETRY_FACTORY . createLinearRing ( polygon . getInteriorRingN ( j ) . getCoordinates ( ) ) , null ) ) ; } } } return GEOMETRY_FACTORY . createGeometryCollection ( holes . toArray ( new Geometry [ 0 ] ) ) ; } else { return GEOMETRY_FACTORY . createGeometryCollection ( null ) ; } } return null ; } | Returns the given geometry s holes as a GeometryCollection . |
6,163 | public int getLength ( Object geometry ) { MultiPoint mp = ( MultiPoint ) geometry ; int length ; if ( shapeType == ShapeType . MULTIPOINT ) { length = ( mp . getNumGeometries ( ) * 16 ) + 40 ; } else if ( shapeType == ShapeType . MULTIPOINTM ) { length = ( mp . getNumGeometries ( ) * 16 ) + 40 + 16 + ( 8 * mp . getNumGeometries ( ) ) ; } else if ( shapeType == ShapeType . MULTIPOINTZ ) { length = ( mp . getNumGeometries ( ) * 16 ) + 40 + 16 + ( 8 * mp . getNumGeometries ( ) ) + 16 + ( 8 * mp . getNumGeometries ( ) ) ; } else { throw new IllegalStateException ( "Expected ShapeType of Arc, got " + shapeType ) ; } return length ; } | Calcuates the record length of this object . |
6,164 | private static String formatKey ( String prjKey ) { String formatKey = prjKey ; if ( prjKey . startsWith ( "+" ) ) { formatKey = prjKey . substring ( 1 ) ; } return formatKey ; } | Remove + char if exists |
6,165 | public static int getSRID ( File prjFile ) throws IOException { int srid = 0 ; if ( prjFile == null ) { log . debug ( "This prj file is null. \n A default srid equals to 0 will be added." ) ; } else { PrjParser parser = new PrjParser ( ) ; String prjString = readPRJFile ( prjFile ) ; if ( ! prjString . isEmpty ( ) ) { Map < String , String > p = parser . getParameters ( prjString ) ; String authorityWithCode = p . get ( PrjKeyParameters . REFNAME ) ; if ( authorityWithCode != null ) { String [ ] authorityNameWithKey = authorityWithCode . split ( ":" ) ; srid = Integer . valueOf ( authorityNameWithKey [ 1 ] ) ; } } else { log . debug ( "The prj is empty. \n A default srid equals to 0 will be added." ) ; } } return srid ; } | Return the SRID value stored in a prj file |
6,166 | private static String readPRJFile ( File prjFile ) throws FileNotFoundException , IOException { try ( FileInputStream fis = new FileInputStream ( prjFile ) ) { BufferedReader r = new BufferedReader ( new InputStreamReader ( fis , Charset . defaultCharset ( ) ) ) ; StringBuilder b = new StringBuilder ( ) ; while ( r . ready ( ) ) { b . append ( r . readLine ( ) ) ; } return b . toString ( ) ; } } | Return the content of the PRJ file as a single string |
6,167 | public static void writePRJ ( Connection connection , TableLocation location , String geomField , File fileName ) throws SQLException , FileNotFoundException { int srid = SFSUtilities . getSRID ( connection , location , geomField ) ; writePRJ ( connection , srid , fileName ) ; } | Write a prj file according the SRID code of an input table |
6,168 | public static void writePRJ ( Connection connection , int srid , File fileName ) throws SQLException , FileNotFoundException { if ( srid != 0 ) { StringBuilder sb = new StringBuilder ( "SELECT SRTEXT FROM " ) ; sb . append ( "PUBLIC.SPATIAL_REF_SYS " ) . append ( " WHERE SRID = ?" ) ; PreparedStatement ps = connection . prepareStatement ( sb . toString ( ) ) ; ps . setInt ( 1 , srid ) ; PrintWriter printWriter = null ; ResultSet rs = null ; try { rs = ps . executeQuery ( ) ; if ( rs . next ( ) ) { printWriter = new PrintWriter ( fileName ) ; printWriter . println ( rs . getString ( 1 ) ) ; } else { log . warn ( "This SRID { " + srid + " } is not supported. \n The PRJ file won't be created." ) ; } } finally { if ( printWriter != null ) { printWriter . close ( ) ; } if ( rs != null ) { rs . close ( ) ; } ps . close ( ) ; } } } | Write a prj file according a given SRID code . |
6,169 | public static boolean isSRIDValid ( int srid , Connection connection ) throws SQLException { PreparedStatement ps = null ; ResultSet rs = null ; String queryCheck = "SELECT count(SRID) from PUBLIC.SPATIAL_REF_SYS WHERE SRID = ?" ; try { ps = connection . prepareStatement ( queryCheck ) ; ps . setInt ( 1 , srid ) ; rs = ps . executeQuery ( ) ; if ( rs . next ( ) ) { return rs . getInt ( 1 ) != 0 ; } } finally { if ( rs != null ) { rs . close ( ) ; } if ( ps != null ) { ps . close ( ) ; } } return false ; } | This method checks if a SRID value is valid according a list of SRID s avalaible on spatial_ref table of the datababase . |
6,170 | public static boolean isFileImportable ( File file , String prefix ) throws SQLException , FileNotFoundException { if ( isExtensionWellFormated ( file , prefix ) ) { if ( file . exists ( ) ) { return true ; } else { throw new FileNotFoundException ( "The following file does not exists:\n" + file . getPath ( ) ) ; } } else { throw new SQLException ( "Please use " + prefix + " extension." ) ; } } | Check if the file is well formatted regarding an extension prefix . Check also if the file doesn t exist . |
6,171 | public static boolean isExtensionWellFormated ( File file , String prefix ) { String path = file . getAbsolutePath ( ) ; String extension = "" ; int i = path . lastIndexOf ( '.' ) ; if ( i >= 0 ) { extension = path . substring ( i + 1 ) ; } return extension . equalsIgnoreCase ( prefix ) ; } | Check if the file has the good extension |
6,172 | public static String getUniqueColumnName ( String base , List < Column > columns ) { String cursor = base ; int cpt = 2 ; boolean findDuplicate = true ; while ( findDuplicate ) { findDuplicate = false ; for ( Column column : columns ) { if ( column . getName ( ) . equalsIgnoreCase ( cursor ) ) { findDuplicate = true ; break ; } } if ( findDuplicate ) { cursor = base + Integer . toString ( cpt ) ; } } return cursor ; } | Compute unique column name among the other columns |
6,173 | public static Geometry snap ( Geometry geometryA , Geometry geometryB , double distance ) { if ( geometryA == null || geometryB == null ) { return null ; } Geometry [ ] snapped = GeometrySnapper . snap ( geometryA , geometryB , distance ) ; return snapped [ 0 ] ; } | Snaps two geometries together with a given tolerance |
6,174 | public static Geometry updateZ ( Geometry geometry , double z , int updateCondition ) throws SQLException { if ( geometry == null ) { return null ; } if ( updateCondition == 1 || updateCondition == 2 || updateCondition == 3 ) { Geometry outPut = geometry . copy ( ) ; outPut . apply ( new UpdateZCoordinateSequenceFilter ( z , updateCondition ) ) ; return outPut ; } else { throw new SQLException ( "Available values are 1, 2 or 3.\n" + "Please read the description of the function to use it." ) ; } } | Replace the z value depending on the condition . |
6,175 | public boolean read ( File inputFile ) throws SAXException , IOException { boolean success = false ; try ( FileInputStream fs = new FileInputStream ( inputFile ) ) { XMLReader parser = XMLReaderFactory . createXMLReader ( ) ; parser . setErrorHandler ( this ) ; parser . setContentHandler ( this ) ; parser . parse ( new InputSource ( fs ) ) ; success = true ; } return success ; } | Reads the document and pre - parses it . The other method is called automatically when a start markup is found . |
6,176 | public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { if ( localName . compareToIgnoreCase ( GPXTags . GPX ) == 0 ) { version = attributes . getValue ( GPXTags . VERSION ) ; } else if ( localName . compareToIgnoreCase ( GPXTags . RTE ) == 0 ) { totalRte ++ ; } else if ( localName . compareToIgnoreCase ( GPXTags . TRK ) == 0 ) { totalTrk ++ ; } else if ( localName . compareToIgnoreCase ( GPXTags . TRKSEG ) == 0 ) { totalTrkseg ++ ; } else if ( localName . compareToIgnoreCase ( GPXTags . WPT ) == 0 ) { totalWpt ++ ; } else if ( localName . compareToIgnoreCase ( GPXTags . RTEPT ) == 0 ) { totalRtept ++ ; } else if ( localName . compareToIgnoreCase ( GPXTags . TRKPT ) == 0 ) { totalTrkpt ++ ; } } | Fires whenever an XML start markup is encountered . It indicates which version of gpx file is to be parsed . It counts the waypoints routes routepoints tracks track segments and trackpoints . |
6,177 | public static boolean contains3D ( Coordinate [ ] coords , Coordinate coord ) { for ( Coordinate coordinate : coords ) { if ( coordinate . equals3D ( coord ) ) { return true ; } } return false ; } | Check if a coordinate array contains a specific coordinate . |
6,178 | public static Coordinate [ ] getFurthestCoordinate ( Coordinate base , Coordinate [ ] coords ) { double distanceMax = Double . MIN_VALUE ; Coordinate farCoordinate = null ; for ( Coordinate coord : coords ) { double distance = coord . distance ( base ) ; if ( distance > distanceMax ) { distanceMax = distance ; farCoordinate = coord ; } } if ( farCoordinate != null ) { return new Coordinate [ ] { base , farCoordinate } ; } else { return null ; } } | Find the furthest coordinate in a geometry from a base coordinate |
6,179 | public static double length3D ( CoordinateSequence pts ) { int n = pts . size ( ) ; if ( n <= 1 ) { return 0.0 ; } double len = 0.0 ; Coordinate p = new Coordinate ( ) ; pts . getCoordinate ( 0 , p ) ; double x0 = p . x ; double y0 = p . y ; double z0 = p . z ; if ( Double . isNaN ( z0 ) ) { return 0.0 ; } for ( int i = 1 ; i < n ; i ++ ) { pts . getCoordinate ( i , p ) ; double x1 = p . x ; double y1 = p . y ; double z1 = p . z ; if ( Double . isNaN ( z1 ) ) { return 0.0 ; } double dx = x1 - x0 ; double dy = y1 - y0 ; double dz = z1 - z0 ; len += Math . sqrt ( dx * dx + dy * dy + dz * dz ) ; x0 = x1 ; y0 = y1 ; z0 = z1 ; } return len ; } | Computes the length of a linestring specified by a sequence of points . if a coordinate has a NaN z return 0 . |
6,180 | public static double length3D ( Geometry geom ) { double sum = 0 ; for ( int i = 0 ; i < geom . getNumGeometries ( ) ; i ++ ) { Geometry subGeom = geom . getGeometryN ( i ) ; if ( subGeom instanceof Polygon ) { sum += length3D ( ( Polygon ) subGeom ) ; } else if ( subGeom instanceof LineString ) { sum += length3D ( ( LineString ) subGeom ) ; } } return sum ; } | Returns the 3D length of the geometry |
6,181 | public static double length3D ( Polygon polygon ) { double len = 0.0 ; len += length3D ( polygon . getExteriorRing ( ) . getCoordinateSequence ( ) ) ; for ( int i = 0 ; i < polygon . getNumInteriorRing ( ) ; i ++ ) { len += length3D ( polygon . getInteriorRingN ( i ) ) ; } return len ; } | Returns the 3D perimeter of a polygon |
6,182 | public static ValueArray createArray ( int begin , int end , int step ) { if ( end < begin ) { throw new IllegalArgumentException ( "End must be greater or equal to begin" ) ; } int nbClasses = ( int ) ( ( end - begin ) / step ) ; ValueInt [ ] getArray = new ValueInt [ nbClasses ] ; for ( int i = 0 ; i < nbClasses ; i ++ ) { getArray [ i ] = ValueInt . get ( i * step + begin ) ; } return ValueArray . get ( getArray ) ; } | Return an array of integers |
6,183 | public static String mangleURL ( String url ) throws SQLException { if ( url . startsWith ( POSTGIS_H2PROTOCOL ) ) { return POSTGIS_PROTOCOL + url . substring ( POSTGIS_H2PROTOCOL . length ( ) ) ; } else { throw new SQLException ( "Unknown protocol or subprotocol in url " + url ) ; } } | Mangles the PostGIS URL to return the original PostGreSQL URL . |
6,184 | public boolean acceptsURL ( String url ) { try { url = mangleURL ( url ) ; } catch ( SQLException e ) { return false ; } return super . acceptsURL ( url ) ; } | Check whether the driver thinks he can handle the given URL . |
6,185 | public static boolean hasField ( Connection connection , String tableName , String fieldName ) throws SQLException { final Statement statement = connection . createStatement ( ) ; try { final ResultSet resultSet = statement . executeQuery ( "SELECT * FROM " + TableLocation . parse ( tableName ) + " LIMIT 0;" ) ; try { return hasField ( resultSet . getMetaData ( ) , fieldName ) ; } finally { resultSet . close ( ) ; } } catch ( SQLException ex ) { return false ; } finally { statement . close ( ) ; } } | Return true if table tableName contains field fieldName . |
6,186 | public static int getFieldIndex ( ResultSetMetaData resultSetMetaData , String fieldName ) throws SQLException { for ( int columnId = 1 ; columnId <= resultSetMetaData . getColumnCount ( ) ; columnId ++ ) { if ( fieldName . equalsIgnoreCase ( resultSetMetaData . getColumnName ( columnId ) ) ) { return columnId ; } } return - 1 ; } | Fetch the metadata and check field name |
6,187 | public static List < String > getFieldNames ( DatabaseMetaData meta , String table ) throws SQLException { List < String > fieldNameList = new ArrayList < String > ( ) ; TableLocation location = TableLocation . parse ( table ) ; ResultSet rs = meta . getColumns ( location . getCatalog ( null ) , location . getSchema ( null ) , location . getTable ( ) , null ) ; try { while ( rs . next ( ) ) { fieldNameList . add ( rs . getString ( "COLUMN_NAME" ) ) ; } } finally { rs . close ( ) ; } return fieldNameList ; } | Returns the list of all the field name of a table . |
6,188 | public static int getRowCount ( Connection connection , String tableReference ) throws SQLException { Statement st = connection . createStatement ( ) ; int rowCount = 0 ; try { ResultSet rs = st . executeQuery ( String . format ( "select count(*) rowcount from %s" , TableLocation . parse ( tableReference ) ) ) ; try { if ( rs . next ( ) ) { rowCount = rs . getInt ( 1 ) ; } } finally { rs . close ( ) ; } } finally { st . close ( ) ; } return rowCount ; } | Fetch the row count of a table . |
6,189 | public static boolean isTemporaryTable ( Connection connection , String tableReference ) throws SQLException { TableLocation location = TableLocation . parse ( tableReference ) ; ResultSet rs = getTablesView ( connection , location . getCatalog ( ) , location . getSchema ( ) , location . getTable ( ) ) ; boolean isTemporary = false ; try { if ( rs . next ( ) ) { String tableType ; if ( hasField ( rs . getMetaData ( ) , "STORAGE_TYPE" ) ) { tableType = rs . getString ( "STORAGE_TYPE" ) ; } else { tableType = rs . getString ( "TABLE_TYPE" ) ; } isTemporary = tableType . contains ( "TEMPORARY" ) ; } else { throw new SQLException ( "The table " + location + " does not exists" ) ; } } finally { rs . close ( ) ; } return isTemporary ; } | Read INFORMATION_SCHEMA . TABLES in order to see if the provided table reference is a temporary table . |
6,190 | public static boolean isLinkedTable ( Connection connection , String tableReference ) throws SQLException { TableLocation location = TableLocation . parse ( tableReference ) ; ResultSet rs = getTablesView ( connection , location . getCatalog ( ) , location . getSchema ( ) , location . getTable ( ) ) ; boolean isLinked ; try { if ( rs . next ( ) ) { String tableType = rs . getString ( "TABLE_TYPE" ) ; isLinked = tableType . contains ( "TABLE LINK" ) ; } else { throw new SQLException ( "The table " + location + " does not exists" ) ; } } finally { rs . close ( ) ; } return isLinked ; } | Read INFORMATION_SCHEMA . TABLES in order to see if the provided table reference is a linked table . |
6,191 | public static boolean tableExists ( Connection connection , String tableName ) throws SQLException { try ( Statement statement = connection . createStatement ( ) ) { statement . execute ( "SELECT * FROM " + TableLocation . parse ( tableName ) + " LIMIT 0;" ) ; return true ; } catch ( SQLException ex ) { return false ; } } | Return true if the table exists . |
6,192 | public static List < String > getTableNames ( DatabaseMetaData metaData , String catalog , String schemaPattern , String tableNamePattern , String [ ] types ) throws SQLException { List < String > tableList = new ArrayList < String > ( ) ; ResultSet rs = metaData . getTables ( catalog , schemaPattern , tableNamePattern , types ) ; boolean isH2 = isH2DataBase ( metaData ) ; try { while ( rs . next ( ) ) { tableList . add ( new TableLocation ( rs ) . toString ( isH2 ) ) ; } } finally { rs . close ( ) ; } return tableList ; } | Returns the list of table names . |
6,193 | public static List < String > getUniqueFieldValues ( Connection connection , String tableName , String fieldName ) throws SQLException { final Statement statement = connection . createStatement ( ) ; List < String > fieldValues = new ArrayList < String > ( ) ; try { ResultSet result = statement . executeQuery ( "SELECT DISTINCT " + TableLocation . quoteIdentifier ( fieldName ) + " FROM " + TableLocation . parse ( tableName ) ) ; while ( result . next ( ) ) { fieldValues . add ( result . getString ( 1 ) ) ; } } finally { statement . close ( ) ; } return fieldValues ; } | Returns the list of distinct values contained by a field from a table from the database |
6,194 | public static List < String > getFieldNames ( ResultSetMetaData resultSetMetaData ) throws SQLException { List < String > columnNames = new ArrayList < > ( ) ; int cols = resultSetMetaData . getColumnCount ( ) ; for ( int i = 1 ; i <= cols ; i ++ ) { columnNames . add ( resultSetMetaData . getColumnName ( i ) ) ; } return columnNames ; } | Fetch the name of columns |
6,195 | public static void feedTableDataFromHeader ( DbaseFileHeader header , CreateTableData data ) throws IOException { for ( int i = 0 ; i < header . getNumFields ( ) ; i ++ ) { String fieldsName = header . getFieldName ( i ) ; final int type = dbfTypeToH2Type ( header , i ) ; Column column = new Column ( fieldsName . toUpperCase ( ) , type ) ; column . setPrecision ( header . getFieldLength ( i ) ) ; data . columns . add ( column ) ; } } | Parse the DBF file then init the provided data structure |
6,196 | private void prepareToAddBytes ( int numBytes ) throws IOException { if ( buffer . remaining ( ) < numBytes ) { buffer . flip ( ) ; channel . write ( buffer ) ; int bufferCapacity = Math . max ( BUFFER_SIZE , numBytes ) ; if ( bufferCapacity != buffer . capacity ( ) ) { ByteOrder order = buffer . order ( ) ; buffer = ByteBuffer . allocate ( bufferCapacity ) ; buffer . order ( order ) ; } else { buffer . clear ( ) ; } } } | Moves the window |
6,197 | public static MultiPoint createMultiPoint ( Geometry geom ) { if ( geom != null ) { return GEOMETRY_FACTORY . createMultiPoint ( geom . getCoordinates ( ) ) ; } else { return null ; } } | Constructs a MultiPoint from the given geometry s coordinates . |
6,198 | public static void writeTSV ( Connection connection , String fileName , String tableReference , String encoding ) throws SQLException , IOException { TSVDriverFunction tSVDriverFunction = new TSVDriverFunction ( ) ; tSVDriverFunction . exportTable ( connection , tableReference , URIUtilities . fileFromString ( fileName ) , new EmptyProgressVisitor ( ) , encoding ) ; } | Export a table into a Tab - separated values file |
6,199 | public static Polygon makeEllipse ( Point p , double width , double height ) throws SQLException { if ( p == null ) { return null ; } if ( height < 0 || width < 0 ) { throw new SQLException ( "Both width and height must be positive." ) ; } else { GSF . setCentre ( new Coordinate ( p . getX ( ) , p . getY ( ) ) ) ; GSF . setWidth ( width ) ; GSF . setHeight ( height ) ; return GSF . createEllipse ( ) ; } } | Make an ellipse centered at the given point with the given width and height . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.