idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
23,400
public static InputStream getCommandResult ( CommandLine cmdLine , File dir , int expectedExit , long timeout , InputStream input ) throws IOException { DefaultExecutor executor = getDefaultExecutor ( dir , expectedExit , timeout ) ; try ( ByteArrayOutputStream outStr = new ByteArrayOutputStream ( ) ) { executor . setStreamHandler ( new PumpStreamHandler ( outStr , outStr , input ) ) ; try { execute ( cmdLine , dir , executor , null ) ; return new ByteArrayInputStream ( outStr . toByteArray ( ) ) ; } catch ( IOException e ) { log . warning ( "Had output before error: " + new String ( outStr . toByteArray ( ) ) ) ; throw new IOException ( e ) ; } } }
Run the given commandline in the given directory and provide the given input to the command . Also verify that the tool has the expected exit code and does finish in the timeout .
167
35
23,401
public IMetaEntry deserializeEntry ( final DataInput pData ) throws TTIOException { try { final int kind = pData . readInt ( ) ; switch ( kind ) { case KEY : return new MetaKey ( pData . readInt ( ) ) ; case VALUE : final int valSize = pData . readInt ( ) ; final byte [ ] bytes = new byte [ valSize ] ; pData . readFully ( bytes ) ; return new MetaValue ( new String ( bytes ) ) ; default : throw new IllegalStateException ( "Kind not defined." ) ; } } catch ( final IOException exc ) { throw new TTIOException ( exc ) ; } }
Create a meta - entry out of a serialized byte - representation .
144
14
23,402
public static boolean isZip ( String fileName ) { if ( fileName == null ) { return false ; } String tl = fileName . toLowerCase ( ) ; for ( String element : ZIP_EXTENSIONS ) { if ( tl . endsWith ( element ) ) { return true ; } } return false ; }
Determines if the file has an extension known to be a ZIP file currently this includes . zip . jar . war . ear . aar
69
29
23,403
public static void findZip ( String zipName , InputStream zipInput , FileFilter searchFilter , List < String > results ) throws IOException { ZipInputStream zin = new ZipInputStream ( zipInput ) ; while ( true ) { final ZipEntry en ; try { en = zin . getNextEntry ( ) ; } catch ( IOException | IllegalArgumentException e ) { throw new IOException ( "While handling file " + zipName , e ) ; } if ( en == null ) { break ; } if ( searchFilter . accept ( new File ( en . getName ( ) ) ) ) { results . add ( zipName + ZIP_DELIMITER + en ) ; } if ( ZipUtils . isZip ( en . getName ( ) ) ) { findZip ( zipName + ZIP_DELIMITER + en , zin , searchFilter , results ) ; } } }
Looks in the ZIP file available via zipInput for files matching the provided file - filter recursing into sub - ZIP files .
194
26
23,404
@ SuppressWarnings ( "resource" ) public static InputStream getZipContentsRecursive ( final String file ) throws IOException { // return local file directly int pos = file . indexOf ( ' ' ) ; if ( pos == - 1 ) { if ( ! new File ( file ) . exists ( ) ) { throw new IOException ( "File " + file + " does not exist" ) ; } try { return new FileInputStream ( file ) ; } catch ( IOException e ) { // filter out locked errors if ( e . getMessage ( ) . contains ( "because another process has locked" ) ) { logger . warning ( "Could not read file: " + file + " because it is locked." ) ; return new ByteArrayInputStream ( new byte [ ] { } ) ; } throw e ; } } String zip = file . substring ( 0 , pos ) ; String subfile = file . substring ( pos + 1 ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Trying to read zipfile: " + zip + " subfile: " + subfile ) ; } // open original zip if ( ! new File ( zip ) . exists ( ) || ! new File ( zip ) . isFile ( ) || ! new File ( zip ) . canRead ( ) || new File ( zip ) . length ( ) == 0 ) { throw new IOException ( "ZIP file: " + zip + " does not exist or is empty or not a readable file." ) ; } ZipFile zipfile = new ZipFile ( zip ) ; // is the target file in yet another ZIP file? pos = subfile . indexOf ( ' ' ) ; if ( pos != - 1 ) { // find out first ZIP file and remainder String remainder = subfile . substring ( pos + 1 ) ; File subzipfile = File . createTempFile ( "ZipUtils" , ".zip" ) ; try { readToTemporaryFile ( pos , zip , subfile , zipfile , subzipfile ) ; // start another recursion with the temporary file and the remainder return new DeleteOnCloseInputStream ( new ZipFileCloseInputStream ( getZipContentsRecursive ( subzipfile . getAbsolutePath ( ) + ZIP_DELIMITER + remainder ) , zipfile ) , subzipfile ) ; } catch ( IOException e ) { // need to close the zipfile here as we do not put it into a ZipFileCloseInputStream zipfile . close ( ) ; throw e ; } finally { if ( ! subzipfile . delete ( ) ) { logger . warning ( "Could not delete file " + subzipfile ) ; } } } ZipEntry entry = zipfile . getEntry ( subfile ) ; return new ZipFileCloseInputStream ( zipfile . getInputStream ( entry ) , zipfile ) ; }
Get a stream of the noted file which potentially resides inside ZIP files . An exclamation mark ! denotes a zip - entry . ZIP files can be nested inside one another .
613
34
23,405
public static String getZipStringContentsRecursive ( final String file ) throws IOException { // return local file directly int pos = file . indexOf ( ' ' ) ; if ( pos == - 1 ) { if ( ! new File ( file ) . exists ( ) ) { throw new IOException ( "File " + file + " does not exist" ) ; } try { try ( InputStream str = new FileInputStream ( file ) ) { if ( str . available ( ) > 0 ) { return IOUtils . toString ( str , "UTF-8" ) ; } return "" ; } } catch ( IOException e ) { // filter out locked errors if ( e . getMessage ( ) . contains ( "because another process has locked" ) ) { logger . warning ( "Could not read file: " + file + " because it is locked." ) ; return "" ; } throw e ; } } String zip = file . substring ( 0 , pos ) ; String subfile = file . substring ( pos + 1 ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Trying to read zipfile: " + zip + " subfile: " + subfile ) ; } // open original zip if ( ! new File ( zip ) . exists ( ) || ! new File ( zip ) . isFile ( ) || ! new File ( zip ) . canRead ( ) || new File ( zip ) . length ( ) == 0 ) { throw new IOException ( "ZIP file: " + zip + " does not exist or is empty or not a readable file." ) ; } try ( ZipFile zipfile = new ZipFile ( zip ) ) { // is the target file in yet another ZIP file? pos = subfile . indexOf ( ' ' ) ; if ( pos != - 1 ) { // find out first ZIP file and remainder String remainder = subfile . substring ( pos + 1 ) ; File subzipfile = File . createTempFile ( "SearchZip" , ".zip" ) ; try { readToTemporaryFile ( pos , zip , subfile , zipfile , subzipfile ) ; // start another recursion with the temporary file and the remainder return getZipStringContentsRecursive ( subzipfile . getAbsolutePath ( ) + ZIP_DELIMITER + remainder ) ; } finally { if ( ! subzipfile . delete ( ) ) { logger . warning ( "Could not delete file " + subzipfile ) ; } } } ZipEntry entry = zipfile . getEntry ( subfile ) ; try ( InputStream str = zipfile . getInputStream ( entry ) ) { if ( str . available ( ) > 0 ) { return IOUtils . toString ( str , "UTF-8" ) ; } return "" ; } } }
Get the text - contents of the noted file . An exclamation mark ! denotes a zip - entry . ZIP files can be nested inside one another .
601
30
23,406
public static void extractZip ( File zip , File toDir ) throws IOException { if ( ! toDir . exists ( ) ) { throw new IOException ( "Directory '" + toDir + "' does not exist." ) ; } try ( ZipFile zipFile = new ZipFile ( zip ) ) { Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; File target = new File ( toDir , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { // Assume directories are stored parents first then children. //logger.info("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. if ( ! target . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target ) ; } continue ; } // zips can contain nested files in sub-dirs without separate entries for the directories if ( ! target . getParentFile ( ) . exists ( ) && ! target . getParentFile ( ) . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target . getParentFile ( ) ) ; } //logger.info("Extracting file: " + entry.getName()); try ( InputStream inputStream = zipFile . getInputStream ( entry ) ) { try ( BufferedOutputStream outputStream = new BufferedOutputStream ( new FileOutputStream ( target ) ) ) { IOUtils . copy ( inputStream , outputStream ) ; } } } } catch ( FileNotFoundException | NoSuchFileException e ) { throw e ; } catch ( IOException e ) { throw new IOException ( "While extracting file " + zip + " to " + toDir , e ) ; } }
Extracts all files in the specified ZIP file and stores them in the denoted directory . The directory needs to exist before running this method .
401
29
23,407
public static void extractZip ( InputStream zip , final File toDir ) throws IOException { if ( ! toDir . exists ( ) ) { throw new IOException ( "Directory '" + toDir + "' does not exist." ) ; } // Use the ZipFileVisitor to walk all the entries in the Zip-Stream and create // directories and files accordingly new ZipFileVisitor ( ) { @ Override public void visit ( ZipEntry entry , InputStream data ) throws IOException { File target = new File ( toDir , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { // Assume directories are stored parents first then children. //logger.info("Extracting directory: " + entry.getName() + " to " + target); // This is not robust, just for demonstration purposes. if ( ! target . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target ) ; } return ; } // zips can contain nested files in sub-dirs without separate entries for the directories if ( ! target . getParentFile ( ) . exists ( ) && ! target . getParentFile ( ) . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target . getParentFile ( ) ) ; } // it seems we cannot use IOUtils/FileUtils to copy as they close the stream int size ; byte [ ] buffer = new byte [ 2048 ] ; try ( OutputStream fout = new BufferedOutputStream ( new FileOutputStream ( target ) , buffer . length ) ) { while ( ( size = data . read ( buffer , 0 , buffer . length ) ) != - 1 ) { fout . write ( buffer , 0 , size ) ; } } } } . walk ( zip ) ; }
Extracts all files in the ZIP file passed as InputStream and stores them in the denoted directory . The directory needs to exist before running this method .
384
32
23,408
public static void replaceInZip ( String zipFile , String data , String encoding ) throws IOException { if ( ! isFileInZip ( zipFile ) ) { throw new IOException ( "Parameter should specify a file inside a ZIP file, but had: " + zipFile ) ; } File zip = new File ( zipFile . substring ( 0 , zipFile . indexOf ( ZIP_DELIMITER ) ) ) ; String zipOut = zipFile . substring ( zipFile . indexOf ( ZIP_DELIMITER ) + 1 ) ; logger . info ( "Updating containing Zip " + zip + " to " + zipOut ) ; // replace in zip ZipUtils . replaceInZip ( zip , zipOut , data , encoding ) ; }
Replace the file denoted by the zipFile with the provided data . The zipFile specifies both the zip and the file inside the zip using ! as separator .
163
34
23,409
public static void replaceInZip ( File zip , String file , String data , String encoding ) throws IOException { // open the output side File zipOutFile = File . createTempFile ( "ZipReplace" , ".zip" ) ; try { FileOutputStream fos = new FileOutputStream ( zipOutFile ) ; try ( ZipOutputStream zos = new ZipOutputStream ( fos ) ) { // open the input side try ( ZipFile zipFile = new ZipFile ( zip ) ) { boolean found = false ; // walk all entries and copy them into the new file Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; try { if ( entry . getName ( ) . equals ( file ) ) { zos . putNextEntry ( new ZipEntry ( entry . getName ( ) ) ) ; IOUtils . write ( data , zos , encoding ) ; found = true ; } else { zos . putNextEntry ( entry ) ; IOUtils . copy ( zipFile . getInputStream ( entry ) , zos ) ; } } finally { zos . closeEntry ( ) ; } } if ( ! found ) { zos . putNextEntry ( new ZipEntry ( file ) ) ; try { IOUtils . write ( data , zos , "UTF-8" ) ; } finally { zos . closeEntry ( ) ; } } } } // copy over the data FileUtils . copyFile ( zipOutFile , zip ) ; } finally { if ( ! zipOutFile . delete ( ) ) { //noinspection ThrowFromFinallyBlock throw new IOException ( "Error deleting file: " + zipOutFile ) ; } } }
Replaces the specified file in the provided ZIP file with the provided content .
386
15
23,410
public static GeoPosition getPosition ( Point2D pixelCoordinate , int zoom , TileFactoryInfo info ) { // p(" --bitmap to latlon : " + coord + " " + zoom); double wx = pixelCoordinate . getX ( ) ; double wy = pixelCoordinate . getY ( ) ; // this reverses getBitmapCoordinates double flon = ( wx - info . getMapCenterInPixelsAtZoom ( zoom ) . getX ( ) ) / info . getLongitudeDegreeWidthInPixels ( zoom ) ; double e1 = ( wy - info . getMapCenterInPixelsAtZoom ( zoom ) . getY ( ) ) / ( - 1 * info . getLongitudeRadianWidthInPixels ( zoom ) ) ; double e2 = ( 2 * Math . atan ( Math . exp ( e1 ) ) - Math . PI / 2 ) / ( Math . PI / 180.0 ) ; double flat = e2 ; GeoPosition wc = new GeoPosition ( flat , flon ) ; return wc ; }
Convert an on screen pixel coordinate and a zoom level to a geo position
236
15
23,411
public GeoPosition pixelToGeo ( Point2D pixelCoordinate , int zoom ) { return GeoUtil . getPosition ( pixelCoordinate , zoom , getInfo ( ) ) ; }
Convert a pixel in the world bitmap at the specified zoom level into a GeoPosition
40
18
23,412
public Point2D geoToPixel ( GeoPosition c , int zoomLevel ) { return GeoUtil . getBitmapCoordinate ( c , zoomLevel , getInfo ( ) ) ; }
Convert a GeoPosition to a pixel position in the world bitmap a the specified zoom level .
40
20
23,413
private void doPaintComponent ( Graphics g ) { /* * if (isOpaque() || isDesignTime()) { g.setColor(getBackground()); g.fillRect(0,0,getWidth(),getHeight()); } */ if ( isDesignTime ( ) ) { // do nothing } else { int z = getZoom ( ) ; Rectangle viewportBounds = getViewportBounds ( ) ; drawMapTiles ( g , z , viewportBounds ) ; drawOverlays ( z , g , viewportBounds ) ; } super . paintBorder ( g ) ; }
the method that does the actual painting
130
7
23,414
public void setZoom ( int zoom ) { if ( zoom == this . zoomLevel ) { return ; } TileFactoryInfo info = getTileFactory ( ) . getInfo ( ) ; // don't repaint if we are out of the valid zoom levels if ( info != null && ( zoom < info . getMinimumZoomLevel ( ) || zoom > info . getMaximumZoomLevel ( ) ) ) { return ; } // if(zoom >= 0 && zoom <= 15 && zoom != this.zoom) { int oldzoom = this . zoomLevel ; Point2D oldCenter = getCenter ( ) ; Dimension oldMapSize = getTileFactory ( ) . getMapSize ( oldzoom ) ; this . zoomLevel = zoom ; this . firePropertyChange ( "zoom" , oldzoom , zoom ) ; Dimension mapSize = getTileFactory ( ) . getMapSize ( zoom ) ; setCenter ( new Point2D . Double ( oldCenter . getX ( ) * ( mapSize . getWidth ( ) / oldMapSize . getWidth ( ) ) , oldCenter . getY ( ) * ( mapSize . getHeight ( ) / oldMapSize . getHeight ( ) ) ) ) ; repaint ( ) ; }
Set the current zoom level
264
5
23,415
public void setAddressLocation ( GeoPosition addressLocation ) { GeoPosition old = getAddressLocation ( ) ; this . addressLocation = addressLocation ; setCenter ( getTileFactory ( ) . geoToPixel ( addressLocation , getZoom ( ) ) ) ; firePropertyChange ( "addressLocation" , old , getAddressLocation ( ) ) ; repaint ( ) ; }
Gets the current address location of the map
78
9
23,416
public void setDrawTileBorders ( boolean drawTileBorders ) { boolean old = isDrawTileBorders ( ) ; this . drawTileBorders = drawTileBorders ; firePropertyChange ( "drawTileBorders" , old , isDrawTileBorders ( ) ) ; repaint ( ) ; }
Set if the tile borders should be drawn . Mainly used for debugging .
66
15
23,417
public void setCenterPosition ( GeoPosition geoPosition ) { GeoPosition oldVal = getCenterPosition ( ) ; setCenter ( getTileFactory ( ) . geoToPixel ( geoPosition , zoomLevel ) ) ; repaint ( ) ; GeoPosition newVal = getCenterPosition ( ) ; firePropertyChange ( "centerPosition" , oldVal , newVal ) ; }
A property indicating the center position of the map
77
9
23,418
public void setCenter ( Point2D center ) { Point2D old = this . getCenter ( ) ; double centerX = center . getX ( ) ; double centerY = center . getY ( ) ; Dimension mapSize = getTileFactory ( ) . getMapSize ( getZoom ( ) ) ; int mapHeight = ( int ) mapSize . getHeight ( ) * getTileFactory ( ) . getTileSize ( getZoom ( ) ) ; int mapWidth = ( int ) mapSize . getWidth ( ) * getTileFactory ( ) . getTileSize ( getZoom ( ) ) ; if ( isRestrictOutsidePanning ( ) ) { Insets insets = getInsets ( ) ; int viewportHeight = getHeight ( ) - insets . top - insets . bottom ; int viewportWidth = getWidth ( ) - insets . left - insets . right ; // don't let the user pan over the top edge Rectangle newVP = calculateViewportBounds ( center ) ; if ( newVP . getY ( ) < 0 ) { centerY = viewportHeight / 2 ; } // don't let the user pan over the left edge if ( ! isHorizontalWrapped ( ) && newVP . getX ( ) < 0 ) { centerX = viewportWidth / 2 ; } // don't let the user pan over the bottom edge if ( newVP . getY ( ) + newVP . getHeight ( ) > mapHeight ) { centerY = mapHeight - viewportHeight / 2 ; } // don't let the user pan over the right edge if ( ! isHorizontalWrapped ( ) && ( newVP . getX ( ) + newVP . getWidth ( ) > mapWidth ) ) { centerX = mapWidth - viewportWidth / 2 ; } // if map is to small then just center it vert if ( mapHeight < newVP . getHeight ( ) ) { centerY = mapHeight / 2 ; // viewportHeight/2;// - mapHeight/2; } // if map is too small then just center it horiz if ( ! isHorizontalWrapped ( ) && mapWidth < newVP . getWidth ( ) ) { centerX = mapWidth / 2 ; } } // If center is outside (0, 0,mapWidth, mapHeight) // compute modulo to get it back in. { centerX = centerX % mapWidth ; centerY = centerY % mapHeight ; if ( centerX < 0 ) centerX += mapWidth ; if ( centerY < 0 ) centerY += mapHeight ; } GeoPosition oldGP = this . getCenterPosition ( ) ; this . center = new Point2D . Double ( centerX , centerY ) ; firePropertyChange ( "center" , old , this . center ) ; firePropertyChange ( "centerPosition" , oldGP , this . getCenterPosition ( ) ) ; repaint ( ) ; }
Sets the new center of the map in pixel coordinates .
625
12
23,419
public void calculateZoomFrom ( Set < GeoPosition > positions ) { // u.p("calculating a zoom based on: "); // u.p(positions); if ( positions . size ( ) < 2 ) { return ; } int zoom = getZoom ( ) ; Rectangle2D rect = generateBoundingRect ( positions , zoom ) ; // Rectangle2D viewport = map.getViewportBounds(); int count = 0 ; while ( ! getViewportBounds ( ) . contains ( rect ) ) { // u.p("not contained"); Point2D centr = new Point2D . Double ( rect . getX ( ) + rect . getWidth ( ) / 2 , rect . getY ( ) + rect . getHeight ( ) / 2 ) ; GeoPosition px = getTileFactory ( ) . pixelToGeo ( centr , zoom ) ; // u.p("new geo = " + px); setCenterPosition ( px ) ; count ++ ; if ( count > 30 ) break ; if ( getViewportBounds ( ) . contains ( rect ) ) { // u.p("did it finally"); break ; } zoom = zoom + 1 ; if ( zoom > 15 ) //TODO: use maxZoom of the tfInfo { break ; } setZoom ( zoom ) ; rect = generateBoundingRect ( positions , zoom ) ; } }
Calculates a zoom level so that all points in the specified set will be visible on screen . This is useful if you have a bunch of points in an area like a city and you want to zoom out so that the entire city and it s points are visible without panning .
299
57
23,420
public void zoomToBestFit ( Set < GeoPosition > positions , double maxFraction ) { if ( positions . isEmpty ( ) ) return ; if ( maxFraction <= 0 || maxFraction > 1 ) throw new IllegalArgumentException ( "maxFraction must be between 0 and 1" ) ; TileFactory tileFactory = getTileFactory ( ) ; TileFactoryInfo info = tileFactory . getInfo ( ) ; if ( info == null ) return ; // set to central position initially GeoPosition centre = computeGeoCenter ( positions ) ; setCenterPosition ( centre ) ; if ( positions . size ( ) == 1 ) return ; // repeatedly zoom in until we find the first zoom level where either the width or height // of the points takes up more than the max fraction of the viewport // start with zoomed out at maximum int bestZoom = info . getMaximumZoomLevel ( ) ; Rectangle2D viewport = getViewportBounds ( ) ; Rectangle2D bounds = generateBoundingRect ( positions , bestZoom ) ; // is this zoom still OK? while ( bestZoom >= info . getMinimumZoomLevel ( ) && bounds . getWidth ( ) < viewport . getWidth ( ) * maxFraction && bounds . getHeight ( ) < viewport . getHeight ( ) * maxFraction ) { bestZoom -- ; bounds = generateBoundingRect ( positions , bestZoom ) ; } setZoom ( bestZoom + 1 ) ; }
Zoom and center the map to a best fit around the input GeoPositions . Best fit is defined as the most zoomed - in possible view where both the width and height of a bounding box around the positions take up no more than maxFraction of the viewport width or height respectively .
316
61
23,421
public GeoPosition convertPointToGeoPosition ( Point2D pt ) { // convert from local to world bitmap Rectangle bounds = getViewportBounds ( ) ; Point2D pt2 = new Point2D . Double ( pt . getX ( ) + bounds . getX ( ) , pt . getY ( ) + bounds . getY ( ) ) ; // convert from world bitmap to geo GeoPosition pos = getTileFactory ( ) . pixelToGeo ( pt2 , getZoom ( ) ) ; return pos ; }
Converts the specified Point2D in the JXMapViewer s local coordinate space to a GeoPosition on the map . This method is especially useful for determining the GeoPosition under the mouse cursor .
115
41
23,422
public void put ( URI uri , byte [ ] bimg , BufferedImage img ) { synchronized ( bytemap ) { while ( bytesize > 1000 * 1000 * 50 ) { URI olduri = bytemapAccessQueue . removeFirst ( ) ; byte [ ] oldbimg = bytemap . remove ( olduri ) ; bytesize -= oldbimg . length ; log ( "removed 1 img from byte cache" ) ; } bytemap . put ( uri , bimg ) ; bytesize += bimg . length ; bytemapAccessQueue . addLast ( uri ) ; } addToImageCache ( uri , img ) ; }
Put a tile image into the cache . This puts both a buffered image and array of bytes that make up the compressed image .
141
26
23,423
protected synchronized ExecutorService getService ( ) { if ( service == null ) { // System.out.println("creating an executor service with a threadpool of size " + threadPoolSize); service = Executors . newFixedThreadPool ( threadPoolSize , new ThreadFactory ( ) { private int count = 0 ; @ Override public Thread newThread ( Runnable r ) { Thread t = new Thread ( r , "tile-pool-" + count ++ ) ; t . setPriority ( Thread . MIN_PRIORITY ) ; t . setDaemon ( true ) ; return t ; } } ) ; } return service ; }
Subclasses may override this method to provide their own executor services . This method will be called each time a tile needs to be loaded . Implementations should cache the ExecutorService when possible .
137
39
23,424
public void setUserAgent ( String userAgent ) { if ( userAgent == null || userAgent . isEmpty ( ) ) { throw new IllegalArgumentException ( "User agent can't be null or empty." ) ; } this . userAgent = userAgent ; }
Set the User agent that will be used when making a tile request .
56
14
23,425
public synchronized void promote ( Tile tile ) { if ( tileQueue . contains ( tile ) ) { try { tileQueue . remove ( tile ) ; tile . setPriority ( Tile . Priority . High ) ; tileQueue . put ( tile ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } }
Increase the priority of this tile so it will be loaded sooner .
70
13
23,426
public final BufferedImageOp [ ] getFilters ( ) { BufferedImageOp [ ] results = new BufferedImageOp [ filters . length ] ; System . arraycopy ( filters , 0 , results , 0 , results . length ) ; return results ; }
A defensive copy of the Effects to apply to the results of the AbstractPainter s painting operation . The array may be empty but it will never be null .
55
32
23,427
public void setAntialiasing ( boolean value ) { boolean old = isAntialiasing ( ) ; antialiasing = value ; if ( old != value ) setDirty ( true ) ; firePropertyChange ( "antialiasing" , old , isAntialiasing ( ) ) ; }
Sets the antialiasing setting . This is a bound property .
66
15
23,428
public void setInterpolation ( Interpolation value ) { Object old = getInterpolation ( ) ; this . interpolation = value == null ? Interpolation . NearestNeighbor : value ; if ( old != value ) setDirty ( true ) ; firePropertyChange ( "interpolation" , old , getInterpolation ( ) ) ; }
Sets a new value for the interpolation setting . This setting determines if interpolation should be used when drawing scaled images .
77
25
23,429
protected void setDirty ( boolean d ) { boolean old = isDirty ( ) ; this . dirty = d ; firePropertyChange ( "dirty" , old , isDirty ( ) ) ; if ( isDirty ( ) ) { clearCache ( ) ; } }
Sets the dirty bit . If true then the painter is considered dirty and the cache will be cleared . This property is bound .
58
26
23,430
public void addPainter ( Painter < T > painter ) { Collection < Painter < T >> old = new ArrayList < Painter < T > > ( getPainters ( ) ) ; this . painters . add ( painter ) ; if ( painter instanceof AbstractPainter ) { ( ( AbstractPainter < ? > ) painter ) . addPropertyChangeListener ( handler ) ; } setDirty ( true ) ; firePropertyChange ( "painters" , old , getPainters ( ) ) ; }
Adds a painter to the queue of painters
105
9
23,431
public void removePainter ( Painter < T > painter ) { Collection < Painter < T >> old = new ArrayList < Painter < T > > ( getPainters ( ) ) ; this . painters . remove ( painter ) ; if ( painter instanceof AbstractPainter ) { ( ( AbstractPainter < ? > ) painter ) . removePropertyChangeListener ( handler ) ; } setDirty ( true ) ; firePropertyChange ( "painters" , old , getPainters ( ) ) ; }
Removes a painter from the queue of painters
105
10
23,432
public void setClipPreserved ( boolean shouldRestoreState ) { boolean oldShouldRestoreState = isClipPreserved ( ) ; this . clipPreserved = shouldRestoreState ; setDirty ( true ) ; firePropertyChange ( "clipPreserved" , oldShouldRestoreState , shouldRestoreState ) ; }
Sets if the clip should be preserved . Normally the clip will be reset between each painter . Setting clipPreserved to true can be used to let one painter mask other painters that come after it .
71
41
23,433
public void setTransform ( AffineTransform transform ) { AffineTransform old = getTransform ( ) ; this . transform = transform ; setDirty ( true ) ; firePropertyChange ( "transform" , old , transform ) ; }
Set a transform to be applied to all painters contained in this CompoundPainter
48
17
23,434
@ Override public Tile getTile ( int x , int y , int zoom ) { return new Tile ( x , y , zoom ) { @ Override public synchronized boolean isLoaded ( ) { return true ; } @ Override public BufferedImage getImage ( ) { return emptyTile ; } } ; }
Gets an instance of an empty tile for the given tile position and zoom on the world map .
65
20
23,435
@ Deprecated public static void installResponseCache ( String baseURL , File cacheDir , boolean checkForUpdates ) { ResponseCache . setDefault ( new LocalResponseCache ( baseURL , cacheDir , checkForUpdates ) ) ; }
Sets this cache as default response cache
50
8
23,436
public void setZoom ( int zoom ) { zoomChanging = true ; mainMap . setZoom ( zoom ) ; miniMap . setZoom ( mainMap . getZoom ( ) + 4 ) ; if ( sliderReversed ) { zoomSlider . setValue ( zoomSlider . getMaximum ( ) - zoom ) ; } else { zoomSlider . setValue ( zoom ) ; } zoomChanging = false ; }
Set the current zoomlevel for the main map . The minimap will be updated accordingly
91
17
23,437
public Action getZoomOutAction ( ) { Action act = new AbstractAction ( ) { /** * */ private static final long serialVersionUID = 5525706163434375107L ; @ Override public void actionPerformed ( ActionEvent e ) { setZoom ( mainMap . getZoom ( ) - 1 ) ; } } ; act . putValue ( Action . NAME , "-" ) ; return act ; }
Returns an action which can be attached to buttons or menu items to make the map zoom out
90
18
23,438
public void setMiniMapVisible ( boolean miniMapVisible ) { boolean old = this . isMiniMapVisible ( ) ; this . miniMapVisible = miniMapVisible ; miniMap . setVisible ( miniMapVisible ) ; firePropertyChange ( "miniMapVisible" , old , this . isMiniMapVisible ( ) ) ; }
Sets if the mini - map should be visible
78
10
23,439
public void setZoomSliderVisible ( boolean zoomSliderVisible ) { boolean old = this . isZoomSliderVisible ( ) ; this . zoomSliderVisible = zoomSliderVisible ; zoomSlider . setVisible ( zoomSliderVisible ) ; firePropertyChange ( "zoomSliderVisible" , old , this . isZoomSliderVisible ( ) ) ; }
Sets if the zoom slider should be visible
91
9
23,440
public void setZoomButtonsVisible ( boolean zoomButtonsVisible ) { boolean old = this . isZoomButtonsVisible ( ) ; this . zoomButtonsVisible = zoomButtonsVisible ; zoomInButton . setVisible ( zoomButtonsVisible ) ; zoomOutButton . setVisible ( zoomButtonsVisible ) ; firePropertyChange ( "zoomButtonsVisible" , old , this . isZoomButtonsVisible ( ) ) ; }
Sets if the zoom buttons should be visible . This ia bound property . Changes can be listened for using a PropertyChaneListener
106
27
23,441
public void setTileFactory ( TileFactory fact ) { mainMap . setTileFactory ( fact ) ; mainMap . setZoom ( fact . getInfo ( ) . getDefaultZoomLevel ( ) ) ; mainMap . setCenterPosition ( new GeoPosition ( 0 , 0 ) ) ; miniMap . setTileFactory ( fact ) ; miniMap . setZoom ( fact . getInfo ( ) . getDefaultZoomLevel ( ) + 3 ) ; miniMap . setCenterPosition ( new GeoPosition ( 0 , 0 ) ) ; zoomSlider . setMinimum ( fact . getInfo ( ) . getMinimumZoomLevel ( ) ) ; zoomSlider . setMaximum ( fact . getInfo ( ) . getMaximumZoomLevel ( ) ) ; }
Sets the tile factory for both embedded JXMapViewer components . Calling this method will also reset the center and zoom levels of both maps as well as the bounds of the zoom slider .
160
39
23,442
public File getLocalFile ( URL remoteUri ) { StringBuilder sb = new StringBuilder ( ) ; String host = remoteUri . getHost ( ) ; String query = remoteUri . getQuery ( ) ; String path = remoteUri . getPath ( ) ; if ( host != null ) { sb . append ( host ) ; } if ( path != null ) { sb . append ( path ) ; } if ( query != null ) { sb . append ( ' ' ) ; sb . append ( query ) ; } String name ; final int maxLen = 250 ; if ( sb . length ( ) < maxLen ) { name = sb . toString ( ) ; } else { name = sb . substring ( 0 , maxLen ) ; } name = name . replace ( ' ' , ' ' ) ; name = name . replace ( ' ' , ' ' ) ; name = name . replace ( ' ' , ' ' ) ; name = name . replace ( ' ' , ' ' ) ; name = name . replace ( ' ' , ' ' ) ; name = name . replace ( ' ' , ' ' ) ; File f = new File ( cacheDir , name ) ; return f ; }
Returns the local File corresponding to the given remote URI .
261
11
23,443
public void setPosition ( GeoPosition coordinate ) { GeoPosition old = getPosition ( ) ; this . position = coordinate ; firePropertyChange ( "position" , old , getPosition ( ) ) ; }
Set a new GeoPosition for this Waypoint
42
9
23,444
public String toWMSURL ( int x , int y , int zoom , int tileSize ) { String format = "image/jpeg" ; String styles = "" ; String srs = "EPSG:4326" ; int ts = tileSize ; int circumference = widthOfWorldInPixels ( zoom , tileSize ) ; double radius = circumference / ( 2 * Math . PI ) ; double ulx = MercatorUtils . xToLong ( x * ts , radius ) ; double uly = MercatorUtils . yToLat ( y * ts , radius ) ; double lrx = MercatorUtils . xToLong ( ( x + 1 ) * ts , radius ) ; double lry = MercatorUtils . yToLat ( ( y + 1 ) * ts , radius ) ; String bbox = ulx + "," + uly + "," + lrx + "," + lry ; String url = getBaseUrl ( ) + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format + "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles + // "&transparent=TRUE"+ "" ; return url ; }
Convertes to a WMS URL
291
8
23,445
public static BufferedImage convertToBufferedImage ( Image img ) { BufferedImage buff = createCompatibleTranslucentImage ( img . getWidth ( null ) , img . getHeight ( null ) ) ; Graphics2D g2 = buff . createGraphics ( ) ; try { g2 . drawImage ( img , 0 , 0 , null ) ; } finally { g2 . dispose ( ) ; } return buff ; }
Converts the specified image into a compatible buffered image .
89
12
23,446
public static void clear ( Image img ) { Graphics g = img . getGraphics ( ) ; try { if ( g instanceof Graphics2D ) { ( ( Graphics2D ) g ) . setComposite ( AlphaComposite . Clear ) ; } else { g . setColor ( new Color ( 0 , 0 , 0 , 0 ) ) ; } g . fillRect ( 0 , 0 , img . getWidth ( null ) , img . getHeight ( null ) ) ; } finally { g . dispose ( ) ; } }
Clears the data from the image .
112
8
23,447
public static void tileStretchPaint ( Graphics g , JComponent comp , BufferedImage img , Insets ins ) { int left = ins . left ; int right = ins . right ; int top = ins . top ; int bottom = ins . bottom ; // top g . drawImage ( img , 0 , 0 , left , top , 0 , 0 , left , top , null ) ; g . drawImage ( img , left , 0 , comp . getWidth ( ) - right , top , left , 0 , img . getWidth ( ) - right , top , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , 0 , comp . getWidth ( ) , top , img . getWidth ( ) - right , 0 , img . getWidth ( ) , top , null ) ; // middle g . drawImage ( img , 0 , top , left , comp . getHeight ( ) - bottom , 0 , top , left , img . getHeight ( ) - bottom , null ) ; g . drawImage ( img , left , top , comp . getWidth ( ) - right , comp . getHeight ( ) - bottom , left , top , img . getWidth ( ) - right , img . getHeight ( ) - bottom , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , top , comp . getWidth ( ) , comp . getHeight ( ) - bottom , img . getWidth ( ) - right , top , img . getWidth ( ) , img . getHeight ( ) - bottom , null ) ; // bottom g . drawImage ( img , 0 , comp . getHeight ( ) - bottom , left , comp . getHeight ( ) , 0 , img . getHeight ( ) - bottom , left , img . getHeight ( ) , null ) ; g . drawImage ( img , left , comp . getHeight ( ) - bottom , comp . getWidth ( ) - right , comp . getHeight ( ) , left , img . getHeight ( ) - bottom , img . getWidth ( ) - right , img . getHeight ( ) , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , comp . getHeight ( ) - bottom , comp . getWidth ( ) , comp . getHeight ( ) , img . getWidth ( ) - right , img . getHeight ( ) - bottom , img . getWidth ( ) , img . getHeight ( ) , null ) ; }
Draws an image on top of a component by doing a 3x3 grid stretch of the image using the specified insets .
522
26
23,448
@ Override public void mouseClicked ( MouseEvent evt ) { final boolean left = SwingUtilities . isLeftMouseButton ( evt ) ; final boolean singleClick = ( evt . getClickCount ( ) == 1 ) ; if ( ( left && singleClick ) ) { Rectangle bounds = viewer . getViewportBounds ( ) ; int x = bounds . x + evt . getX ( ) ; int y = bounds . y + evt . getY ( ) ; Point pixelCoordinates = new Point ( x , y ) ; mapClicked ( viewer . getTileFactory ( ) . pixelToGeo ( pixelCoordinates , viewer . getZoom ( ) ) ) ; } }
Gets called on mouseClicked events calculates the GeoPosition and fires the mapClicked method that the extending class needs to implement .
152
27
23,449
private void setRect ( double minLat , double minLng , double maxLat , double maxLng ) { if ( ! ( minLat < maxLat ) ) { throw new IllegalArgumentException ( "GeoBounds is not valid - minLat must be less that maxLat." ) ; } if ( ! ( minLng < maxLng ) ) { if ( minLng > 0 && minLng < 180 && maxLng < 0 ) { rects = new Rectangle2D [ ] { // split into two rects e.g. 176.8793 to 180 and -180 to // -175.0104 new Rectangle2D . Double ( minLng , minLat , 180 - minLng , maxLat - minLat ) , new Rectangle2D . Double ( - 180 , minLat , maxLng + 180 , maxLat - minLat ) } ; } else { rects = new Rectangle2D [ ] { new Rectangle2D . Double ( minLng , minLat , maxLng - minLng , maxLat - minLat ) } ; throw new IllegalArgumentException ( "GeoBounds is not valid - minLng must be less that maxLng or " + "minLng must be greater than 0 and maxLng must be less than 0." ) ; } } else { rects = new Rectangle2D [ ] { new Rectangle2D . Double ( minLng , minLat , maxLng - minLng , maxLat - minLat ) } ; } }
Sets the internal rectangle representation .
335
7
23,450
public boolean intersects ( GeoBounds other ) { boolean rv = false ; for ( Rectangle2D r1 : rects ) { for ( Rectangle2D r2 : other . rects ) { rv = r1 . intersects ( r2 ) ; if ( rv ) { break ; } } if ( rv ) { break ; } } return rv ; }
Determines if this bounds intersects the other bounds .
83
12
23,451
public GeoPosition getSouthEast ( ) { Rectangle2D r = rects [ 0 ] ; if ( rects . length > 1 ) { r = rects [ 1 ] ; } return new GeoPosition ( r . getY ( ) , r . getMaxX ( ) ) ; }
Gets the south east position .
62
7
23,452
public ExecuterManager bindListener ( Class < ? extends IExecutersListener > listener ) throws IllegalAccessException , InstantiationException { if ( listener != null ) { this . executerListeners . add ( listener . newInstance ( ) ) ; } return this ; }
bind executer listener
56
4
23,453
public static void save ( byte [ ] bytes , String filePath , String fileName ) throws IOException { Path path = Paths . get ( filePath , fileName ) ; mkirDirs ( path . getParent ( ) ) ; String pathStr = path . toString ( ) ; File file = new File ( pathStr ) ; write ( bytes , file ) ; }
save bytes into file
79
4
23,454
public static void write ( byte [ ] bytes , File file ) throws IOException { BufferedOutputStream outputStream = new BufferedOutputStream ( new FileOutputStream ( file ) ) ; outputStream . write ( bytes ) ; outputStream . close ( ) ; }
wtire bytes into file
55
5
23,455
public static char forDigit ( int digit , int radix ) { if ( digit >= 0 && digit < radix && radix >= Character . MIN_RADIX && radix <= MAX_RADIX ) { return digits [ digit ] ; } return ' ' ; }
Determines the character representation for a specific digit in the specified radix .
59
16
23,456
public RequestResponse setRequestData ( Object requestData ) { this . requestData = requestData ; requestJson = requestData != null ? ( requestData instanceof JsonNode ? ( JsonNode ) requestData : SerializationUtils . toJson ( requestData ) ) : null ; return this ; }
HTTP request body .
66
4
23,457
public RequestResponse setResponseData ( byte [ ] responseData ) { this . responseData = responseData ; try { responseJson = responseData != null ? SerializationUtils . readJson ( responseData ) : null ; } catch ( Exception e ) { responseJson = null ; LOGGER . error ( e . getMessage ( ) , e ) ; } return this ; }
Raw HTTP response data .
81
5
23,458
public String create ( Request request , Response response , Long duration ) { return createStringBuilder ( request , response , duration ) . toString ( ) ; }
Creates a string suitable for logging output .
32
9
23,459
public static long getMacAddr ( ) { if ( macAddr == 0 ) { try { InetAddress ip = InetAddress . getLocalHost ( ) ; NetworkInterface network = NetworkInterface . getByInetAddress ( ip ) ; byte [ ] mac = network . getHardwareAddress ( ) ; for ( byte temp : mac ) { macAddr = ( macAddr << 8 ) | ( ( int ) temp & 0xFF ) ; } } catch ( Exception e ) { macAddr = 0 ; } } return macAddr ; }
Returns host s MAC address .
118
6
23,460
public static long waitTillNextMillisec ( long currentMillisec ) { long nextMillisec = System . currentTimeMillis ( ) ; for ( ; nextMillisec <= currentMillisec ; nextMillisec = System . currentTimeMillis ( ) ) { Thread . yield ( ) ; } return nextMillisec ; }
Waits till clock moves to the next millisecond .
68
11
23,461
public static long waitTillNextTick ( long currentTick , long tickSize ) { long nextBlock = System . currentTimeMillis ( ) / tickSize ; for ( ; nextBlock <= currentTick ; nextBlock = System . currentTimeMillis ( ) / tickSize ) { Thread . yield ( ) ; } return nextBlock ; }
Waits till clock moves to the next tick .
74
10
23,462
synchronized public long generateId48 ( ) { final long blockSize = 1000L ; // block 1000 ms long timestamp = System . currentTimeMillis ( ) / blockSize ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) / blockSize ) { timestamp = waitTillNextSecond ( timestamp ) ; } if ( timestamp == lastTimestampMillisec . get ( ) / blockSize ) { // increase sequence sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_48 ) { // reset sequence sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextSecond ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp * blockSize ) ; timestamp = ( ( timestamp * blockSize - TIMESTAMP_EPOCH ) / blockSize ) & MASK_TIMESTAMP_48 ; return timestamp << SHIFT_TIMESTAMP_48 | template48 | ( sequence & MASK_SEQUENCE_48 ) ; }
Generates a 48 - bit id .
251
8
23,463
synchronized public long generateId64 ( ) { long timestamp = System . currentTimeMillis ( ) ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) ) { timestamp = waitTillNextMillisec ( timestamp ) ; } if ( timestamp == lastTimestampMillisec . get ( ) ) { // increase sequence sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_64 ) { // reset sequence sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextMillisec ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp ) ; timestamp = ( timestamp - TIMESTAMP_EPOCH ) & MASK_TIMESTAMP_64 ; return timestamp << SHIFT_TIMESTAMP_64 | template64 | ( sequence & MASK_SEQUENCE_64 ) ; }
Generates a 64 - bit id .
221
8
23,464
synchronized public BigInteger generateId128 ( ) { long timestamp = System . currentTimeMillis ( ) ; long sequence = 0 ; boolean done = false ; while ( ! done ) { done = true ; while ( timestamp < lastTimestampMillisec . get ( ) ) { timestamp = waitTillNextMillisec ( timestamp ) ; } if ( timestamp == lastTimestampMillisec . get ( ) ) { // increase sequence sequence = sequenceMillisec . incrementAndGet ( ) ; if ( sequence > MAX_SEQUENCE_128 ) { // reset sequence sequenceMillisec . set ( sequence = 0 ) ; timestamp = waitTillNextMillisec ( timestamp ) ; done = false ; } } } sequenceMillisec . set ( sequence ) ; lastTimestampMillisec . set ( timestamp ) ; BigInteger biSequence = BigInteger . valueOf ( sequence & MASK_SEQUENCE_128 ) ; BigInteger biResult = BigInteger . valueOf ( timestamp ) ; biResult = biResult . shiftLeft ( ( int ) SHIFT_TIMESTAMP_128 ) ; biResult = biResult . or ( template128 ) . or ( biSequence ) ; return biResult ; }
Generates a 128 - bit id .
253
8
23,465
public static RSAPublicKey buildPublicKey ( String base64KeyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { byte [ ] keyData = Base64 . getDecoder ( ) . decode ( base64KeyData ) ; return buildPublicKey ( keyData ) ; }
Construct the RSA public key from a key string data .
61
11
23,466
public static RSAPublicKey buildPublicKey ( byte [ ] keyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec ( keyData ) ; KeyFactory keyFactory = KeyFactory . getInstance ( CIPHER_ALGORITHM ) ; PublicKey generatePublic = keyFactory . generatePublic ( publicKeySpec ) ; return ( RSAPublicKey ) generatePublic ; }
Construct the RSA public key from a key binary data .
99
11
23,467
public static RSAPrivateKey buildPrivateKey ( final byte [ ] keyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec ( keyData ) ; KeyFactory keyFactory = KeyFactory . getInstance ( CIPHER_ALGORITHM ) ; PrivateKey generatePrivate = keyFactory . generatePrivate ( privateKeySpec ) ; return ( RSAPrivateKey ) generatePrivate ; }
Construct the RSA private key from a key binary data .
104
11
23,468
public static RSAPrivateKey buildPrivateKey ( final String base64KeyData ) throws NoSuchAlgorithmException , InvalidKeySpecException { byte [ ] keyData = Base64 . getDecoder ( ) . decode ( base64KeyData ) ; return buildPrivateKey ( keyData ) ; }
Construct the RSA private key from a key string data .
63
11
23,469
public static KeyPair generateKeys ( int numBits ) throws NoSuchAlgorithmException { int numBitsPow2 = 1 ; while ( numBitsPow2 < numBits ) { numBitsPow2 <<= 1 ; } KeyPairGenerator kpg = KeyPairGenerator . getInstance ( CIPHER_ALGORITHM ) ; kpg . initialize ( numBitsPow2 , SECURE_RNG ) ; KeyPair keyPair = kpg . generateKeyPair ( ) ; return keyPair ; }
Generate a random RSA keypair .
125
8
23,470
public static CloseableHttpClient newHttpClient ( ) { final SocketConfig socketConfig = SocketConfig . custom ( ) . setSoKeepAlive ( Boolean . TRUE ) . setTcpNoDelay ( Boolean . TRUE ) . setSoTimeout ( SOCKET_TIMEOUT_MS ) . build ( ) ; final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager ( ) ; manager . setDefaultMaxPerRoute ( MAX_HOSTS ) ; manager . setMaxTotal ( MAX_HOSTS ) ; manager . setDefaultSocketConfig ( socketConfig ) ; final RequestConfig requestConfig = RequestConfig . custom ( ) . setConnectTimeout ( CONNECTION_TIMEOUT_MS ) . setCookieSpec ( CookieSpecs . IGNORE_COOKIES ) . setStaleConnectionCheckEnabled ( Boolean . FALSE ) . setSocketTimeout ( SOCKET_TIMEOUT_MS ) . build ( ) ; final CloseableHttpClient client = HttpClients . custom ( ) . disableRedirectHandling ( ) . setConnectionManager ( manager ) . setDefaultRequestConfig ( requestConfig ) . setConnectionReuseStrategy ( new DefaultConnectionReuseStrategy ( ) ) . setConnectionBackoffStrategy ( new DefaultBackoffStrategy ( ) ) . setRetryHandler ( new DefaultHttpRequestRetryHandler ( MAX_RETRIES , false ) ) . setKeepAliveStrategy ( new DefaultConnectionKeepAliveStrategy ( ) ) . build ( ) ; return client ; }
Get a new CloseableHttpClient
323
7
23,471
@ Nullable public SnowizardResponse executeRequest ( final String host , final int count ) throws IOException { final String uri = String . format ( "http://%s/?count=%d" , host , count ) ; final HttpGet request = new HttpGet ( uri ) ; request . addHeader ( HttpHeaders . ACCEPT , ProtocolBufferMediaType . APPLICATION_PROTOBUF ) ; request . addHeader ( HttpHeaders . USER_AGENT , getUserAgent ( ) ) ; SnowizardResponse snowizard = null ; try { final BasicHttpContext context = new BasicHttpContext ( ) ; final HttpResponse response = client . execute ( request , context ) ; final int code = response . getStatusLine ( ) . getStatusCode ( ) ; if ( code == HttpStatus . SC_OK ) { final HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { snowizard = SnowizardResponse . parseFrom ( entity . getContent ( ) ) ; } EntityUtils . consumeQuietly ( entity ) ; } } finally { request . releaseConnection ( ) ; } return snowizard ; }
Execute a request to the Snowizard service URL
251
10
23,472
public long getId ( ) throws SnowizardClientException { for ( final String host : hosts ) { try { final SnowizardResponse snowizard = executeRequest ( host ) ; if ( snowizard != null ) { return snowizard . getId ( 0 ) ; } } catch ( final Exception ex ) { LOGGER . warn ( "Unable to get ID from host ({})" , host ) ; } } throw new SnowizardClientException ( "Unable to generate ID from Snowizard" ) ; }
Get a new ID from Snowizard
105
7
23,473
public List < Long > getIds ( final int count ) throws SnowizardClientException { for ( final String host : hosts ) { try { final SnowizardResponse snowizard = executeRequest ( host , count ) ; if ( snowizard != null ) { return snowizard . getIdList ( ) ; } } catch ( final Exception ex ) { LOGGER . warn ( "Unable to get ID from host ({})" , host ) ; } } throw new SnowizardClientException ( "Unable to generate batch of IDs from Snowizard" ) ; }
Get multiple IDs from Snowizard
116
6
23,474
protected String resolveAvailable ( CommonTokenStream tokens , EvaluationContext context ) { boolean hasMissing = false ; List < Object > outputComponents = new ArrayList <> ( ) ; for ( int t = 0 ; t < tokens . size ( ) - 1 ; t ++ ) { // we can ignore the final EOF token Token token = tokens . get ( t ) ; Token nextToken = tokens . get ( t + 1 ) ; // if token is a NAME not followed by ( then it's a context reference if ( token . getType ( ) == ExcellentParser . NAME && nextToken . getType ( ) != ExcellentParser . LPAREN ) { try { outputComponents . add ( context . resolveVariable ( token . getText ( ) ) ) ; } catch ( EvaluationError ex ) { hasMissing = true ; outputComponents . add ( token ) ; } } else { outputComponents . add ( token ) ; } } // if we don't have missing context references, perform evaluation as normal if ( ! hasMissing ) { return null ; } // re-combine the tokens and context values back into an expression StringBuilder output = new StringBuilder ( String . valueOf ( m_expressionPrefix ) ) ; for ( Object outputComponent : outputComponents ) { String compVal ; if ( outputComponent instanceof Token ) { compVal = ( ( Token ) outputComponent ) . getText ( ) ; } else { compVal = Conversions . toRepr ( outputComponent , context ) ; } output . append ( compVal ) ; } return output . toString ( ) ; }
Checks the token stream for context references and if there are missing references - substitutes available references and returns a partially evaluated expression .
333
25
23,475
public static Object getSpringBean ( ApplicationContext appContext , String id ) { try { Object bean = appContext . getBean ( id ) ; return bean ; } catch ( BeansException e ) { return null ; } }
Gets a bean by its id .
48
8
23,476
public static < T > T getBean ( ApplicationContext appContext , String id , Class < T > clazz ) { try { return appContext . getBean ( id , clazz ) ; } catch ( BeansException e ) { return null ; } }
Gets a bean by its id and class .
55
10
23,477
public static < T > Map < String , T > getBeansOfType ( ApplicationContext appContext , Class < T > clazz ) { try { return appContext . getBeansOfType ( clazz ) ; } catch ( BeansException e ) { return new HashMap < String , T > ( ) ; } }
Gets all beans of a given type .
68
9
23,478
public static Map < String , Object > getBeansWithAnnotation ( ApplicationContext appContext , Class < ? extends Annotation > annotationType ) { try { return appContext . getBeansWithAnnotation ( annotationType ) ; } catch ( BeansException e ) { return new HashMap < String , Object > ( ) ; } }
Gets all beans whose Class has the supplied Annotation type .
70
13
23,479
@ Override public MetricsPlugin register ( RestExpress server ) { if ( isRegistered ) return this ; server . registerPlugin ( this ) ; this . isRegistered = true ; server . addMessageObserver ( this ) . addPreprocessor ( this ) . addFinallyProcessor ( this ) ; return this ; }
Register the MetricsPlugin with the RestExpress server .
66
11
23,480
@ Override public void process ( Request request , Response response ) { Long duration = computeDurationMillis ( START_TIMES_BY_CORRELATION_ID . get ( request . getCorrelationId ( ) ) ) ; if ( duration != null && duration . longValue ( ) > 0 ) { response . addHeader ( "X-Response-Time" , String . valueOf ( duration ) ) ; } }
Set the X - Response - Time header to the response time in milliseconds .
89
15
23,481
public static boolean isValidIp ( String ip ) { if ( ! IP_PATTERN_FULL . matcher ( ip ) . matches ( ) ) { return false ; } String [ ] ipArr = ip . split ( "\\." ) ; for ( String part : ipArr ) { int v = Integer . parseInt ( part ) ; if ( v < 0 || v > 255 ) { return false ; } } return true ; }
Check is an IP is valid .
96
7
23,482
public static String normalisedVersion ( String version , String sep , int maxWidth ) { if ( version == null ) { return null ; } String [ ] split = Pattern . compile ( sep , Pattern . LITERAL ) . split ( version ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String s : split ) { sb . append ( String . format ( "%" + maxWidth + ' ' , s ) ) ; } return sb . toString ( ) ; }
Normalizes a version string .
104
6
23,483
public long getEstimateNumKeys ( String cfName ) throws RocksDbException { String prop = getProperty ( cfName , "rocksdb.estimate-num-keys" ) ; return prop != null ? Long . parseLong ( prop ) : 0 ; }
Gets estimated number of keys for a column family .
56
11
23,484
public RocksIterator getIterator ( String cfName ) { synchronized ( iterators ) { RocksIterator it = iterators . get ( cfName ) ; if ( it == null ) { ColumnFamilyHandle cfh = getColumnFamilyHandle ( cfName ) ; if ( cfh == null ) { return null ; } it = rocksDb . newIterator ( cfh , readOptions ) ; iterators . put ( cfName , it ) ; } return it ; } }
Obtains an iterator for a column family .
96
9
23,485
public void delete ( WriteOptions writeOptions , String key ) throws RocksDbException { delete ( DEFAULT_COLUMN_FAMILY , writeOptions , key ) ; }
Deletes a key from the default family specifying write options . F
37
13
23,486
public void delete ( String cfName , String key ) throws RocksDbException { delete ( cfName , writeOptions , key ) ; }
Deletes a key from a column family .
28
9
23,487
public void delete ( String cfName , WriteOptions writeOptions , String key ) throws RocksDbException { if ( cfName == null ) { cfName = DEFAULT_COLUMN_FAMILY ; } try { delete ( getColumnFamilyHandle ( cfName ) , writeOptions , key . getBytes ( StandardCharsets . UTF_8 ) ) ; } catch ( RocksDbException . ColumnFamilyNotExists e ) { throw new RocksDbException . ColumnFamilyNotExists ( cfName ) ; } }
Deletes a key from a column family specifying write options .
109
12
23,488
public byte [ ] get ( ReadOptions readOPtions , String key ) throws RocksDbException { return get ( DEFAULT_COLUMN_FAMILY , readOPtions , key ) ; }
Gets a value from the default column family specifying read options .
42
13
23,489
public byte [ ] get ( String cfName , String key ) throws RocksDbException { return get ( cfName , readOptions , key ) ; }
Gets a value from a column family .
31
9
23,490
public byte [ ] get ( String cfName , ReadOptions readOptions , String key ) throws RocksDbException { if ( cfName == null ) { cfName = DEFAULT_COLUMN_FAMILY ; } ColumnFamilyHandle cfh = columnFamilyHandles . get ( cfName ) ; if ( cfh == null ) { throw new RocksDbException . ColumnFamilyNotExists ( cfName ) ; } return get ( cfh , readOptions , key . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Gets a value from a column family specifying read options .
114
12
23,491
protected byte [ ] get ( ColumnFamilyHandle cfh , ReadOptions readOptions , byte [ ] key ) throws RocksDbException { try { return rocksDb . get ( cfh , readOptions != null ? readOptions : this . readOptions , key ) ; } catch ( Exception e ) { throw e instanceof RocksDbException ? ( RocksDbException ) e : new RocksDbException ( e ) ; } }
Gets a value .
86
5
23,492
protected String createCompleteMessage ( Request request , Response response , Timer timer ) { StringBuilder sb = new StringBuilder ( request . getEffectiveHttpMethod ( ) . toString ( ) ) ; sb . append ( " " ) ; sb . append ( request . getUrl ( ) ) ; if ( timer != null ) { sb . append ( " responded with " ) ; sb . append ( response . getResponseStatus ( ) . toString ( ) ) ; sb . append ( " in " ) ; sb . append ( timer . toString ( ) ) ; } else { sb . append ( " responded with " ) ; sb . append ( response . getResponseStatus ( ) . toString ( ) ) ; sb . append ( " (no timer found)" ) ; } return sb . toString ( ) ; }
Create the message to be logged when a request is completed successfully . Sub - classes can override .
180
19
23,493
protected String createExceptionMessage ( Throwable exception , Request request , Response response ) { StringBuilder sb = new StringBuilder ( request . getEffectiveHttpMethod ( ) . toString ( ) ) ; sb . append ( ' ' ) ; sb . append ( request . getUrl ( ) ) ; sb . append ( " threw exception: " ) ; sb . append ( exception . getClass ( ) . getSimpleName ( ) ) ; return sb . toString ( ) ; }
Create the message to be logged when a request results in an exception . Sub - classes can override .
104
20
23,494
public static void deleteValue ( Object target , String dPath ) { if ( target instanceof JsonNode ) { deleteValue ( ( JsonNode ) target , dPath ) ; return ; } String [ ] paths = splitDpath ( dPath ) ; Object cursor = target ; // "seek"to the correct position for ( int i = 0 ; i < paths . length - 1 ; i ++ ) { cursor = extractValue ( cursor , paths [ i ] ) ; } if ( cursor == null ) { return ; } String index = paths [ paths . length - 1 ] ; Matcher m = PATTERN_INDEX . matcher ( index ) ; if ( m . matches ( ) ) { try { int i = Integer . parseInt ( m . group ( 1 ) ) ; deleteFieldValue ( dPath , cursor , i ) ; } catch ( IndexOutOfBoundsException e ) { // rethrow for now throw e ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Error: Invalid index. Path [" + dPath + "], target [" + cursor . getClass ( ) + "]." , e ) ; } } else { deleteFieldValue ( dPath , cursor , index ) ; } }
Delete a value from the target object specified by DPath expression .
261
13
23,495
public static String toJsonString ( Object obj , ClassLoader classLoader ) { if ( obj == null ) { return "null" ; } ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; } try { ObjectMapper mapper = poolMapper . borrowObject ( ) ; if ( mapper != null ) { try { return mapper . writeValueAsString ( obj ) ; } finally { poolMapper . returnObject ( mapper ) ; } } throw new SerializationException ( "No ObjectMapper instance avaialble!" ) ; } catch ( Exception e ) { throw e instanceof SerializationException ? ( SerializationException ) e : new SerializationException ( e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } }
Serialize an object to JSON string with a custom class loader .
201
13
23,496
public static < T > T fromJsonString ( String jsonString , Class < T > clazz ) { return fromJsonString ( jsonString , clazz , null ) ; }
Deserialize a JSON string .
39
7
23,497
public void addLibrary ( Class < ? > library ) { for ( Method method : library . getDeclaredMethods ( ) ) { if ( ( method . getModifiers ( ) & Modifier . PUBLIC ) == 0 ) { continue ; // ignore non-public methods } String name = method . getName ( ) . toLowerCase ( ) ; // strip preceding _ chars used to avoid conflicts with Java keywords if ( name . startsWith ( "_" ) ) { name = name . substring ( 1 ) ; } m_functions . put ( name , method ) ; } }
Adds functions from a library class
121
6
23,498
public Object invokeFunction ( EvaluationContext ctx , String name , List < Object > args ) { // find function with given name Method func = getFunction ( name ) ; if ( func == null ) { throw new EvaluationError ( "Undefined function: " + name ) ; } List < Object > parameters = new ArrayList <> ( ) ; List < Object > remainingArgs = new ArrayList <> ( args ) ; for ( Parameter param : Parameter . fromMethod ( func ) ) { BooleanDefault defaultBool = param . getAnnotation ( BooleanDefault . class ) ; IntegerDefault defaultInt = param . getAnnotation ( IntegerDefault . class ) ; StringDefault defaultStr = param . getAnnotation ( StringDefault . class ) ; if ( param . getType ( ) . equals ( EvaluationContext . class ) ) { parameters . add ( ctx ) ; } else if ( param . getType ( ) . isArray ( ) ) { // we've reach a varargs param parameters . add ( remainingArgs . toArray ( new Object [ remainingArgs . size ( ) ] ) ) ; remainingArgs . clear ( ) ; break ; } else if ( remainingArgs . size ( ) > 0 ) { Object arg = remainingArgs . remove ( 0 ) ; parameters . add ( arg ) ; } else if ( defaultBool != null ) { parameters . add ( defaultBool . value ( ) ) ; } else if ( defaultInt != null ) { parameters . add ( defaultInt . value ( ) ) ; } else if ( defaultStr != null ) { parameters . add ( defaultStr . value ( ) ) ; } else { throw new EvaluationError ( "Too few arguments provided for function " + name ) ; } } if ( ! remainingArgs . isEmpty ( ) ) { throw new EvaluationError ( "Too many arguments provided for function " + name ) ; } try { return func . invoke ( null , parameters . toArray ( new Object [ parameters . size ( ) ] ) ) ; } catch ( Exception e ) { List < String > prettyArgs = new ArrayList <> ( ) ; for ( Object arg : args ) { String pretty ; if ( arg instanceof String ) { pretty = "\"" + arg + "\"" ; } else { try { pretty = Conversions . toString ( arg , ctx ) ; } catch ( EvaluationError ex ) { pretty = arg . toString ( ) ; } } prettyArgs . add ( pretty ) ; } throw new EvaluationError ( "Error calling function " + name + " with arguments " + StringUtils . join ( prettyArgs , ", " ) , e ) ; } }
Invokes a function
553
4
23,499
public List < FunctionDescriptor > buildListing ( ) { List < FunctionDescriptor > listing = new ArrayList <> ( ) ; for ( Map . Entry < String , Method > entry : m_functions . entrySet ( ) ) { FunctionDescriptor descriptor = new FunctionDescriptor ( entry . getKey ( ) . toUpperCase ( ) ) ; listing . add ( descriptor ) ; } Collections . sort ( listing , new Comparator < FunctionDescriptor > ( ) { @ Override public int compare ( FunctionDescriptor f1 , FunctionDescriptor f2 ) { return f1 . m_name . compareTo ( f2 . m_name ) ; } } ) ; return listing ; }
Builds a listing of all functions sorted A - Z . Unlike the Python port this only returns function names as Java doesn t so easily support reading of docstrings and Java 7 doesn t provide access to parameter names .
156
43