idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
16,800
public static List < String > getDatabases ( String host , String port , String existingDb , String user , String pwd ) throws Exception { if ( existingDb == null ) { existingDb = "postgres" ; } String url = EDb . POSTGRES . getJdbcPrefix ( ) + host + ":" + port + "/" + existingDb ; try ( Connection connection = DriverManager . getConnection ( url , user , pwd ) ) { String sql = "SELECT datname FROM pg_database WHERE datistemplate = false;" ; List < String > dbs = new ArrayList <> ( ) ; try ( Statement stmt = connection . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( sql ) ) { while ( rs . next ( ) ) { String dbName = rs . getString ( 1 ) ; dbs . add ( dbName ) ; } return dbs ; } } }
Get the list of databases .
199
6
16,801
public static BufferedImage scaleImage ( BufferedImage image , int newSize ) throws Exception { int imageWidth = image . getWidth ( ) ; int imageHeight = image . getHeight ( ) ; int width ; int height ; if ( imageWidth > imageHeight ) { width = newSize ; height = imageHeight * width / imageWidth ; } else { height = newSize ; width = height * imageWidth / imageHeight ; } BufferedImage resizedImage = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g = resizedImage . createGraphics ( ) ; g . drawImage ( image , 0 , 0 , width , height , null ) ; g . dispose ( ) ; return resizedImage ; }
Scale an image to a given size maintaining the ratio .
162
11
16,802
public static BufferedImage imageFromReader ( AbstractGridCoverage2DReader reader , int cols , int rows , double w , double e , double s , double n , CoordinateReferenceSystem resampleCrs ) throws IOException { CoordinateReferenceSystem sourceCrs = reader . getCoordinateReferenceSystem ( ) ; GeneralParameterValue [ ] readParams = new GeneralParameterValue [ 1 ] ; Parameter < GridGeometry2D > readGG = new Parameter < GridGeometry2D > ( AbstractGridFormat . READ_GRIDGEOMETRY2D ) ; GridEnvelope2D gridEnvelope = new GridEnvelope2D ( 0 , 0 , cols , rows ) ; DirectPosition2D minDp = new DirectPosition2D ( sourceCrs , w , s ) ; DirectPosition2D maxDp = new DirectPosition2D ( sourceCrs , e , n ) ; Envelope env = new Envelope2D ( minDp , maxDp ) ; readGG . setValue ( new GridGeometry2D ( gridEnvelope , env ) ) ; readParams [ 0 ] = readGG ; GridCoverage2D gridCoverage2D = reader . read ( readParams ) ; if ( gridCoverage2D == null ) { return null ; } if ( resampleCrs != null ) { gridCoverage2D = ( GridCoverage2D ) Operations . DEFAULT . resample ( gridCoverage2D , resampleCrs ) ; } RenderedImage image = gridCoverage2D . getRenderedImage ( ) ; if ( image instanceof BufferedImage ) { BufferedImage bImage = ( BufferedImage ) image ; return bImage ; } else { ColorModel cm = image . getColorModel ( ) ; int width = image . getWidth ( ) ; int height = image . getHeight ( ) ; WritableRaster raster = cm . createCompatibleWritableRaster ( width , height ) ; boolean isAlphaPremultiplied = cm . isAlphaPremultiplied ( ) ; Hashtable properties = new Hashtable ( ) ; String [ ] keys = image . getPropertyNames ( ) ; if ( keys != null ) { for ( int i = 0 ; i < keys . length ; i ++ ) { properties . put ( keys [ i ] , image . getProperty ( keys [ i ] ) ) ; } } BufferedImage result = new BufferedImage ( cm , raster , isAlphaPremultiplied , properties ) ; image . copyData ( raster ) ; return result ; } }
Read an image from a coverage reader .
561
8
16,803
public static BufferedImage makeColorTransparent ( BufferedImage bufferedImageToProcess , final Color colorToMakeTransparent ) { ImageFilter filter = new RGBImageFilter ( ) { public int markerRGB = colorToMakeTransparent . getRGB ( ) | 0xFF000000 ; public final int filterRGB ( int x , int y , int rgb ) { if ( ( rgb | 0xFF000000 ) == markerRGB ) { // Mark the alpha bits as zero - transparent return 0x00FFFFFF & rgb ; } else { return rgb ; } } } ; ImageProducer ip = new FilteredImageSource ( bufferedImageToProcess . getSource ( ) , filter ) ; Image image = Toolkit . getDefaultToolkit ( ) . createImage ( ip ) ; BufferedImage bufferedImage = new BufferedImage ( image . getWidth ( null ) , image . getHeight ( null ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g2 = bufferedImage . createGraphics ( ) ; g2 . drawImage ( image , 0 , 0 , null ) ; g2 . dispose ( ) ; return bufferedImage ; }
Make a color of the image transparent .
247
8
16,804
public static boolean isAllOneColor ( BufferedImage image ) { int width = image . getWidth ( ) ; int height = image . getHeight ( ) ; int previousRgb = 0 ; boolean isFirst = true ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { int rgb = image . getRGB ( x , y ) ; if ( isFirst ) { isFirst = false ; } else { if ( rgb != previousRgb ) { return false ; } } previousRgb = rgb ; } } return true ; }
Checks if an image is all of one color .
130
11
16,805
public void setParentGroups ( final List < TemplateTokenInfo > tokenInfos ) { // inefficient, perhaps should look into being provided a map of tokenInfos // - keep double itterator for now as // probably irrelevant in the face of speed as a whole for ( final String tokenName : containsString ) { for ( final TemplateTokenInfo tokenInfo : tokenInfos ) { if ( tokenName . equals ( tokenInfo . getName ( ) ) ) { tokenInfo . setParentGroup ( this ) ; break ; } } } }
sets the parent group of all its contained tokens
113
9
16,806
private SimpleFeatureType getCalibrationFeatureType ( CoordinateReferenceSystem crs ) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; ITrentoPType [ ] values = TrentoPFeatureType . PipesTrentoP . values ( ) ; String typeName = values [ 0 ] . getName ( ) ; b . setName ( typeName ) ; b . setCRS ( crs ) ; b . add ( "the_geom" , LineString . class ) ; // create ID attribute. b . add ( values [ 0 ] . getAttributeName ( ) , values [ 0 ] . getClazz ( ) ) ; // create drain area attribute. b . add ( values [ 2 ] . getAttributeName ( ) , values [ 2 ] . getClazz ( ) ) ; // create the percentage area. b . add ( values [ 11 ] . getAttributeName ( ) , values [ 12 ] . getClazz ( ) ) ; // The upstream elevation of the node. b . add ( values [ 3 ] . getAttributeName ( ) , values [ 3 ] . getClazz ( ) ) ; // The downstream elevation of the land. b . add ( values [ 4 ] . getAttributeName ( ) , values [ 4 ] . getClazz ( ) ) ; // runoff coefficent. b . add ( values [ 5 ] . getAttributeName ( ) , values [ 5 ] . getClazz ( ) ) ; // average residence time. b . add ( values [ 6 ] . getAttributeName ( ) , values [ 6 ] . getClazz ( ) ) ; // ks b . add ( values [ 7 ] . getAttributeName ( ) , values [ 7 ] . getClazz ( ) ) ; // average slope b . add ( values [ 10 ] . getAttributeName ( ) , values [ 10 ] . getClazz ( ) ) ; // diameter to verify b . add ( values [ 19 ] . getAttributeName ( ) , values [ 11 ] . getClazz ( ) ) ; return b . buildFeatureType ( ) ; }
Build the Calibration Type .
443
7
16,807
public static String joinByComma ( List < String > items ) { StringBuilder sb = new StringBuilder ( ) ; for ( String item : items ) { sb . append ( "," ) . append ( item ) ; } if ( sb . length ( ) == 0 ) { return "" ; } return sb . substring ( 1 ) ; }
Join a list of strings by comma .
76
8
16,808
public static String joinBySeparator ( List < String > items , String separator ) { int size = items . size ( ) ; if ( size == 0 ) { return "" ; } StringBuilder sb = new StringBuilder ( items . get ( 0 ) ) ; for ( int i = 1 ; i < size ; i ++ ) { sb . append ( separator ) . append ( items . get ( i ) ) ; } return sb . toString ( ) ; }
Join a list of strings by string .
102
8
16,809
public static Polygon createPolygonFromEnvelope ( Envelope env ) { double minX = env . getMinX ( ) ; double minY = env . getMinY ( ) ; double maxY = env . getMaxY ( ) ; double maxX = env . getMaxX ( ) ; Coordinate [ ] c = new Coordinate [ ] { new Coordinate ( minX , minY ) , new Coordinate ( minX , maxY ) , new Coordinate ( maxX , maxY ) , new Coordinate ( maxX , minY ) , new Coordinate ( minX , minY ) } ; return gf ( ) . createPolygon ( c ) ; }
Create a polygon using an envelope .
148
8
16,810
public static Polygon createPolygonFromBounds ( double minX , double minY , double maxX , double maxY ) { Coordinate [ ] c = new Coordinate [ ] { new Coordinate ( minX , minY ) , new Coordinate ( minX , maxY ) , new Coordinate ( maxX , maxY ) , new Coordinate ( maxX , minY ) , new Coordinate ( minX , minY ) } ; return gf ( ) . createPolygon ( c ) ; }
Create a polygon using boundaries .
110
7
16,811
public static String getSelectQuery ( ASpatialDb db , final TableLevel selectedTable , boolean geomFirst ) throws Exception { String tableName = selectedTable . tableName ; String letter = tableName . substring ( 0 , 1 ) ; List < String [ ] > tableColumns = db . getTableColumns ( tableName ) ; GeometryColumn geometryColumns = db . getGeometryColumnsForTable ( tableName ) ; String query = "SELECT " ; if ( geomFirst ) { // first geom List < String > nonGeomCols = new ArrayList < String > ( ) ; for ( int i = 0 ; i < tableColumns . size ( ) ; i ++ ) { String colName = tableColumns . get ( i ) [ 0 ] ; if ( geometryColumns != null && colName . equals ( geometryColumns . geometryColumnName ) ) { colName = letter + "." + colName + " as " + colName ; query += colName ; } else { nonGeomCols . add ( colName ) ; } } // then others for ( int i = 0 ; i < nonGeomCols . size ( ) ; i ++ ) { String colName = tableColumns . get ( i ) [ 0 ] ; query += "," + letter + "." + colName ; } } else { for ( int i = 0 ; i < tableColumns . size ( ) ; i ++ ) { if ( i > 0 ) query += "," ; String colName = tableColumns . get ( i ) [ 0 ] ; if ( geometryColumns != null && colName . equals ( geometryColumns . geometryColumnName ) ) { colName = letter + "." + colName + " as " + colName ; query += colName ; } else { query += letter + "." + colName ; } } } query += " FROM " + tableName + " " + letter ; return query ; }
Get a full select query from a table in the db .
417
12
16,812
public static Map < String , String > queryToMap ( ADb db , String sql , Map < String , String > optionalType ) throws Exception { Map < String , String > map = optionalType ; if ( map == null ) { map = new HashMap <> ( ) ; } Map < String , String > _map = map ; return db . execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( sql ) ) { while ( rs . next ( ) ) { String key = rs . getObject ( 1 ) . toString ( ) ; String value = rs . getObject ( 2 ) . toString ( ) ; _map . put ( key , value ) ; } return _map ; } } ) ; }
Quick method to convert a query to a map .
173
10
16,813
public static Map < String , Geometry > queryToGeomMap ( ADb db , String sql , Map < String , Geometry > optionalType ) throws Exception { Map < String , Geometry > map = optionalType ; if ( map == null ) { map = new HashMap <> ( ) ; } IGeometryParser gp = db . getType ( ) . getGeometryParser ( ) ; Map < String , Geometry > _map = map ; return db . execOnConnection ( connection -> { try ( IHMStatement stmt = connection . createStatement ( ) ; IHMResultSet rs = stmt . executeQuery ( sql ) ) { while ( rs . next ( ) ) { String key = rs . getObject ( 1 ) . toString ( ) ; Geometry geometry = gp . fromResultSet ( rs , 2 ) ; _map . put ( key , geometry ) ; } return _map ; } } ) ; }
Quick method to convert a query to a map with geometry values .
198
13
16,814
public float getFloatValueFromMap ( RandomIter map ) { try { if ( map == null ) { return HMConstants . floatNovalue ; } float value = map . getSampleFloat ( col , row , 0 ) ; return value ; } catch ( Exception e ) { // ignore and return novalue return HMConstants . floatNovalue ; } }
Get the float value of another map in the current node position .
77
13
16,815
public int getIntValueFromMap ( RandomIter map ) { try { if ( map == null ) { return HMConstants . intNovalue ; } int value = map . getSample ( col , row , 0 ) ; return value ; } catch ( Exception e ) { // ignore and return novalue return HMConstants . intNovalue ; } }
Get the int value of another map in the current node position .
76
13
16,816
public double getDoubleValueFromMap ( RandomIter map ) { try { if ( map == null ) { return HMConstants . doubleNovalue ; } double value = map . getSampleDouble ( col , row , 0 ) ; return value ; } catch ( Exception e ) { // ignore and return novalue return HMConstants . doubleNovalue ; } }
Get the double value of another map in the current node position .
77
13
16,817
public void setFloatValueInMap ( WritableRandomIter map , float value ) { if ( map == null ) { return ; } try { map . setSample ( col , row , 0 , value ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Utility method to set the value of a certain map in the current node position .
62
17
16,818
public double getNorth ( ) { Double n = get ( NORTH ) ; if ( n != null ) { return n ; } return HMConstants . doubleNovalue ; }
Getter for the region s north bound .
38
9
16,819
public double getSouth ( ) { Double s = get ( SOUTH ) ; if ( s != null ) { return s ; } return HMConstants . doubleNovalue ; }
Getter for the region s south bound .
38
9
16,820
public double getEast ( ) { Double e = get ( EAST ) ; if ( e != null ) { return e ; } return HMConstants . doubleNovalue ; }
Getter for the region s east bound .
38
9
16,821
public double getWest ( ) { Double w = get ( WEST ) ; if ( w != null ) { return w ; } return HMConstants . doubleNovalue ; }
Getter for the region s west bound .
38
9
16,822
public double getXres ( ) { Double xres = get ( XRES ) ; if ( xres != null ) { return xres ; } return HMConstants . doubleNovalue ; }
Getter for the region s X resolution .
42
9
16,823
public double getYres ( ) { Double yres = get ( YRES ) ; if ( yres != null ) { return yres ; } return HMConstants . doubleNovalue ; }
Getter for the region s Y resolution .
42
9
16,824
public Envelope toEnvelope ( ) { Envelope env = new Envelope ( getWest ( ) , getEast ( ) , getSouth ( ) , getNorth ( ) ) ; return env ; }
Create the envelope of the region borders .
46
8
16,825
public static LinkedHashMap < String , String > getProjectMetadata ( IHMConnection connection ) throws Exception { LinkedHashMap < String , String > metadataMap = new LinkedHashMap <> ( ) ; try ( IHMStatement statement = connection . createStatement ( ) ) { statement . setQueryTimeout ( 30 ) ; // set timeout to 30 sec. String sql = "select " + MetadataTableFields . COLUMN_KEY . getFieldName ( ) + ", " + // MetadataTableFields . COLUMN_VALUE . getFieldName ( ) + " from " + TABLE_METADATA ; IHMResultSet rs = statement . executeQuery ( sql ) ; while ( rs . next ( ) ) { String key = rs . getString ( MetadataTableFields . COLUMN_KEY . getFieldName ( ) ) ; String value = rs . getString ( MetadataTableFields . COLUMN_VALUE . getFieldName ( ) ) ; if ( ! key . endsWith ( "ts" ) ) { metadataMap . put ( key , value ) ; } else { try { long ts = Long . parseLong ( value ) ; String dateTimeString = ETimeUtilities . INSTANCE . TIME_FORMATTER_LOCAL . format ( new Date ( ts ) ) ; metadataMap . put ( key , dateTimeString ) ; } catch ( Exception e ) { metadataMap . put ( key , value ) ; } } } } return metadataMap ; }
Get the map of metadata of the project .
320
9
16,826
public byte [ ] getRL2Image ( Geometry geom , String geomEpsg , int width , int height ) throws Exception { String sql ; String rasterName = getName ( ) ; if ( geomEpsg != null ) { sql = "select GetMapImageFromRaster('" + rasterName + "', ST_Transform(ST_GeomFromText('" + geom . toText ( ) + "', " + geomEpsg + "), " + srid + ") , " + width + " , " + height + ", 'default', 'image/png', '#ffffff', 0, 80, 1 )" ; } else { sql = "select GetMapImageFromRaster('" + rasterName + "', ST_GeomFromText('" + geom . toText ( ) + "') , " + width + " , " + height + ", 'default', 'image/png', '#ffffff', 0, 80, 1 )" ; } return database . execOnConnection ( mConn -> { try ( IHMStatement stmt = mConn . createStatement ( ) ) { IHMResultSet resultSet = stmt . executeQuery ( sql ) ; if ( resultSet . next ( ) ) { byte [ ] bytes = resultSet . getBytes ( 1 ) ; return bytes ; } } return null ; } ) ; }
Extract an image from the database .
301
8
16,827
@ Execute public void process ( ) throws Exception { if ( ! concatOr ( outCb == null , doReset ) ) { return ; } checkNull ( inRaster1 ) ; RenderedImage map1RI = inRaster1 . getRenderedImage ( ) ; RenderedImage map2RI = null ; if ( inRaster2 == null ) { map2RI = map1RI ; } else { map2RI = inRaster2 . getRenderedImage ( ) ; } outCb = new CoupledFieldsMoments ( ) . process ( map1RI , map2RI , pBins , pFirst , pLast , pm , binmode ) ; }
private float base ;
149
4
16,828
public static byte [ ] readFileToBytes ( String filePath ) throws IOException { Path path = Paths . get ( filePath ) ; byte [ ] bytes = Files . readAllBytes ( path ) ; return bytes ; }
Read a file into a byte array .
48
8
16,829
public static String readFile ( File file ) throws IOException { if ( ! file . exists ( ) ) { throw new FileNotFoundException ( "The required projection file is not available: " + file . getAbsolutePath ( ) ) ; } try ( BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ) { StringBuilder sb = new StringBuilder ( 200 ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) ; sb . append ( "\n" ) ; //$NON-NLS-1$ } return sb . toString ( ) ; } }
Read text from a file in one line .
144
9
16,830
public static List < String > readFileToLinesList ( File file ) throws IOException { List < String > lines = new ArrayList <> ( ) ; try ( BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { lines . add ( line ) ; } return lines ; } }
Read text from a file to a list of lines .
87
11
16,831
public static void writeFile ( String text , File file ) throws IOException { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( file ) ) ) { bw . write ( text ) ; } }
Write text to a file in one line .
48
9
16,832
public static File substituteExtention ( File file , String newExtention ) { String path = file . getAbsolutePath ( ) ; int lastDot = path . lastIndexOf ( "." ) ; //$NON-NLS-1$ if ( lastDot == - 1 ) { path = path + "." + newExtention ; //$NON-NLS-1$ } else { path = path . substring ( 0 , lastDot ) + "." + newExtention ; //$NON-NLS-1$ } return new File ( path ) ; }
Substitute the extention of a file .
127
10
16,833
public static String getSafeFileName ( String fileName ) { // not allowed chars in win and linux char [ ] notAllowed = new char [ ] { ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' } ; char escape = ' ' ; int len = fileName . length ( ) ; StringBuilder sb = new StringBuilder ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { char ch = fileName . charAt ( i ) ; boolean trapped = false ; for ( char forbidden : notAllowed ) { if ( ch == forbidden ) { sb . append ( escape ) ; trapped = true ; break ; } } if ( ! trapped ) { sb . append ( ch ) ; } } String newName = sb . toString ( ) ; // no space at end is allowed newName = newName . trim ( ) ; // win doesn't allow dots at the end if ( newName . endsWith ( "." ) ) { newName = newName . substring ( 0 , newName . length ( ) - 1 ) ; } // reserved words for windows String [ ] reservedWindows = { "CON" , "PRN" , "AUX" , "NUL" , "COM1" , "COM2" , "COM3" , "COM4" , "COM5" , "COM6" , "COM7" , "COM8" , "COM9" , "LPT1" , "LPT2" , "LPT3" , "LPT4" , "LPT5" , "LPT6" , "LPT7" , "LPT8" , "LPT9" } ; for ( String reservedWin : reservedWindows ) { if ( newName . equals ( reservedWin ) ) { newName = newName + "_" ; break ; } } return newName ; }
Makes a file name safe to be used .
417
10
16,834
public static File [ ] getFilesListByExtention ( String folderPath , final String ext ) { File [ ] files = new File ( folderPath ) . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ext ) ; } } ) ; return files ; }
Get the list of files in a folder by its extension .
71
12
16,835
public static String getLasFileVersion ( File lasFile ) throws IOException { FileInputStream fis = null ; FileChannel fc = null ; try { fis = new FileInputStream ( lasFile ) ; fc = fis . getChannel ( ) ; // Version Major fis . skip ( 24 ) ; int versionMajor = fis . read ( ) ; // Version Minor int versionMinor = fis . read ( ) ; String version = versionMajor + "." + versionMinor ; //$NON-NLS-1$ return version ; } finally { fc . close ( ) ; fis . close ( ) ; } }
Read just the version bytes from a las file .
136
10
16,836
public static SimpleFeatureBuilder getLasFeatureBuilder ( CoordinateReferenceSystem crs ) { if ( lasSimpleFeatureBuilder == null ) { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "lasdata" ) ; b . setCRS ( crs ) ; b . add ( THE_GEOM , Point . class ) ; b . add ( ID , Integer . class ) ; b . add ( ELEVATION , Double . class ) ; b . add ( INTENSITY , Double . class ) ; b . add ( CLASSIFICATION , Integer . class ) ; b . add ( IMPULSE , Double . class ) ; b . add ( NUM_OF_IMPULSES , Double . class ) ; final SimpleFeatureType featureType = b . buildFeatureType ( ) ; lasSimpleFeatureBuilder = new SimpleFeatureBuilder ( featureType ) ; } return lasSimpleFeatureBuilder ; }
Creates a builder for las data .
196
8
16,837
public static SimpleFeature tofeature ( LasRecord r , Integer featureId , CoordinateReferenceSystem crs ) { final Point point = toGeometry ( r ) ; double elev = r . z ; if ( ! Double . isNaN ( r . groundElevation ) ) { elev = r . groundElevation ; } if ( featureId == null ) { featureId = - 1 ; } final Object [ ] values = new Object [ ] { point , featureId , elev , r . intensity , r . classification , r . returnNumber , r . numberOfReturns } ; SimpleFeatureBuilder lasFeatureBuilder = getLasFeatureBuilder ( crs ) ; lasFeatureBuilder . addAll ( values ) ; final SimpleFeature feature = lasFeatureBuilder . buildFeature ( null ) ; return feature ; }
Convert a record to a feature .
167
8
16,838
public static void dumpLasFolderOverview ( String folder , CoordinateReferenceSystem crs ) throws Exception { SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder ( ) ; b . setName ( "overview" ) ; b . setCRS ( crs ) ; b . add ( "the_geom" , Polygon . class ) ; b . add ( "name" , String . class ) ; SimpleFeatureType type = b . buildFeatureType ( ) ; SimpleFeatureBuilder builder = new SimpleFeatureBuilder ( type ) ; DefaultFeatureCollection newCollection = new DefaultFeatureCollection ( ) ; OmsFileIterator iter = new OmsFileIterator ( ) ; iter . inFolder = folder ; iter . fileFilter = new FileFilter ( ) { public boolean accept ( File pathname ) { return pathname . getName ( ) . endsWith ( ".las" ) ; } } ; iter . process ( ) ; List < File > filesList = iter . filesList ; for ( File file : filesList ) { try ( ALasReader r = new LasReaderBuffered ( file , crs ) ) { r . open ( ) ; ReferencedEnvelope3D envelope = r . getHeader ( ) . getDataEnvelope ( ) ; Polygon polygon = GeometryUtilities . createPolygonFromEnvelope ( envelope ) ; Object [ ] objs = new Object [ ] { polygon , r . getLasFile ( ) . getName ( ) } ; builder . addAll ( objs ) ; SimpleFeature feature = builder . buildFeature ( null ) ; newCollection . add ( feature ) ; } } File folderFile = new File ( folder ) ; File outFile = new File ( folder , "overview_" + folderFile . getName ( ) + ".shp" ) ; OmsVectorWriter . writeVector ( outFile . getAbsolutePath ( ) , newCollection ) ; }
Dump an overview shapefile for a las folder .
406
11
16,839
public static double distance ( LasRecord r1 , LasRecord r2 ) { double distance = NumericsUtilities . pythagoras ( r1 . x - r2 . x , r1 . y - r2 . y ) ; return distance ; }
Projected distance between two points .
55
7
16,840
public static double distance3D ( LasRecord r1 , LasRecord r2 ) { double deltaElev = Math . abs ( r1 . z - r2 . z ) ; double projectedDistance = NumericsUtilities . pythagoras ( r1 . x - r2 . x , r1 . y - r2 . y ) ; double distance = NumericsUtilities . pythagoras ( projectedDistance , deltaElev ) ; return distance ; }
Distance between two points .
100
5
16,841
public static List < Geometry > triangulate ( List < LasRecord > lasPoints , Double elevThres , boolean useGround , IHMProgressMonitor pm ) { pm . beginTask ( "Triangulation..." , - 1 ) ; List < Coordinate > lasCoordinates = new ArrayList < Coordinate > ( ) ; for ( LasRecord lasRecord : lasPoints ) { lasCoordinates . add ( new Coordinate ( lasRecord . x , lasRecord . y , useGround ? lasRecord . groundElevation : lasRecord . z ) ) ; } DelaunayTriangulationBuilder triangulationBuilder = new DelaunayTriangulationBuilder ( ) ; triangulationBuilder . setSites ( lasCoordinates ) ; Geometry triangles = triangulationBuilder . getTriangles ( gf ) ; pm . done ( ) ; ArrayList < Geometry > trianglesList = new ArrayList < Geometry > ( ) ; int numTriangles = triangles . getNumGeometries ( ) ; if ( elevThres == null ) { // no true dsm to be calculated for ( int i = 0 ; i < numTriangles ; i ++ ) { Geometry geometryN = triangles . getGeometryN ( i ) ; trianglesList . add ( geometryN ) ; } } else { double pElevThres = elevThres ; numTriangles = triangles . getNumGeometries ( ) ; pm . beginTask ( "Extracting triangles based on threshold..." , numTriangles ) ; for ( int i = 0 ; i < numTriangles ; i ++ ) { pm . worked ( 1 ) ; Geometry geometryN = triangles . getGeometryN ( i ) ; Coordinate [ ] coordinates = geometryN . getCoordinates ( ) ; double z0 = coordinates [ 0 ] . z ; double z1 = coordinates [ 1 ] . z ; double z2 = coordinates [ 2 ] . z ; double diff1 = abs ( z0 - z1 ) ; if ( diff1 > pElevThres ) { continue ; } double diff2 = abs ( z0 - z2 ) ; if ( diff2 > pElevThres ) { continue ; } double diff3 = abs ( z1 - z2 ) ; if ( diff3 > pElevThres ) { continue ; } trianglesList . add ( geometryN ) ; } pm . done ( ) ; } pm . beginTask ( "Triangulation1..." , - 1 ) ; List < Coordinate > lasCoordinates2 = new ArrayList < Coordinate > ( ) ; for ( Geometry g : trianglesList ) { Coordinate [ ] c = g . getCoordinates ( ) ; lasCoordinates2 . add ( c [ 0 ] ) ; lasCoordinates2 . add ( c [ 1 ] ) ; lasCoordinates2 . add ( c [ 2 ] ) ; } trianglesList . clear ( ) ; DelaunayTriangulationBuilder triangulationBuilder1 = new DelaunayTriangulationBuilder ( ) ; triangulationBuilder1 . setSites ( lasCoordinates2 ) ; Geometry triangles1 = triangulationBuilder1 . getTriangles ( gf ) ; pm . done ( ) ; numTriangles = triangles1 . getNumGeometries ( ) ; // no true dsm to be calculated for ( int i = 0 ; i < numTriangles ; i ++ ) { Geometry geometryN = triangles1 . getGeometryN ( i ) ; trianglesList . add ( geometryN ) ; } return trianglesList ; }
Triangulates a set of las points .
761
9
16,842
@ SuppressWarnings ( "unchecked" ) public static void smoothIDW ( List < LasRecord > lasPoints , boolean useGround , double idwBuffer , IHMProgressMonitor pm ) { List < Coordinate > coordinatesList = new ArrayList < Coordinate > ( ) ; if ( useGround ) { for ( LasRecord dot : lasPoints ) { Coordinate c = new Coordinate ( dot . x , dot . y , dot . groundElevation ) ; coordinatesList . add ( c ) ; } } else { for ( LasRecord dot : lasPoints ) { Coordinate c = new Coordinate ( dot . x , dot . y , dot . z ) ; coordinatesList . add ( c ) ; } } // make triangles tree STRtree pointsTree = new STRtree ( coordinatesList . size ( ) ) ; pm . beginTask ( "Make points tree..." , coordinatesList . size ( ) ) ; for ( Coordinate coord : coordinatesList ) { pointsTree . insert ( new Envelope ( coord ) , coord ) ; pm . worked ( 1 ) ; } pm . done ( ) ; pm . beginTask ( "Interpolate..." , coordinatesList . size ( ) ) ; for ( int i = 0 ; i < coordinatesList . size ( ) ; i ++ ) { Coordinate coord = coordinatesList . get ( i ) ; Envelope env = new Envelope ( coord ) ; env . expandBy ( idwBuffer ) ; List < Coordinate > nearPoints = pointsTree . query ( env ) ; double avg = 0 ; for ( Coordinate coordinate : nearPoints ) { avg += coordinate . z ; } avg = avg / nearPoints . size ( ) ; LasRecord lasRecord = lasPoints . get ( i ) ; if ( useGround ) { lasRecord . groundElevation = avg ; } else { lasRecord . z = avg ; } pm . worked ( 1 ) ; } pm . done ( ) ; }
Smooths a set of las points through the IDW method .
412
14
16,843
public static double [ ] getLastVisiblePointData ( LasRecord baseRecord , List < LasRecord > lasRecords , boolean useGround ) { if ( lasRecords . size ( ) < 1 ) { throw new IllegalArgumentException ( "This needs to have at least 1 point." ) ; } double baseElev = useGround ? baseRecord . groundElevation : baseRecord . z ; Coordinate baseCoord = new Coordinate ( 0 , 0 ) ; double minAzimuthAngle = Double . POSITIVE_INFINITY ; double maxAzimuthAngle = Double . NEGATIVE_INFINITY ; LasRecord minAzimuthPoint = null ; LasRecord maxAzimuthPoint = null ; for ( int i = 0 ; i < lasRecords . size ( ) ; i ++ ) { LasRecord currentPoint = lasRecords . get ( i ) ; double currentElev = useGround ? currentPoint . groundElevation : currentPoint . z ; if ( HMConstants . isNovalue ( currentElev ) ) { continue ; } currentElev = currentElev - baseElev ; double currentProg = LasUtils . distance ( baseRecord , currentPoint ) ; Coordinate currentCoord = new Coordinate ( currentProg , currentElev ) ; double azimuth = GeometryUtilities . azimuth ( baseCoord , currentCoord ) ; if ( azimuth <= minAzimuthAngle ) { minAzimuthAngle = azimuth ; minAzimuthPoint = currentPoint ; } if ( azimuth >= maxAzimuthAngle ) { maxAzimuthAngle = azimuth ; maxAzimuthPoint = currentPoint ; } } if ( minAzimuthPoint == null || maxAzimuthPoint == null ) { return null ; } return new double [ ] { // /* */ useGround ? minAzimuthPoint . groundElevation : minAzimuthPoint . z , // minAzimuthPoint . x , // minAzimuthPoint . y , // LasUtils . distance ( baseRecord , minAzimuthPoint ) , // minAzimuthAngle , // useGround ? maxAzimuthPoint . groundElevation : maxAzimuthPoint . z , // maxAzimuthPoint . x , // maxAzimuthPoint . y , // LasUtils . distance ( baseRecord , maxAzimuthPoint ) , // maxAzimuthAngle , // } ; }
Return last visible point data for a las records points list from a given position .
542
16
16,844
public static String getString ( String key , Object ... params ) { String message = getStringSafely ( key ) ; if ( params != null && params . length > 0 ) { return MessageFormat . format ( message , params ) ; } else { return message ; } }
Applies the message parameters and returns the message from one of the message bundles .
57
16
16,845
private static String getStringSafely ( String key ) { String resource = null ; for ( ResourceBundle bundle : bundles ) { try { resource = bundle . getString ( key ) ; } catch ( MissingResourceException mrex ) { continue ; } return resource ; } return NO_MESSAGE + key ; }
Returns the message from one of the message bundles .
67
10
16,846
@ SuppressWarnings ( "unchecked" ) public ValidationPlanResult execute ( ValidationCheck check , Object target ) throws ValidationEngineException { if ( check == null ) { return validationPlanResult ; } try { check . setEmblEntryValidationPlanProperty ( planProperty ) ; if ( planProperty . enproConnection . get ( ) != null && entryDAOUtils == null ) { entryDAOUtils = new EntryDAOUtilsImpl ( planProperty . enproConnection . get ( ) , true ) ; } check . setEntryDAOUtils ( entryDAOUtils ) ; if ( planProperty . eraproConnection . get ( ) != null && eraproDAOUtils == null ) { eraproDAOUtils = new EraproDAOUtilsImpl ( planProperty . eraproConnection . get ( ) ) ; } check . setEraproDAOUtils ( eraproDAOUtils ) ; } catch ( Exception e ) { throw new ValidationEngineException ( e ) ; } //long start= System.currentTimeMillis(); Class < ? extends ValidationCheck > checkClass = check . getClass ( ) ; ExcludeScope excludeScopeAnnotation = checkClass . getAnnotation ( ExcludeScope . class ) ; RemoteExclude remoteExclude = checkClass . getAnnotation ( RemoteExclude . class ) ; Description descAnnotation = checkClass . getAnnotation ( Description . class ) ; GroupIncludeScope groupIncludeAnnotation = checkClass . getAnnotation ( GroupIncludeScope . class ) ; if ( remoteExclude != null && remote ) { return validationPlanResult ; } if ( excludeScopeAnnotation != null && isInValidationScope ( excludeScopeAnnotation . validationScope ( ) ) ) { return validationPlanResult ; } if ( groupIncludeAnnotation != null && ! isInValidationScopeGroup ( groupIncludeAnnotation . group ( ) ) ) { return validationPlanResult ; } // inject data sets /*if(null != checkDataSetAnnotation) { Stream.of(checkDataSetAnnotation.dataSetNames()).forEach( dsName -> GlobalDataSets.loadIfNotExist(dsName, dataManager, fileManager, devMode)); } */ validationPlanResult . append ( check . check ( target ) ) ; if ( excludeScopeAnnotation != null ) { demoteSeverity ( validationPlanResult , excludeScopeAnnotation . maxSeverity ( ) ) ; } if ( groupIncludeAnnotation != null ) { demoteSeverity ( validationPlanResult , groupIncludeAnnotation . maxSeverity ( ) ) ; } // System.out.println(this.result.count()); return validationPlanResult ; }
Executes a validation check .
594
6
16,847
public static void writeVector ( String path , SimpleFeatureCollection featureCollection ) throws IOException { OmsVectorWriter writer = new OmsVectorWriter ( ) ; writer . file = path ; writer . inVector = featureCollection ; writer . process ( ) ; }
Fast write access mode .
54
5
16,848
public static JSONArray getFormItems ( JSONObject formObj ) throws JSONException { if ( formObj . has ( TAG_FORMITEMS ) ) { JSONArray formItemsArray = formObj . getJSONArray ( TAG_FORMITEMS ) ; return formItemsArray ; } return null ; }
Utility method to get the formitems of a form object .
62
13
16,849
public static List < String > getImageIds ( String formString ) throws Exception { List < String > imageIds = new ArrayList < String > ( ) ; if ( formString != null && formString . length ( ) > 0 ) { JSONObject sectionObject = new JSONObject ( formString ) ; List < String > formsNames = Utilities . getFormNames4Section ( sectionObject ) ; for ( String formName : formsNames ) { JSONObject form4Name = Utilities . getForm4Name ( formName , sectionObject ) ; JSONArray formItems = Utilities . getFormItems ( form4Name ) ; for ( int i = 0 ; i < formItems . length ( ) ; i ++ ) { JSONObject formItem = formItems . getJSONObject ( i ) ; if ( ! formItem . has ( Utilities . TAG_KEY ) ) { continue ; } String type = formItem . getString ( Utilities . TAG_TYPE ) ; String value = "" ; if ( formItem . has ( Utilities . TAG_VALUE ) ) value = formItem . getString ( Utilities . TAG_VALUE ) ; if ( type . equals ( Utilities . TYPE_PICTURES ) ) { if ( value . trim ( ) . length ( ) == 0 ) { continue ; } String [ ] imageSplit = value . split ( ";" ) ; Collections . addAll ( imageIds , imageSplit ) ; } else if ( type . equals ( Utilities . TYPE_MAP ) ) { if ( value . trim ( ) . length ( ) == 0 ) { continue ; } String image = value . trim ( ) ; imageIds . add ( image ) ; } else if ( type . equals ( Utilities . TYPE_SKETCH ) ) { if ( value . trim ( ) . length ( ) == 0 ) { continue ; } String [ ] imageSplit = value . split ( ";" ) ; Collections . addAll ( imageIds , imageSplit ) ; } } } } return imageIds ; }
Get the images paths out of a form string .
420
10
16,850
public static JSONArray formsRootFromSectionsMap ( HashMap < String , JSONObject > sectionsMap ) { JSONArray rootArray = new JSONArray ( ) ; Collection < JSONObject > objects = sectionsMap . values ( ) ; for ( JSONObject jsonObject : objects ) { rootArray . put ( jsonObject ) ; } return rootArray ; }
Create the forms root json object from the map of sections json objects .
74
14
16,851
public String ofCompat ( String compatibilityDataTypeName ) { switch ( compatibilityDataTypeName ) { case COMPAT_TEXT : return TEXT ( ) ; case COMPAT_INT : return INTEGER ( ) ; case COMPAT_LONG : return LONG ( ) ; case COMPAT_REAL : return REAL ( ) ; case COMPAT_BLOB : return BLOB ( ) ; case COMPAT_CLOB : return CLOB ( ) ; } throw new RuntimeException ( "No type for name: " + compatibilityDataTypeName ) ; }
Get the type by its compatibility name .
115
8
16,852
public String ofDbType ( String dbSpecificType ) { if ( dbSpecificType . equals ( TEXT ( ) ) ) { return COMPAT_TEXT ; } else if ( dbSpecificType . equals ( INTEGER ( ) ) ) { return COMPAT_INT ; } else if ( dbSpecificType . equals ( LONG ( ) ) ) { return COMPAT_LONG ; } else if ( dbSpecificType . equals ( REAL ( ) ) ) { return COMPAT_REAL ; } else if ( dbSpecificType . equals ( BLOB ( ) ) ) { return COMPAT_BLOB ; } else if ( dbSpecificType . equals ( CLOB ( ) ) ) { return COMPAT_CLOB ; } throw new RuntimeException ( "No type for name: " + dbSpecificType ) ; }
Get the compatibility name by the db specific type .
170
10
16,853
private BinaryFast thinBinaryRep ( BinaryFast b , int [ ] kernel ) { Point p ; HashSet < Point > inputHashSet = new HashSet < Point > ( ) ; int [ ] [ ] pixels = b . getPixels ( ) ; if ( kernelNo0s ( kernel ) ) { for ( int j = 0 ; j < b . getHeight ( ) ; ++ j ) { for ( int i = 0 ; i < b . getWidth ( ) ; ++ i ) { if ( pixels [ i ] [ j ] == BinaryFast . FOREGROUND ) { inputHashSet . add ( new Point ( i , j ) ) ; } } } } else { Iterator < Point > it = b . getForegroundEdgePixels ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { inputHashSet . add ( it . next ( ) ) ; } } HashSet < Point > result = hitMissHashSet ( b , inputHashSet , kernel ) ; Iterator < Point > it = result . iterator ( ) ; while ( it . hasNext ( ) ) { p = new Point ( it . next ( ) ) ; // make p a background pixel and update the edge sets b . removePixel ( p ) ; b . getForegroundEdgePixels ( ) . remove ( p ) ; b . getBackgroundEdgePixels ( ) . add ( p ) ; // check if new foreground pixels are exposed as edges for ( int j = - 1 ; j < 2 ; ++ j ) { for ( int k = - 1 ; k < 2 ; ++ k ) { if ( p . x + j >= 0 && p . y + k > 0 && p . x + j < b . getWidth ( ) && p . y + k < b . getHeight ( ) && pixels [ p . x + j ] [ p . y + k ] == BinaryFast . FOREGROUND ) { Point p2 = new Point ( p . x + j , p . y + k ) ; b . getForegroundEdgePixels ( ) . add ( p2 ) ; } } } } return b ; }
Takes an image and a kernel and thins it once .
452
13
16,854
public void processSkeleton ( BinaryFast binary , int [ ] [ ] kernel ) { int oldForeEdge = 0 ; int oldBackEdge = 0 ; while ( ! ( binary . getForegroundEdgePixels ( ) . size ( ) == oldForeEdge && binary . getBackgroundEdgePixels ( ) . size ( ) == oldBackEdge ) ) { oldForeEdge = binary . getForegroundEdgePixels ( ) . size ( ) ; oldBackEdge = binary . getBackgroundEdgePixels ( ) . size ( ) ; for ( int i = 0 ; i < kernel . length ; ++ i ) { binary = thinBinaryRep ( binary , kernel [ i ] ) ; binary . generateBackgroundEdgeFromForegroundEdge ( ) ; } } }
Takes an image and a kernel and thins it the specified number of times .
159
17
16,855
private boolean kernelMatch ( Point p , int [ ] [ ] pixels , int w , int h , int [ ] kernel ) { int matched = 0 ; for ( int j = - 1 ; j < 2 ; ++ j ) { for ( int i = - 1 ; i < 2 ; ++ i ) { if ( kernel [ ( ( j + 1 ) * 3 ) + ( i + 1 ) ] == 2 ) { ++ matched ; } else if ( ( p . x + i >= 0 ) && ( p . x + i < w ) && ( p . y + j >= 0 ) && ( p . y + j < h ) && ( ( ( pixels [ p . x + i ] [ p . y + j ] == BinaryFast . FOREGROUND ) && ( kernel [ ( ( j + 1 ) * 3 ) + ( i + 1 ) ] == 1 ) ) || ( ( pixels [ p . x + i ] [ p . y + j ] == BinaryFast . BACKGROUND ) && ( kernel [ ( ( j + 1 ) * 3 ) + ( i + 1 ) ] == 0 ) ) ) ) { ++ matched ; } } } if ( matched == 9 ) { return true ; } else return false ; }
Returns true if the 8 neighbours of p match the kernel 0 is background 1 is foreground 2 is don t care .
259
23
16,856
private HashSet < Point > hitMissHashSet ( BinaryFast b , HashSet < Point > input , int [ ] kernel ) { HashSet < Point > output = new HashSet < Point > ( ) ; Iterator < Point > it = input . iterator ( ) ; while ( it . hasNext ( ) ) { Point p = it . next ( ) ; if ( kernelMatch ( p , b . getPixels ( ) , b . getWidth ( ) , b . getHeight ( ) , kernel ) ) { // System.out.println("Match "+p.x+" "+p.y); output . add ( p ) ; } } // System.out.println(output.size()); return output ; }
Applies the hitmiss operation to a set of pixels stored in a hash table .
152
17
16,857
private boolean kernelNo0s ( int [ ] kernel ) { for ( int i = 0 ; i < kernel . length ; ++ i ) { if ( kernel [ i ] == 0 ) return false ; } return true ; }
Returns true if the kernel has no 0s .
47
10
16,858
public static float [ ] dashFromString ( String dashPattern ) { if ( dashPattern . trim ( ) . length ( ) > 0 ) { String [ ] split = dashPattern . split ( "," ) ; if ( split . length > 1 ) { float [ ] dash = new float [ split . length ] ; for ( int i = 0 ; i < split . length ; i ++ ) { try { float tmpDash = Float . parseFloat ( split [ i ] . trim ( ) ) ; dash [ i ] = tmpDash ; } catch ( NumberFormatException e ) { // GPLog.error("Style", "Can't convert to dash pattern: " + dashPattern, e); return null ; } } return dash ; } } return null ; }
Convert string to dash .
158
6
16,859
public static String dashToString ( float [ ] dash , Float shift ) { StringBuilder sb = new StringBuilder ( ) ; if ( shift != null ) sb . append ( shift ) ; for ( int i = 0 ; i < dash . length ; i ++ ) { if ( shift != null || i > 0 ) { sb . append ( "," ) ; } sb . append ( ( int ) dash [ i ] ) ; } return sb . toString ( ) ; }
Convert a dash array to string .
104
8
16,860
public void clear ( ) { Arrays . fill ( clusters , 0 , bound , null ) ; pairs . clear ( ) ; additions = 0 ; count = 0 ; bound = 0 ; }
Removes all clusters and clustered points but retains the keyer .
39
13
16,861
public void add ( double m , Object pt , K key ) { if ( m == 0.0 ) return ; //nothing to do if ( count < capacity ) { //shortcut //TODO should prefer add if var comes to zero GvmCluster < S , K > cluster = new GvmCluster < S , K > ( this ) ; clusters [ additions ] = cluster ; cluster . set ( m , pt ) ; addPairs ( ) ; cluster . key = keyer . addKey ( cluster , key ) ; count ++ ; bound = count ; } else { //identify cheapest merge GvmClusterPair < S , K > mergePair = pairs . peek ( ) ; double mergeT = mergePair == null ? Double . MAX_VALUE : mergePair . value ; //find cheapest addition GvmCluster < S , K > additionC = null ; double additionT = Double . MAX_VALUE ; for ( int i = 0 ; i < clusters . length ; i ++ ) { GvmCluster < S , K > cluster = clusters [ i ] ; double t = cluster . test ( m , pt ) ; if ( t < additionT ) { additionC = cluster ; additionT = t ; } } if ( additionT <= mergeT ) { //chose addition additionC . add ( m , pt ) ; updatePairs ( additionC ) ; additionC . key = keyer . addKey ( additionC , key ) ; } else { //choose merge GvmCluster < S , K > c1 = mergePair . c1 ; GvmCluster < S , K > c2 = mergePair . c2 ; if ( c1 . m0 < c2 . m0 ) { c1 = c2 ; c2 = mergePair . c1 ; } c1 . key = keyer . mergeKeys ( c1 , c2 ) ; c1 . add ( c2 ) ; updatePairs ( c1 ) ; c2 . set ( m , pt ) ; updatePairs ( c2 ) ; //TODO should this pass through a method on keyer? c2 . key = null ; c2 . key = keyer . addKey ( c2 , key ) ; } } additions ++ ; }
Adds a point to be clustered .
485
7
16,862
private void addPairs ( ) { GvmCluster < S , K > cj = clusters [ count ] ; int c = count - 1 ; //index at which new pairs registered for existing clusters for ( int i = 0 ; i < count ; i ++ ) { GvmCluster < S , K > ci = clusters [ i ] ; GvmClusterPair < S , K > pair = new GvmClusterPair < S , K > ( ci , cj ) ; ci . pairs [ c ] = pair ; cj . pairs [ i ] = pair ; pairs . add ( pair ) ; } }
assumes pairs are contiguous
136
5
16,863
private void updatePairs ( GvmCluster < S , K > cluster ) { GvmClusterPair < S , K > [ ] pairs = cluster . pairs ; //accelerated path if ( count == bound ) { int limit = count - 1 ; for ( int i = 0 ; i < limit ; i ++ ) { this . pairs . reprioritize ( pairs [ i ] ) ; } } else { int limit = bound - 1 ; for ( int i = 0 ; i < limit ; i ++ ) { GvmClusterPair < S , K > pair = pairs [ i ] ; if ( pair . c1 . removed || pair . c2 . removed ) continue ; this . pairs . reprioritize ( pair ) ; } } }
does not assume pairs are contiguous
163
6
16,864
private void removePairs ( GvmCluster < S , K > cluster ) { GvmClusterPair < S , K > [ ] pairs = cluster . pairs ; for ( int i = 0 ; i < bound - 1 ; i ++ ) { GvmClusterPair < S , K > pair = pairs [ i ] ; if ( pair . c1 . removed || pair . c2 . removed ) continue ; this . pairs . remove ( pair ) ; } }
these are tidied when everything is made contiguous again
101
10
16,865
public void open ( String filename , int mode ) throws jsqlite . Exception { this . filename = filename ; if ( ( mode & 0200 ) != 0 ) { mode = jsqlite . Constants . SQLITE_OPEN_READWRITE | jsqlite . Constants . SQLITE_OPEN_CREATE ; } else if ( ( mode & 0400 ) != 0 ) { mode = jsqlite . Constants . SQLITE_OPEN_READONLY ; } synchronized ( this ) { try { _open4 ( filename , mode , null , false ) ; } catch ( Exception | OutOfMemoryError se ) { throw se ; } catch ( Throwable t ) { _open ( filename , mode ) ; } } }
Open an SQLite database file .
158
7
16,866
public void create_function ( String name , int nargs , Function f ) { synchronized ( this ) { _create_function ( name , nargs , f ) ; } }
Create regular function .
37
4
16,867
public void create_aggregate ( String name , int nargs , Function f ) { synchronized ( this ) { _create_aggregate ( name , nargs , f ) ; } }
Create aggregate function .
39
4
16,868
public Backup backup ( Database dest , String destName , String srcName ) throws jsqlite . Exception { synchronized ( this ) { Backup b = new Backup ( ) ; _backup ( b , dest , destName , this , srcName ) ; return b ; } }
Initiate a database backup SQLite 3 . x only .
57
13
16,869
public Vm compile ( String sql ) throws jsqlite . Exception { synchronized ( this ) { Vm vm = new Vm ( ) ; vm_compile ( sql , vm ) ; return vm ; } }
Compile and return SQLite VM for SQL statement . Only available in SQLite 2 . 8 . 0 and above otherwise a no - op .
45
29
16,870
public Vm compile ( String sql , String args [ ] ) throws jsqlite . Exception { synchronized ( this ) { Vm vm = new Vm ( ) ; vm_compile_args ( sql , vm , args ) ; return vm ; } }
Compile and return SQLite VM for SQL statement . Only available in SQLite 3 . 0 and above otherwise a no - op .
54
27
16,871
public Stmt prepare ( String sql ) throws jsqlite . Exception { synchronized ( this ) { Stmt stmt = new Stmt ( ) ; stmt_prepare ( sql , stmt ) ; return stmt ; } }
Prepare and return SQLite3 statement for SQL . Only available in SQLite 3 . 0 and above otherwise a no - op .
49
27
16,872
public Blob open_blob ( String db , String table , String column , long row , boolean rw ) throws jsqlite . Exception { synchronized ( this ) { Blob blob = new Blob ( ) ; _open_blob ( db , table , column , row , rw , blob ) ; return blob ; } }
Open an SQLite3 blob . Only available in SQLite 3 . 4 . 0 and above .
71
20
16,873
public static long long_from_julian ( String s ) throws jsqlite . Exception { try { double d = Double . valueOf ( s ) . doubleValue ( ) ; return long_from_julian ( d ) ; } catch ( java . lang . Exception ee ) { throw new jsqlite . Exception ( "not a julian date: " + s + ": " + ee ) ; } }
Make long value from julian date for java . lang . Date
93
14
16,874
public void clear ( ) { column = new String [ 0 ] ; types = null ; rows = new Vector ( ) ; ncolumns = nrows = 0 ; atmaxrows = false ; }
Clear result set .
41
4
16,875
public boolean newrow ( String rowdata [ ] ) { if ( rowdata != null ) { if ( maxrows > 0 && nrows >= maxrows ) { atmaxrows = true ; return true ; } rows . addElement ( rowdata ) ; nrows ++ ; } return false ; }
Callback method used while the query is executed .
62
9
16,876
public ColumnVector solve ( ColumnVector b , boolean improve ) throws MatrixException { // Validate b's size. if ( b . nRows != nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } decompose ( ) ; // Solve Ly = b for y by forward substitution. // Solve Ux = y for x by back substitution. ColumnVector y = forwardSubstitution ( b ) ; ColumnVector x = backSubstitution ( y ) ; // Improve and return x. if ( improve ) improve ( b , x ) ; return x ; }
Solve Ax = b for x using the Gaussian elimination algorithm .
130
14
16,877
private void forwardElimination ( double scales [ ] ) throws MatrixException { // Loop once per pivot row 0..nRows-1. for ( int rPivot = 0 ; rPivot < nRows - 1 ; ++ rPivot ) { double largestScaledElmt = 0 ; int rLargest = 0 ; // Starting from the pivot row rPivot, look down // column rPivot to find the largest scaled element. for ( int r = rPivot ; r < nRows ; ++ r ) { // Use the permuted row index. int pr = permutation [ r ] ; double absElmt = Math . abs ( LU . at ( pr , rPivot ) ) ; double scaledElmt = absElmt * scales [ pr ] ; if ( largestScaledElmt < scaledElmt ) { // The largest scaled element and // its row index. largestScaledElmt = scaledElmt ; rLargest = r ; } } // Is the matrix singular? if ( largestScaledElmt == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } // Exchange rows if necessary to choose the best // pivot element by making its row the pivot row. if ( rLargest != rPivot ) { int temp = permutation [ rPivot ] ; permutation [ rPivot ] = permutation [ rLargest ] ; permutation [ rLargest ] = temp ; ++ exchangeCount ; } // Use the permuted pivot row index. int prPivot = permutation [ rPivot ] ; double pivotElmt = LU . at ( prPivot , rPivot ) ; // Do the elimination below the pivot row. for ( int r = rPivot + 1 ; r < nRows ; ++ r ) { // Use the permuted row index. int pr = permutation [ r ] ; double multiple = LU . at ( pr , rPivot ) / pivotElmt ; // Set the multiple into matrix L. LU . set ( pr , rPivot , multiple ) ; // Eliminate an unknown from matrix U. if ( multiple != 0 ) { for ( int c = rPivot + 1 ; c < nCols ; ++ c ) { double elmt = LU . at ( pr , c ) ; // Subtract the multiple of the pivot row. elmt -= multiple * LU . at ( prPivot , c ) ; LU . set ( pr , c , elmt ) ; } } } } }
Do forward elimination with scaled partial row pivoting .
537
10
16,878
private ColumnVector forwardSubstitution ( ColumnVector b ) throws MatrixException { ColumnVector y = new ColumnVector ( nRows ) ; // Do forward substitution. for ( int r = 0 ; r < nRows ; ++ r ) { int pr = permutation [ r ] ; // permuted row index double dot = 0 ; for ( int c = 0 ; c < r ; ++ c ) { dot += LU . at ( pr , c ) * y . at ( c ) ; } y . set ( r , b . at ( pr ) - dot ) ; } return y ; }
Solve Ly = b for y by forward substitution .
125
11
16,879
private ColumnVector backSubstitution ( ColumnVector y ) throws MatrixException { ColumnVector x = new ColumnVector ( nRows ) ; // Do back substitution. for ( int r = nRows - 1 ; r >= 0 ; -- r ) { int pr = permutation [ r ] ; // permuted row index double dot = 0 ; for ( int c = r + 1 ; c < nRows ; ++ c ) { dot += LU . at ( pr , c ) * x . at ( c ) ; } x . set ( r , ( y . at ( r ) - dot ) / LU . at ( pr , r ) ) ; } return x ; }
Solve Ux = y for x by back substitution .
142
12
16,880
private void improve ( ColumnVector b , ColumnVector x ) throws MatrixException { // Find the largest x element. double largestX = 0 ; for ( int r = 0 ; r < nRows ; ++ r ) { double absX = Math . abs ( x . values [ r ] [ 0 ] ) ; if ( largestX < absX ) largestX = absX ; } // Is x already as good as possible? if ( largestX == 0 ) return ; ColumnVector residuals = new ColumnVector ( nRows ) ; // Iterate to improve x. for ( int iter = 0 ; iter < MAX_ITER ; ++ iter ) { // Compute residuals = b - Ax. // Must use double precision! for ( int r = 0 ; r < nRows ; ++ r ) { double dot = 0 ; double row [ ] = values [ r ] ; for ( int c = 0 ; c < nRows ; ++ c ) { double elmt = at ( r , c ) ; dot += elmt * x . at ( c ) ; // dbl.prec. * } double value = b . at ( r ) - dot ; // dbl.prec. - residuals . set ( r , ( double ) value ) ; } // Solve Az = residuals for z. ColumnVector z = solve ( residuals , false ) ; // Set x = x + z. // Find largest the largest difference. double largestDiff = 0 ; for ( int r = 0 ; r < nRows ; ++ r ) { double oldX = x . at ( r ) ; x . set ( r , oldX + z . at ( r ) ) ; double diff = Math . abs ( x . at ( r ) - oldX ) ; if ( largestDiff < diff ) largestDiff = diff ; } // Is any further improvement possible? if ( largestDiff < largestX * TOLERANCE ) return ; } // Failed to converge because A is nearly singular. throw new MatrixException ( MatrixException . NO_CONVERGENCE ) ; }
Iteratively improve the solution x to machine accuracy .
437
10
16,881
void addFillComponents ( Container panel , int [ ] cols , int [ ] rows ) { Dimension filler = new Dimension ( 10 , 10 ) ; boolean filled_cell_11 = false ; CellConstraints cc = new CellConstraints ( ) ; if ( cols . length > 0 && rows . length > 0 ) { if ( cols [ 0 ] == 1 && rows [ 0 ] == 1 ) { /** add a rigid area */ panel . add ( Box . createRigidArea ( filler ) , cc . xy ( 1 , 1 ) ) ; filled_cell_11 = true ; } } for ( int index = 0 ; index < cols . length ; index ++ ) { if ( cols [ index ] == 1 && filled_cell_11 ) { continue ; } panel . add ( Box . createRigidArea ( filler ) , cc . xy ( cols [ index ] , 1 ) ) ; } for ( int index = 0 ; index < rows . length ; index ++ ) { if ( rows [ index ] == 1 && filled_cell_11 ) { continue ; } panel . add ( Box . createRigidArea ( filler ) , cc . xy ( 1 , rows [ index ] ) ) ; } }
Adds fill components to empty cells in the first row and first column of the grid . This ensures that the grid spacing will be the same as shown in the designer .
267
33
16,882
public ImageIcon loadImage ( String imageName ) { try { ClassLoader classloader = getClass ( ) . getClassLoader ( ) ; java . net . URL url = classloader . getResource ( imageName ) ; if ( url != null ) { ImageIcon icon = new ImageIcon ( url ) ; return icon ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } throw new IllegalArgumentException ( "Unable to load image: " + imageName ) ; }
Helper method to load an image file from the CLASSPATH
106
13
16,883
public synchronized Class < ? > compileSource ( String name , String code ) throws Exception { Class < ? > c = cache . get ( name ) ; if ( c == null ) { c = compileSource0 ( name , code ) ; cache . put ( name , c ) ; } return c ; }
Compiles a single source file and loads the class with a default class loader . The default class loader is the one used to load the test case class .
63
31
16,884
private Class < ? > compileSource0 ( String className , String sourceCode ) throws Exception { List < MemorySourceJavaFileObject > compUnits = new ArrayList < MemorySourceJavaFileObject > ( 1 ) ; compUnits . add ( new MemorySourceJavaFileObject ( className + ".java" , sourceCode ) ) ; DiagnosticCollector < JavaFileObject > diag = new DiagnosticCollector < JavaFileObject > ( ) ; Boolean result = compiler . getTask ( null , fileManager , diag , compilerOptions , null , compUnits ) . call ( ) ; if ( result . equals ( Boolean . FALSE ) ) { throw new RuntimeException ( diag . getDiagnostics ( ) . toString ( ) ) ; } try { String classDotName = className . replace ( ' ' , ' ' ) ; return Class . forName ( classDotName , true , loader ) ; } catch ( ClassNotFoundException e ) { throw e ; } }
Compiles multiple sources file and loads the classes .
211
10
16,885
public void setValue ( int position , double value ) { if ( position >= internalArray . length ) { double [ ] newArray = new double [ position + growingSize ] ; System . arraycopy ( internalArray , 0 , newArray , 0 , internalArray . length ) ; internalArray = newArray ; } internalArray [ position ] = value ; lastIndex = max ( lastIndex , position ) ; }
Safe set the value in a certain position .
85
9
16,886
public double [ ] getTrimmedInternalArray ( ) { if ( internalArray . length == lastIndex + 1 ) { return internalArray ; } double [ ] newArray = new double [ lastIndex + 1 ] ; System . arraycopy ( internalArray , 0 , newArray , 0 , newArray . length ) ; return newArray ; }
Get a trimmed version of the array i . e . without ending unset positions .
72
17
16,887
public byte [ ] getColor ( float cat ) { /* First check to see if the category * value is within the range of this rule. */ float diff = cat - low ; if ( diff <= 0f ) return catColor ; // else if (diff < 0) // { // /* Category value below lowest value in this rule. */ // return new byte[]{(byte)catColor[0], (byte)catColor[1], // (byte)catColor[2], (byte)catColor[3]}; // } else if ( diff > range ) { return new byte [ ] { ( byte ) ( ( int ) ( rmul * range ) + ( int ) catColor [ 0 ] ) , ( byte ) ( ( int ) ( gmul * range ) + ( int ) catColor [ 1 ] ) , ( byte ) ( ( int ) ( bmul * range ) + ( int ) catColor [ 2 ] ) , ( byte ) catColor [ 3 ] } ; } /* Calculate the color from the gradient */ return new byte [ ] { ( byte ) ( ( int ) ( rmul * diff ) + ( int ) catColor [ 0 ] ) , ( byte ) ( ( int ) ( gmul * diff ) + ( int ) catColor [ 1 ] ) , ( byte ) ( ( int ) ( bmul * diff ) + ( int ) catColor [ 2 ] ) , ( byte ) catColor [ 3 ] } ; }
Return the colour tupple for specified category value
311
10
16,888
private String [ ] getExpectedRow ( TableIterator < String [ ] > tableRowIterator , DateTime expectedDT ) throws IOException { while ( tableRowIterator . hasNext ( ) ) { String [ ] row = tableRowIterator . next ( ) ; DateTime currentTimestamp = formatter . parseDateTime ( row [ 1 ] ) ; if ( currentTimestamp . equals ( expectedDT ) ) { if ( pNum == 1 ) { return row ; } else { String [ ] [ ] allRows = new String [ pNum ] [ ] ; allRows [ 0 ] = row ; int rowNum = 1 ; for ( int i = 1 ; i < pNum ; i ++ ) { if ( tableRowIterator . hasNext ( ) ) { String [ ] nextRow = tableRowIterator . next ( ) ; allRows [ i ] = nextRow ; rowNum ++ ; } } // now aggregate String [ ] aggregatedRow = new String [ row . length ] ; // date is the one of the first instant aggregatedRow [ 0 ] = allRows [ 0 ] [ 0 ] ; aggregatedRow [ 1 ] = allRows [ 0 ] [ 1 ] ; for ( int col = 2 ; col < allRows [ 0 ] . length ; col ++ ) { boolean hasOne = false ; switch ( pAggregation ) { case 0 : double sum = 0 ; for ( int j = 0 ; j < rowNum ; j ++ ) { String valueStr = allRows [ j ] [ col ] ; if ( ! valueStr . equals ( fileNovalue ) ) { double value = Double . parseDouble ( valueStr ) ; sum = sum + value ; hasOne = true ; } } if ( ! hasOne ) { sum = doubleNovalue ; } aggregatedRow [ col ] = String . valueOf ( sum ) ; break ; case 1 : double avg = 0 ; for ( int j = 0 ; j < rowNum ; j ++ ) { String valueStr = allRows [ j ] [ col ] ; if ( ! valueStr . equals ( fileNovalue ) ) { double value = Double . parseDouble ( valueStr ) ; avg = avg + value ; hasOne = true ; } } if ( ! hasOne ) { avg = doubleNovalue ; } else { avg = avg / pNum ; } aggregatedRow [ col ] = String . valueOf ( avg ) ; break ; default : break ; } } return aggregatedRow ; } } else if ( currentTimestamp . isBefore ( expectedDT ) ) { // browse until the instant is found continue ; } else if ( currentTimestamp . isAfter ( expectedDT ) ) { /* * lost the moment, for now throw exception. * Could be enhanced in future. */ String message = "The data are not aligned with the simulation interval (" + currentTimestamp + "/" + expectedDT + "). Check your data file: " + file ; throw new IOException ( message ) ; } } return null ; }
Get the needed datarow from the table .
639
10
16,889
@ SuppressWarnings ( "unchecked" ) @ Execute public void process ( ) throws Exception { checkNull ( inVector , pMaxOverlap , inRaster ) ; RandomIter rasterIter = CoverageUtilities . getRandomIterator ( inRaster ) ; GridGeometry2D gridGeometry = inRaster . getGridGeometry ( ) ; double [ ] tm_utm_tac = new double [ 3 ] ; STRtree circlesTree = FeatureUtilities . featureCollectionToSTRtree ( inVector ) ; List < SimpleFeature > circlesList = FeatureUtilities . featureCollectionToList ( inVector ) ; DefaultFeatureCollection outFC = new DefaultFeatureCollection ( ) ; for ( SimpleFeature circleFeature : circlesList ) { Geometry geometry = ( Geometry ) circleFeature . getDefaultGeometry ( ) ; Polygon circle = ( Polygon ) geometry . getGeometryN ( 0 ) ; PreparedGeometry preparedCircle = PreparedGeometryFactory . prepare ( circle ) ; List < SimpleFeature > circlesAround = circlesTree . query ( circle . getEnvelopeInternal ( ) ) ; List < Geometry > intersectedCircles = new ArrayList < Geometry > ( ) ; for ( SimpleFeature circleAround : circlesAround ) { if ( circleAround . equals ( circleFeature ) ) { continue ; } Geometry circleAroundGeometry = ( Geometry ) circleAround . getDefaultGeometry ( ) ; if ( preparedCircle . intersects ( circleAroundGeometry ) ) { intersectedCircles . add ( circleAroundGeometry ) ; } } Point centroid = circle . getCentroid ( ) ; int intersectionsCount = intersectedCircles . size ( ) ; if ( intersectionsCount != 0 ) { // check how many circles overlapped if ( intersectionsCount > pMaxOverlapCount ) { continue ; } // check if the circles overlap too much, i.e. cover their baricenter boolean intersected = false ; for ( Geometry intersectedCircle : intersectedCircles ) { if ( intersectedCircle . intersects ( centroid ) ) { intersected = true ; break ; } } if ( intersected ) { continue ; } } // check if the center has a raster value, i.e. is not empty double value = CoverageUtilities . getValue ( inRaster , centroid . getCoordinate ( ) ) ; if ( ! HMConstants . isNovalue ( value ) ) { continue ; } // check if the inner part of the circle is indeed rather empty // min, max, mean, var, sdev, activeCellCount, passiveCellCount double [ ] stats = OmsZonalStats . polygonStats ( circle , gridGeometry , rasterIter , false , tm_utm_tac , 0 , pm ) ; // if we have many more active cells than passive cells, that is not a circle double activeCells = stats [ 5 ] ; double novalues = stats [ 6 ] ; if ( activeCells * 1.5 > novalues ) { continue ; } // take it as valid circle outFC . add ( circleFeature ) ; } outCircles = outFC ; rasterIter . done ( ) ; }
VARS DESCR END
687
5
16,890
private static byte [ ] byteCopy ( byte [ ] source , int offset , int count , byte [ ] target ) { for ( int i = offset , j = 0 ; i < offset + count ; i ++ , j ++ ) { target [ j ] = source [ i ] ; } return target ; }
Copies count elements from source starting at element with index offset to the given target .
64
17
16,891
public static String encodeX ( byte [ ] a ) { // check input if ( a == null || a . length == 0 ) { return "X''" ; } char [ ] out = new char [ a . length * 2 + 3 ] ; int i = 2 ; for ( int j = 0 ; j < a . length ; j ++ ) { out [ i ++ ] = xdigits [ ( a [ j ] >> 4 ) & 0x0F ] ; out [ i ++ ] = xdigits [ a [ j ] & 0x0F ] ; } out [ 0 ] = ' ' ; out [ 1 ] = ' ' ; out [ i ] = ' ' ; return new String ( out ) ; }
Encodes the given byte array into SQLite3 blob notation ie X ..
153
15
16,892
public double [ ] [ ] getWindow ( int size , boolean doCircular ) { if ( size % 2 == 0 ) { size ++ ; } double [ ] [ ] window = new double [ size ] [ size ] ; int delta = ( size - 1 ) / 2 ; if ( ! doCircular ) { for ( int c = - delta ; c <= delta ; c ++ ) { int tmpCol = col + c ; for ( int r = - delta ; r <= delta ; r ++ ) { int tmpRow = row + r ; GridNode n = new GridNode ( gridIter , cols , rows , xRes , yRes , tmpCol , tmpRow ) ; window [ r + delta ] [ c + delta ] = n . elevation ; } } } else { double radius = delta ; // rows + half cell for ( int c = - delta ; c <= delta ; c ++ ) { int tmpCol = col + c ; for ( int r = - delta ; r <= delta ; r ++ ) { int tmpRow = row + r ; double distance = sqrt ( c * c + r * r ) ; if ( distance <= radius ) { GridNode n = new GridNode ( gridIter , cols , rows , xRes , yRes , tmpCol , tmpRow ) ; window [ r + delta ] [ c + delta ] = n . elevation ; } else { window [ r + delta ] [ c + delta ] = doubleNovalue ; } } } } return window ; }
Get a window of values surrounding the current node .
317
10
16,893
public double getElevationAt ( Direction direction ) { switch ( direction ) { case E : return eElev ; case W : return wElev ; case N : return nElev ; case S : return sElev ; case EN : return enElev ; case NW : return nwElev ; case WS : return wsElev ; case SE : return seElev ; default : throw new IllegalArgumentException ( ) ; } }
Get the value of the elevation in one of the surrounding direction .
96
13
16,894
public int getFlow ( ) { GridNode nextDown = goDownstreamSP ( ) ; if ( nextDown == null ) { return HMConstants . intNovalue ; } int dcol = nextDown . col - col ; int drow = nextDown . row - row ; Direction dir = Direction . getDir ( dcol , drow ) ; return dir . getFlow ( ) ; }
Get the flow value of this node based in the steepest path .
84
14
16,895
public GridNode getNodeAt ( Direction direction ) { int newCol = col + direction . col ; int newRow = row + direction . row ; GridNode node = new GridNode ( gridIter , cols , rows , xRes , yRes , newCol , newRow ) ; return node ; }
Get a neighbor node at a certain direction .
64
9
16,896
public Direction isNeighborOf ( GridNode otherNode ) { Direction [ ] orderedDirs = Direction . getOrderedDirs ( ) ; for ( int i = 0 ; i < orderedDirs . length ; i ++ ) { Direction direction = orderedDirs [ i ] ; int newCol = col + direction . col ; int newRow = row + direction . row ; if ( otherNode . col == newCol && otherNode . row == newRow ) { return direction ; } } return null ; }
Checks if the supplied node is adjacent to the current .
107
12
16,897
public Direction isSameValueNeighborOf ( GridNode otherNode ) { Direction direction = isNeighborOf ( otherNode ) ; if ( direction != null && NumericsUtilities . dEq ( elevation , otherNode . elevation ) ) { return direction ; } return null ; }
Checks if the supplied node is adjacent to the current and has the same value .
60
17
16,898
public double getSlopeTo ( GridNode node ) { double slope = ( elevation - node . elevation ) / getDistance ( node ) ; return slope ; }
Calculates the slope from the current to the supplied point .
33
13
16,899
protected static String getXmlEncoding ( Reader reader ) { try { StringWriter sw = new StringWriter ( MAX_XMLDECL_SIZE ) ; int c ; int count = 0 ; for ( ; ( 6 > count ) && ( - 1 != ( c = reader . read ( ) ) ) ; count ++ ) { sw . write ( c ) ; } /* * Hmm, checking for the case when there is no XML declaration and * document begins with processing instruction whose target name * starts with "<?xml" ("<?xmlfoo"). Sounds like a nearly impossible * thing, but Xerces guys are checking for that somewhere in the * depths of their code :) */ if ( ( 6 > count ) || ( ! "<?xml " . equals ( sw . toString ( ) ) ) ) { if ( LOGGER . isLoggable ( Level . FINER ) ) { LOGGER . finer ( "Invalid(?) XML declaration: " + sw . toString ( ) + "." ) ; } return null ; } /* * Continuing reading declaration(?) til the first '>' ('\u003E') * encountered. Conversion from `int` to `char` should be safe * for our purposes, at least I'm not expecting any extended * (0x10000+) characters in xml declaration. I also limited * the total number of chars read this way to prevent any * malformed (no '>') input potentially forcing us to read * megabytes of useless data :) */ for ( ; ( MAX_XMLDECL_SIZE > count ) && ( - 1 != ( c = reader . read ( ) ) ) && ( RIGHT_ANGLE_BRACKET != ( char ) c ) ; count ++ ) { sw . write ( c ) ; } Matcher m = ENCODING_PATTERN . matcher ( sw . toString ( ) ) ; if ( m . find ( ) ) { String result = m . group ( 1 ) ; return result ; } else { return null ; } } catch ( IOException e ) { if ( LOGGER . isLoggable ( Level . WARNING ) ) { LOGGER . warning ( "Failed to extract charset info from XML " + "declaration due to IOException: " + e . getMessage ( ) ) ; } return null ; } }
Gets the encoding of the xml request made to the dispatcher . This works by reading the temp file where we are storing the request looking to match the header specified encoding that should be present on all xml files . This call should only be made after the temp file has been set . If no encoding is found or if an IOError is encountered then null shall be returned .
487
74