idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
21,000 | public static int simulateSerialization ( List < WayDataBlock > blocks ) { int sum = 0 ; for ( WayDataBlock wayDataBlock : blocks ) { sum += mSimulateSerialization ( wayDataBlock . getOuterWay ( ) ) ; if ( wayDataBlock . getInnerWays ( ) != null ) { for ( List < Integer > list : wayDataBlock . getInnerWays ( ) ) { sum += mSimulateSerialization ( list ) ; } } } return sum ; } | Computes the size in bytes for storing a list of WayDataBlock objects as unsigned var - bytes . |
21,001 | public static void clearResourceBitmaps ( ) { if ( ! AndroidGraphicFactory . KEEP_RESOURCE_BITMAPS ) { return ; } synchronized ( RESOURCE_BITMAPS ) { for ( Pair < android . graphics . Bitmap , Integer > p : RESOURCE_BITMAPS . values ( ) ) { p . first . recycle ( ) ; if ( AndroidGraphicFactory . DEBUG_BITMAPS ) { rInstances . decrementAndGet ( ) ; } } if ( AndroidGraphicFactory . DEBUG_BITMAPS ) { rBitmaps . clear ( ) ; } RESOURCE_BITMAPS . clear ( ) ; } } | clearResourceBitmaps is called |
21,002 | protected void destroyBitmap ( ) { if ( this . bitmap != null ) { if ( removeBitmap ( this . hash ) ) { this . bitmap . recycle ( ) ; } this . bitmap = null ; } } | and call down into destroyBitmap when the resource bitmap needs to be destroyed |
21,003 | public static OSMTag fromOSMTag ( OSMTag otherTag , short newID ) { return new OSMTag ( newID , otherTag . getKey ( ) , otherTag . getValue ( ) , otherTag . getZoomAppear ( ) , otherTag . isRenderable ( ) , otherTag . isForcePolygonLine ( ) , otherTag . isLabelPosition ( ) ) ; } | Convenience method that constructs a new OSMTag with a new id from another OSMTag . |
21,004 | public TileBitmap executeJob ( RendererJob rendererJob ) { RenderContext renderContext = null ; try { renderContext = new RenderContext ( rendererJob , new CanvasRasterer ( graphicFactory ) ) ; if ( renderBitmap ( renderContext ) ) { TileBitmap bitmap = null ; if ( this . mapDataStore != null ) { MapReadResult mapReadResult = this . mapDataStore . readMapData ( rendererJob . tile ) ; processReadMapData ( renderContext , mapReadResult ) ; } if ( ! rendererJob . labelsOnly ) { renderContext . renderTheme . matchHillShadings ( this , renderContext ) ; bitmap = this . graphicFactory . createTileBitmap ( rendererJob . tile . tileSize , rendererJob . hasAlpha ) ; bitmap . setTimestamp ( rendererJob . mapDataStore . getDataTimestamp ( rendererJob . tile ) ) ; renderContext . canvasRasterer . setCanvasBitmap ( bitmap ) ; if ( ! rendererJob . hasAlpha && rendererJob . displayModel . getBackgroundColor ( ) != renderContext . renderTheme . getMapBackground ( ) ) { renderContext . canvasRasterer . fill ( renderContext . renderTheme . getMapBackground ( ) ) ; } renderContext . canvasRasterer . drawWays ( renderContext ) ; } if ( this . renderLabels ) { Set < MapElementContainer > labelsToDraw = processLabels ( renderContext ) ; renderContext . canvasRasterer . drawMapElements ( labelsToDraw , rendererJob . tile ) ; } if ( ! rendererJob . labelsOnly && renderContext . renderTheme . hasMapBackgroundOutside ( ) ) { Rectangle insideArea = this . mapDataStore . boundingBox ( ) . getPositionRelativeToTile ( rendererJob . tile ) ; if ( ! rendererJob . hasAlpha ) { renderContext . canvasRasterer . fillOutsideAreas ( renderContext . renderTheme . getMapBackgroundOutside ( ) , insideArea ) ; } else { renderContext . canvasRasterer . fillOutsideAreas ( Color . TRANSPARENT , insideArea ) ; } } return bitmap ; } return null ; } catch ( Exception e ) { LOGGER . warning ( "Exception: " + e . getMessage ( ) ) ; return null ; } finally { if ( renderContext != null ) { renderContext . destroy ( ) ; } } } | Called when a job needs to be executed . |
21,005 | int getThreadDefaultConnectionFlags ( boolean readOnly ) { int flags = readOnly ? SQLiteConnectionPool . CONNECTION_FLAG_READ_ONLY : SQLiteConnectionPool . CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY ; if ( isMainThread ( ) ) { flags |= SQLiteConnectionPool . CONNECTION_FLAG_INTERACTIVE ; } return flags ; } | Gets default connection flags that are appropriate for this thread taking into account whether the thread is acting on behalf of the UI . |
21,006 | public static boolean deleteDatabase ( File file ) { if ( file == null ) { throw new IllegalArgumentException ( "file must not be null" ) ; } boolean deleted = false ; deleted |= file . delete ( ) ; deleted |= new File ( file . getPath ( ) + "-journal" ) . delete ( ) ; deleted |= new File ( file . getPath ( ) + "-shm" ) . delete ( ) ; deleted |= new File ( file . getPath ( ) + "-wal" ) . delete ( ) ; File dir = file . getParentFile ( ) ; if ( dir != null ) { final String prefix = file . getName ( ) + "-mj" ; File [ ] files = dir . listFiles ( new FileFilter ( ) { public boolean accept ( File candidate ) { return candidate . getName ( ) . startsWith ( prefix ) ; } } ) ; if ( files != null ) { for ( File masterJournal : files ) { deleted |= masterJournal . delete ( ) ; } } } return deleted ; } | Deletes a database including its journal file and other auxiliary files that may have been created by the database engine . |
21,007 | public void reopenReadWrite ( ) { synchronized ( mLock ) { throwIfNotOpenLocked ( ) ; if ( ! isReadOnlyLocked ( ) ) { return ; } final int oldOpenFlags = mConfigurationLocked . openFlags ; mConfigurationLocked . openFlags = ( mConfigurationLocked . openFlags & ~ OPEN_READ_MASK ) | OPEN_READWRITE ; try { mConnectionPoolLocked . reconfigure ( mConfigurationLocked ) ; } catch ( RuntimeException ex ) { mConfigurationLocked . openFlags = oldOpenFlags ; throw ex ; } } } | Reopens the database in read - write mode . If the database is already read - write does nothing . |
21,008 | public void addCustomFunction ( String name , int numArgs , CustomFunction function ) { SQLiteCustomFunction wrapper = new SQLiteCustomFunction ( name , numArgs , function ) ; synchronized ( mLock ) { throwIfNotOpenLocked ( ) ; mConfigurationLocked . customFunctions . add ( wrapper ) ; try { mConnectionPoolLocked . reconfigure ( mConfigurationLocked ) ; } catch ( RuntimeException ex ) { mConfigurationLocked . customFunctions . remove ( wrapper ) ; throw ex ; } } } | Registers a CustomFunction callback as a function that can be called from SQLite database triggers . |
21,009 | public long setMaximumSize ( long numBytes ) { long pageSize = getPageSize ( ) ; long numPages = numBytes / pageSize ; if ( ( numBytes % pageSize ) != 0 ) { numPages ++ ; } long newPageCount = DatabaseUtils . longForQuery ( this , "PRAGMA max_page_count = " + numPages , null ) ; return newPageCount * pageSize ; } | Sets the maximum size the database will grow to . The maximum size cannot be set below the current size . |
21,010 | public static String findEditTable ( String tables ) { if ( ! TextUtils . isEmpty ( tables ) ) { int spacepos = tables . indexOf ( ' ' ) ; int commapos = tables . indexOf ( ',' ) ; if ( spacepos > 0 && ( spacepos < commapos || commapos < 0 ) ) { return tables . substring ( 0 , spacepos ) ; } else if ( commapos > 0 && ( commapos < spacepos || spacepos < 0 ) ) { return tables . substring ( 0 , commapos ) ; } return tables ; } else { throw new IllegalStateException ( "Invalid tables" ) ; } } | Finds the name of the first table which is editable . |
21,011 | public long replaceOrThrow ( String table , String nullColumnHack , ContentValues initialValues ) throws SQLException { return insertWithOnConflict ( table , nullColumnHack , initialValues , CONFLICT_REPLACE ) ; } | Convenience method for replacing a row in the database . Inserts a new row if a row does not already exist . |
21,012 | public long insertWithOnConflict ( String table , String nullColumnHack , ContentValues initialValues , int conflictAlgorithm ) { acquireReference ( ) ; try { StringBuilder sql = new StringBuilder ( ) ; sql . append ( "INSERT" ) ; sql . append ( CONFLICT_VALUES [ conflictAlgorithm ] ) ; sql . append ( " INTO " ) ; sql . append ( table ) ; sql . append ( '(' ) ; Object [ ] bindArgs = null ; int size = ( initialValues != null && initialValues . size ( ) > 0 ) ? initialValues . size ( ) : 0 ; if ( size > 0 ) { bindArgs = new Object [ size ] ; int i = 0 ; for ( String colName : initialValues . keySet ( ) ) { sql . append ( ( i > 0 ) ? "," : "" ) ; sql . append ( colName ) ; bindArgs [ i ++ ] = initialValues . get ( colName ) ; } sql . append ( ')' ) ; sql . append ( " VALUES (" ) ; for ( i = 0 ; i < size ; i ++ ) { sql . append ( ( i > 0 ) ? ",?" : "?" ) ; } } else { sql . append ( nullColumnHack + ") VALUES (NULL" ) ; } sql . append ( ')' ) ; SQLiteStatement statement = new SQLiteStatement ( this , sql . toString ( ) , bindArgs ) ; try { return statement . executeInsert ( ) ; } finally { statement . close ( ) ; } } finally { releaseReference ( ) ; } } | General method for inserting a row into the database . |
21,013 | static void dumpAll ( Printer printer , boolean verbose ) { for ( SQLiteDatabase db : getActiveDatabases ( ) ) { db . dump ( printer , verbose ) ; } } | Dump detailed information about all open databases in the current process . Used by bug report . |
21,014 | public List < Pair < String , String > > getAttachedDbs ( ) { ArrayList < Pair < String , String > > attachedDbs = new ArrayList < Pair < String , String > > ( ) ; synchronized ( mLock ) { if ( mConnectionPoolLocked == null ) { return null ; } if ( ! mHasAttachedDbsLocked ) { attachedDbs . add ( new Pair < String , String > ( "main" , mConfigurationLocked . path ) ) ; return attachedDbs ; } acquireReference ( ) ; } try { Cursor c = null ; try { c = rawQuery ( "pragma database_list;" , null ) ; while ( c . moveToNext ( ) ) { attachedDbs . add ( new Pair < String , String > ( c . getString ( 1 ) , c . getString ( 2 ) ) ) ; } } finally { if ( c != null ) { c . close ( ) ; } } return attachedDbs ; } finally { releaseReference ( ) ; } } | Returns list of full pathnames of all attached databases including the main database by executing pragma database_list on the database . |
21,015 | public static TDWay fromWay ( Way way , NodeResolver resolver , List < String > preferredLanguages ) { if ( way == null ) return null ; SpecialTagExtractionResult ster = OSMUtils . extractSpecialFields ( way , preferredLanguages ) ; Map < Short , Object > knownWayTags = OSMUtils . extractKnownWayTags ( way ) ; if ( way . getWayNodes ( ) . size ( ) >= 2 ) { boolean validWay = true ; TDNode [ ] waynodes = new TDNode [ way . getWayNodes ( ) . size ( ) ] ; int i = 0 ; for ( WayNode waynode : way . getWayNodes ( ) ) { waynodes [ i ] = resolver . getNode ( waynode . getNodeId ( ) ) ; if ( waynodes [ i ] == null ) { validWay = false ; LOGGER . finer ( "unknown way node: " + waynode . getNodeId ( ) + " in way " + way . getId ( ) ) ; } i ++ ; } if ( validWay ) { byte shape = LINE ; if ( waynodes [ 0 ] . getId ( ) == waynodes [ waynodes . length - 1 ] . getId ( ) ) { if ( waynodes . length >= GeoUtils . MIN_NODES_POLYGON ) { if ( OSMUtils . isArea ( way ) ) { shape = SIMPLE_POLYGON ; } } else { LOGGER . finer ( "Found closed polygon with fewer than 4 way nodes. Way-id: " + way . getId ( ) ) ; return null ; } } return new TDWay ( way . getId ( ) , ster . getLayer ( ) , ster . getName ( ) , ster . getHousenumber ( ) , ster . getRef ( ) , knownWayTags , shape , waynodes ) ; } } return null ; } | Creates a new TDWay from an osmosis way entity using the given NodeResolver . |
21,016 | public void mergeRelationInformation ( TDRelation relation ) { if ( relation . hasTags ( ) ) { addTags ( relation . getTags ( ) ) ; } if ( getName ( ) == null && relation . getName ( ) != null ) { setName ( relation . getName ( ) ) ; } if ( getRef ( ) == null && relation . getRef ( ) != null ) { setRef ( relation . getRef ( ) ) ; } } | Merges tags from a relation with the tags of this way and puts the result into the way tags of this way . |
21,017 | public static TDNode fromNode ( Node node , List < String > preferredLanguages ) { SpecialTagExtractionResult ster = OSMUtils . extractSpecialFields ( node , preferredLanguages ) ; Map < Short , Object > knownWayTags = OSMUtils . extractKnownPOITags ( node ) ; return new TDNode ( node . getId ( ) , LatLongUtils . degreesToMicrodegrees ( node . getLatitude ( ) ) , LatLongUtils . degreesToMicrodegrees ( node . getLongitude ( ) ) , ster . getElevation ( ) , ster . getLayer ( ) , ster . getHousenumber ( ) , ster . getName ( ) , knownWayTags ) ; } | Constructs a new TDNode from a given osmosis node entity . Checks the validity of the entity . |
21,018 | private void setScaleStrokeWidth ( byte zoomLevel ) { int zoomLevelDiff = Math . max ( zoomLevel - STROKE_MIN_ZOOM_LEVEL , 0 ) ; this . renderTheme . scaleStrokeWidth ( ( float ) Math . pow ( STROKE_INCREASE , zoomLevelDiff ) , this . rendererJob . tile . zoomLevel ) ; } | Sets the scale stroke factor for the given zoom level . |
21,019 | private void closeFileChannel ( ) { try { if ( this . databaseIndexCache != null ) { this . databaseIndexCache . destroy ( ) ; } if ( this . inputChannel != null ) { this . inputChannel . close ( ) ; } } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } | Closes the map file channel and destroys all internal caches . Has no effect if no map file channel is currently opened . |
21,020 | private boolean processBlockSignature ( ReadBuffer readBuffer ) { if ( this . mapFileHeader . getMapFileInfo ( ) . debugFile ) { String signatureBlock = readBuffer . readUTF8EncodedString ( SIGNATURE_LENGTH_BLOCK ) ; if ( ! signatureBlock . startsWith ( "###TileStart" ) ) { LOGGER . warning ( "invalid block signature: " + signatureBlock ) ; return false ; } } return true ; } | Processes the block signature if present . |
21,021 | public MapReadResult readLabels ( Tile tile ) { return readMapData ( tile , tile , Selector . LABELS ) ; } | Reads only labels for tile . |
21,022 | public MapReadResult readMapData ( Tile tile ) { return readMapData ( tile , tile , Selector . ALL ) ; } | Reads all map data for the area covered by the given tile at the tile zoom level . |
21,023 | public MapReadResult readPoiData ( Tile tile ) { return readMapData ( tile , tile , Selector . POIS ) ; } | Reads only POI data for tile . |
21,024 | public MapReadResult readPoiData ( Tile upperLeft , Tile lowerRight ) { return readMapData ( upperLeft , lowerRight , Selector . POIS ) ; } | Reads POI data for an area defined by the tile in the upper left and the tile in the lower right corner . This implementation takes the data storage of a MapFile into account for greater efficiency . |
21,025 | public synchronized void addItem ( T item ) { synchronized ( items ) { items . add ( item ) ; } if ( center == null ) { center = item . getLatLong ( ) ; } else { double lat = 0 , lon = 0 ; int n = 0 ; synchronized ( items ) { for ( T object : items ) { if ( object == null ) { throw new NullPointerException ( "object == null" ) ; } if ( object . getLatLong ( ) == null ) { throw new NullPointerException ( "object.getLatLong() == null" ) ; } lat += object . getLatLong ( ) . latitude ; lon += object . getLatLong ( ) . longitude ; n ++ ; } } center = new LatLong ( lat / n , lon / n ) ; } } | add item to cluster object |
21,026 | public void clear ( ) { if ( clusterMarker != null ) { Layers mapOverlays = clusterManager . getMapView ( ) . getLayerManager ( ) . getLayers ( ) ; if ( mapOverlays . contains ( clusterMarker ) ) { mapOverlays . remove ( clusterMarker ) ; } clusterManager = null ; clusterMarker = null ; } synchronized ( items ) { items . clear ( ) ; } } | clears cluster object and removes the cluster from the layers collection . |
21,027 | public void redraw ( ) { Layers mapOverlays = clusterManager . getMapView ( ) . getLayerManager ( ) . getLayers ( ) ; if ( clusterMarker != null && ! clusterManager . getCurBounds ( ) . contains ( center ) && mapOverlays . contains ( clusterMarker ) ) { mapOverlays . remove ( clusterMarker ) ; return ; } if ( clusterMarker != null && mapOverlays . size ( ) > 0 && ! mapOverlays . contains ( clusterMarker ) && ! clusterManager . isClustering ) { mapOverlays . add ( 1 , clusterMarker ) ; } } | add the ClusterMarker to the Layers if is within Viewport otherwise remove . |
21,028 | static Point calculateCenterOfBoundingBox ( Point [ ] coordinates ) { double pointXMin = coordinates [ 0 ] . x ; double pointXMax = coordinates [ 0 ] . x ; double pointYMin = coordinates [ 0 ] . y ; double pointYMax = coordinates [ 0 ] . y ; for ( Point immutablePoint : coordinates ) { if ( immutablePoint . x < pointXMin ) { pointXMin = immutablePoint . x ; } else if ( immutablePoint . x > pointXMax ) { pointXMax = immutablePoint . x ; } if ( immutablePoint . y < pointYMin ) { pointYMin = immutablePoint . y ; } else if ( immutablePoint . y > pointYMax ) { pointYMax = immutablePoint . y ; } } return new Point ( ( pointXMin + pointXMax ) / 2 , ( pointYMax + pointYMin ) / 2 ) ; } | Calculates the center of the minimum bounding rectangle for the given coordinates . |
21,029 | public static ZoomIntervalConfiguration fromString ( String confString ) { String [ ] splitted = confString . split ( "," ) ; if ( splitted . length % 3 != 0 ) { throw new IllegalArgumentException ( "invalid zoom interval configuration, amount of comma-separated values must be a multiple of 3" ) ; } byte [ ] [ ] intervals = new byte [ splitted . length / 3 ] [ 3 ] ; for ( int i = 0 ; i < intervals . length ; i ++ ) { intervals [ i ] [ 0 ] = Byte . parseByte ( splitted [ i * 3 ] ) ; intervals [ i ] [ 1 ] = Byte . parseByte ( splitted [ i * 3 + 1 ] ) ; intervals [ i ] [ 2 ] = Byte . parseByte ( splitted [ i * 3 + 2 ] ) ; } return ZoomIntervalConfiguration . newInstance ( intervals ) ; } | Create a new ZoomIntervalConfiguration from the given string representation . Checks for validity . |
21,030 | public void setWorkingSet ( Set < K > workingSet ) { synchronized ( workingSet ) { for ( K key : workingSet ) { this . get ( key ) ; } } } | Sets the current working set ensuring that elements in this working set will not be ejected in the near future . |
21,031 | public static int filterColor ( int color , Filter filter ) { if ( filter == Filter . NONE ) { return color ; } int a = color >>> 24 ; int r = ( color >> 16 ) & 0xFF ; int g = ( color >> 8 ) & 0xFF ; int b = color & 0xFF ; switch ( filter ) { case GRAYSCALE : r = g = b = ( int ) ( 0.213f * r + 0.715f * g + 0.072f * b ) ; break ; case GRAYSCALE_INVERT : r = g = b = 255 - ( int ) ( 0.213f * r + 0.715f * g + 0.072f * b ) ; break ; case INVERT : r = 255 - r ; g = 255 - g ; b = 255 - b ; break ; } return ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b ; } | Color filtering . |
21,032 | public static float [ ] imageSize ( float picWidth , float picHeight , float scaleFactor , int width , int height , int percent ) { float bitmapWidth = picWidth * scaleFactor ; float bitmapHeight = picHeight * scaleFactor ; float aspectRatio = picWidth / picHeight ; if ( width != 0 && height != 0 ) { bitmapWidth = width ; bitmapHeight = height ; } else if ( width == 0 && height != 0 ) { bitmapWidth = height * aspectRatio ; bitmapHeight = height ; } else if ( width != 0 && height == 0 ) { bitmapHeight = width / aspectRatio ; bitmapWidth = width ; } if ( percent != 100 ) { bitmapWidth *= percent / 100f ; bitmapHeight *= percent / 100f ; } return new float [ ] { bitmapWidth , bitmapHeight } ; } | Given the original image size as well as width height percent parameters can compute the final image size . |
21,033 | public void validate ( ) { if ( this . mapStartPosition != null && this . bboxConfiguration != null && ! this . bboxConfiguration . contains ( this . mapStartPosition ) ) { throw new IllegalArgumentException ( "map start position is not valid, must be included in bounding box of the map, bbox: " + this . bboxConfiguration . toString ( ) + " - map start position: " + this . mapStartPosition . toString ( ) ) ; } } | Validates this configuration . |
21,034 | public static Geometry clipToTile ( TDWay way , Geometry geometry , TileCoordinate tileCoordinate , int enlargementInMeters ) { Geometry tileBBJTS = null ; Geometry ret = null ; tileBBJTS = tileToJTSGeometry ( tileCoordinate . getX ( ) , tileCoordinate . getY ( ) , tileCoordinate . getZoomlevel ( ) , enlargementInMeters ) ; try { if ( ! geometry . isValid ( ) ) { LOGGER . warning ( "invalid geometry prior to tile clipping, trying to repair " + way . getId ( ) ) ; geometry = JTSUtils . repairInvalidPolygon ( geometry ) ; if ( ! geometry . isValid ( ) ) { LOGGER . warning ( "invalid geometry even after attempt to fix " + way . getId ( ) ) ; } } ret = tileBBJTS . intersection ( geometry ) ; if ( ( ret instanceof Polygon || ret instanceof MultiPolygon ) && ! ret . isValid ( ) ) { LOGGER . warning ( "clipped way is not valid, trying to repair it: " + way . getId ( ) ) ; ret = JTSUtils . repairInvalidPolygon ( ret ) ; if ( ret == null ) { way . setInvalid ( true ) ; LOGGER . warning ( "could not repair invalid polygon: " + way . getId ( ) ) ; } } } catch ( TopologyException e ) { LOGGER . log ( Level . WARNING , "JTS cannot clip way, not storing it in data file: " + way . getId ( ) , e ) ; way . setInvalid ( true ) ; return null ; } return ret ; } | Clips a geometry to a tile . |
21,035 | public static Geometry simplifyGeometry ( TDWay way , Geometry geometry , byte zoomlevel , int tileSize , double simplificationFactor ) { Geometry ret = null ; Envelope bbox = geometry . getEnvelopeInternal ( ) ; double latMax = Math . max ( Math . abs ( bbox . getMaxY ( ) ) , Math . abs ( bbox . getMinY ( ) ) ) ; double deltaLat = deltaLat ( simplificationFactor , latMax , zoomlevel , tileSize ) ; try { ret = TopologyPreservingSimplifier . simplify ( geometry , deltaLat ) ; } catch ( TopologyException e ) { LOGGER . log ( Level . FINE , "JTS cannot simplify way due to an error, not simplifying way with id: " + way . getId ( ) , e ) ; way . setInvalid ( true ) ; return geometry ; } return ret ; } | Simplifies a geometry using the Douglas Peucker algorithm . |
21,036 | private static double deltaLat ( double deltaPixel , double lat , byte zoom , int tileSize ) { long mapSize = MercatorProjection . getMapSize ( zoom , tileSize ) ; double pixelY = MercatorProjection . latitudeToPixelY ( lat , mapSize ) ; double lat2 = MercatorProjection . pixelYToLatitude ( pixelY + deltaPixel , mapSize ) ; return Math . abs ( lat2 - lat ) ; } | Computes the amount of latitude degrees for a given distance in pixel at a given zoom level . |
21,037 | public void moveCenterAndZoom ( double moveHorizontal , double moveVertical , byte zoomLevelDiff ) { moveCenterAndZoom ( moveHorizontal , moveVertical , zoomLevelDiff , true ) ; } | Animates the center position of the map by the given amount of pixels . |
21,038 | public void moveCenterAndZoom ( double moveHorizontal , double moveVertical , byte zoomLevelDiff , boolean animated ) { synchronized ( this ) { long mapSize = MercatorProjection . getMapSize ( this . zoomLevel , this . displayModel . getTileSize ( ) ) ; double pixelX = MercatorProjection . longitudeToPixelX ( this . longitude , mapSize ) - moveHorizontal ; double pixelY = MercatorProjection . latitudeToPixelY ( this . latitude , mapSize ) - moveVertical ; pixelX = Math . min ( Math . max ( 0 , pixelX ) , mapSize ) ; pixelY = Math . min ( Math . max ( 0 , pixelY ) , mapSize ) ; double newLatitude = MercatorProjection . pixelYToLatitude ( pixelY , mapSize ) ; double newLongitude = MercatorProjection . pixelXToLongitude ( pixelX , mapSize ) ; setCenterInternal ( newLatitude , newLongitude ) ; setZoomLevelInternal ( this . zoomLevel + zoomLevelDiff , animated ) ; } notifyObservers ( ) ; } | Moves the center position of the map by the given amount of pixels . |
21,039 | public void setCenter ( LatLong latLong ) { synchronized ( this ) { setCenterInternal ( latLong . latitude , latLong . longitude ) ; } notifyObservers ( ) ; } | Sets the new center position of the map . |
21,040 | public void setMapPosition ( MapPosition mapPosition , boolean animated ) { synchronized ( this ) { setCenterInternal ( mapPosition . latLong . latitude , mapPosition . latLong . longitude ) ; setZoomLevelInternal ( mapPosition . zoomLevel , animated ) ; } notifyObservers ( ) ; } | Sets the new center position and zoom level of the map . |
21,041 | public void setZoomLevel ( byte zoomLevel , boolean animated ) { if ( zoomLevel < 0 ) { throw new IllegalArgumentException ( "zoomLevel must not be negative: " + zoomLevel ) ; } synchronized ( this ) { setZoomLevelInternal ( zoomLevel , animated ) ; } notifyObservers ( ) ; } | Sets the new zoom level of the map |
21,042 | protected ScaleBarLengthAndValue calculateScaleBarLengthAndValue ( DistanceUnitAdapter unitAdapter ) { this . prevMapPosition = this . mapViewPosition . getMapPosition ( ) ; double groundResolution = MercatorProjection . calculateGroundResolution ( this . prevMapPosition . latLong . latitude , MercatorProjection . getMapSize ( this . prevMapPosition . zoomLevel , this . displayModel . getTileSize ( ) ) ) ; groundResolution = groundResolution / unitAdapter . getMeterRatio ( ) ; int [ ] scaleBarValues = unitAdapter . getScaleBarValues ( ) ; int scaleBarLength = 0 ; int mapScaleValue = 0 ; for ( int scaleBarValue : scaleBarValues ) { mapScaleValue = scaleBarValue ; scaleBarLength = ( int ) ( mapScaleValue / groundResolution ) ; if ( scaleBarLength < ( this . mapScaleBitmap . getWidth ( ) - 10 ) ) { break ; } } return new ScaleBarLengthAndValue ( scaleBarLength , mapScaleValue ) ; } | Calculates the required length and value of the scalebar |
21,043 | protected boolean isRedrawNecessary ( ) { if ( this . redrawNeeded || this . prevMapPosition == null ) { return true ; } MapPosition currentMapPosition = this . mapViewPosition . getMapPosition ( ) ; if ( currentMapPosition . zoomLevel != this . prevMapPosition . zoomLevel ) { return true ; } double latitudeDiff = Math . abs ( currentMapPosition . latLong . latitude - this . prevMapPosition . latLong . latitude ) ; return latitudeDiff > LATITUDE_REDRAW_THRESHOLD ; } | Determines if a redraw is necessary or not |
21,044 | public synchronized T get ( int maxAssigned ) throws InterruptedException { while ( this . queueItems . isEmpty ( ) || this . assignedJobs . size ( ) >= maxAssigned ) { this . wait ( 200 ) ; if ( this . isInterrupted ) { this . isInterrupted = false ; return null ; } } if ( this . scheduleNeeded ) { this . scheduleNeeded = false ; schedule ( displayModel . getTileSize ( ) ) ; } T job = this . queueItems . remove ( 0 ) . object ; this . assignedJobs . add ( job ) ; return job ; } | Returns the most important entry from this queue . The method blocks while this queue is empty or while there are already a certain number of jobs assigned . |
21,045 | public void setWriteAheadLoggingEnabled ( boolean enabled ) { synchronized ( this ) { if ( mEnableWriteAheadLogging != enabled ) { if ( mDatabase != null && mDatabase . isOpen ( ) && ! mDatabase . isReadOnly ( ) ) { if ( enabled ) { mDatabase . enableWriteAheadLogging ( ) ; } else { mDatabase . disableWriteAheadLogging ( ) ; } } mEnableWriteAheadLogging = enabled ; } } } | Enables or disables the use of write - ahead logging for the database . |
21,046 | public synchronized void close ( ) { if ( mIsInitializing ) throw new IllegalStateException ( "Closed during initialization" ) ; if ( mDatabase != null && mDatabase . isOpen ( ) ) { mDatabase . close ( ) ; mDatabase = null ; } } | Close any open database object . |
21,047 | public void readHeader ( ReadBuffer readBuffer , long fileSize ) throws IOException { RequiredFields . readMagicByte ( readBuffer ) ; RequiredFields . readRemainingHeader ( readBuffer ) ; MapFileInfoBuilder mapFileInfoBuilder = new MapFileInfoBuilder ( ) ; RequiredFields . readFileVersion ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readFileSize ( readBuffer , fileSize , mapFileInfoBuilder ) ; RequiredFields . readMapDate ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readBoundingBox ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readTilePixelSize ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readProjectionName ( readBuffer , mapFileInfoBuilder ) ; OptionalFields . readOptionalFields ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readPoiTags ( readBuffer , mapFileInfoBuilder ) ; RequiredFields . readWayTags ( readBuffer , mapFileInfoBuilder ) ; readSubFileParameters ( readBuffer , fileSize , mapFileInfoBuilder ) ; this . mapFileInfo = mapFileInfoBuilder . build ( ) ; } | Reads and validates the header block from the map file . |
21,048 | protected void setMapScaleBar ( ) { String value = this . sharedPreferences . getString ( SETTING_SCALEBAR , SETTING_SCALEBAR_BOTH ) ; if ( SETTING_SCALEBAR_NONE . equals ( value ) ) { AndroidUtil . setMapScaleBar ( this . mapView , null , null ) ; } else { if ( SETTING_SCALEBAR_BOTH . equals ( value ) ) { AndroidUtil . setMapScaleBar ( this . mapView , MetricUnitAdapter . INSTANCE , ImperialUnitAdapter . INSTANCE ) ; } else if ( SETTING_SCALEBAR_METRIC . equals ( value ) ) { AndroidUtil . setMapScaleBar ( this . mapView , MetricUnitAdapter . INSTANCE , null ) ; } else if ( SETTING_SCALEBAR_IMPERIAL . equals ( value ) ) { AndroidUtil . setMapScaleBar ( this . mapView , ImperialUnitAdapter . INSTANCE , null ) ; } else if ( SETTING_SCALEBAR_NAUTICAL . equals ( value ) ) { AndroidUtil . setMapScaleBar ( this . mapView , NauticalUnitAdapter . INSTANCE , null ) ; } } } | Sets the scale bar from preferences . |
21,049 | protected void setMaxTextWidthFactor ( ) { mapView . getModel ( ) . displayModel . setMaxTextWidthFactor ( Float . valueOf ( sharedPreferences . getString ( SamplesApplication . SETTING_TEXTWIDTH , "0.7" ) ) ) ; } | sets the value for breaking line text in labels . |
21,050 | @ TargetApi ( Build . VERSION_CODES . HONEYCOMB ) public static void enableHome ( Activity a ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { a . getActionBar ( ) . setDisplayHomeAsUpEnabled ( true ) ; } } | Compatibility method . |
21,051 | public synchronized void storeMapItems ( Tile tile , List < MapElementContainer > mapItems ) { this . put ( tile , LayerUtil . collisionFreeOrdered ( mapItems ) ) ; this . version += 1 ; } | Stores a list of MapElements against a tile . |
21,052 | public static String getGraphVizString ( DoubleLinkedPoiCategory rootNode ) { StringBuilder sb = new StringBuilder ( ) ; Stack < PoiCategory > stack = new Stack < > ( ) ; stack . push ( rootNode ) ; DoubleLinkedPoiCategory currentNode ; sb . append ( "// dot test.dot -Tpng > test.png\r\n" ) ; sb . append ( "digraph Categories {\r\n" ) ; sb . append ( " graph [\r\nrankdir = \"LR\"\r\n]\r\n\r\nnode [\r\nshape = \"plaintext\"\r\n]" ) ; while ( ! stack . isEmpty ( ) ) { currentNode = ( DoubleLinkedPoiCategory ) stack . pop ( ) ; for ( PoiCategory childNode : currentNode . childCategories ) { stack . push ( childNode ) ; sb . append ( "\t\"" ) . append ( currentNode . getTitle ( ) ) . append ( " (" ) . append ( currentNode . getID ( ) ) . append ( ")" ) . append ( "\" -> \"" ) . append ( childNode . getTitle ( ) ) . append ( " (" ) . append ( childNode . getID ( ) ) . append ( ")" ) . append ( "\"\r\n" ) ; } } sb . append ( "}\r\n" ) ; return sb . toString ( ) ; } | Generates a GraphViz source representation as a tree having the current node as its root . |
21,053 | public static BoundingBox fromString ( String boundingBoxString ) { double [ ] coordinates = LatLongUtils . parseCoordinateString ( boundingBoxString , 4 ) ; return new BoundingBox ( coordinates [ 0 ] , coordinates [ 1 ] , coordinates [ 2 ] , coordinates [ 3 ] ) ; } | Creates a new BoundingBox from a comma - separated string of coordinates in the order minLat minLon maxLat maxLon . All coordinate values must be in degrees . |
21,054 | public Rectangle getPositionRelativeToTile ( Tile tile ) { Point upperLeft = MercatorProjection . getPixelRelativeToTile ( new LatLong ( this . maxLatitude , minLongitude ) , tile ) ; Point lowerRight = MercatorProjection . getPixelRelativeToTile ( new LatLong ( this . minLatitude , maxLongitude ) , tile ) ; return new Rectangle ( upperLeft . x , upperLeft . y , lowerRight . x , lowerRight . y ) ; } | Computes the coordinates of this bounding box relative to a tile . |
21,055 | public void destroy ( ) { this . poiMatchingCache . clear ( ) ; this . wayMatchingCache . clear ( ) ; for ( Rule r : this . rulesList ) { r . destroy ( ) ; } } | Must be called when this RenderTheme gets destroyed to clean up and free resources . |
21,056 | public void matchClosedWay ( RenderCallback renderCallback , final RenderContext renderContext , PolylineContainer way ) { matchWay ( renderCallback , renderContext , Closed . YES , way ) ; } | Matches a closed way with the given parameters against this RenderTheme . |
21,057 | public void matchLinearWay ( RenderCallback renderCallback , final RenderContext renderContext , PolylineContainer way ) { matchWay ( renderCallback , renderContext , Closed . NO , way ) ; } | Matches a linear way with the given parameters against this RenderTheme . |
21,058 | public synchronized void matchNode ( RenderCallback renderCallback , final RenderContext renderContext , PointOfInterest poi ) { MatchingCacheKey matchingCacheKey = new MatchingCacheKey ( poi . tags , renderContext . rendererJob . tile . zoomLevel , Closed . NO ) ; List < RenderInstruction > matchingList = this . poiMatchingCache . get ( matchingCacheKey ) ; if ( matchingList != null ) { for ( int i = 0 , n = matchingList . size ( ) ; i < n ; ++ i ) { matchingList . get ( i ) . renderNode ( renderCallback , renderContext , poi ) ; } return ; } matchingList = new ArrayList < RenderInstruction > ( ) ; for ( int i = 0 , n = this . rulesList . size ( ) ; i < n ; ++ i ) { this . rulesList . get ( i ) . matchNode ( renderCallback , renderContext , matchingList , poi ) ; } this . poiMatchingCache . put ( matchingCacheKey , matchingList ) ; } | Matches a node with the given parameters against this RenderTheme . |
21,059 | public synchronized void scaleStrokeWidth ( float scaleFactor , byte zoomLevel ) { if ( ! strokeScales . containsKey ( zoomLevel ) || scaleFactor != strokeScales . get ( zoomLevel ) ) { for ( int i = 0 , n = this . rulesList . size ( ) ; i < n ; ++ i ) { Rule rule = this . rulesList . get ( i ) ; if ( rule . zoomMin <= zoomLevel && rule . zoomMax >= zoomLevel ) { rule . scaleStrokeWidth ( scaleFactor * this . baseStrokeWidth , zoomLevel ) ; } } strokeScales . put ( zoomLevel , scaleFactor ) ; } } | Scales the stroke width of this RenderTheme by the given factor for a given zoom level |
21,060 | public synchronized void scaleTextSize ( float scaleFactor , byte zoomLevel ) { if ( ! textScales . containsKey ( zoomLevel ) || scaleFactor != textScales . get ( zoomLevel ) ) { for ( int i = 0 , n = this . rulesList . size ( ) ; i < n ; ++ i ) { Rule rule = this . rulesList . get ( i ) ; if ( rule . zoomMin <= zoomLevel && rule . zoomMax >= zoomLevel ) { rule . scaleTextSize ( scaleFactor * this . baseTextSize , zoomLevel ) ; } } textScales . put ( zoomLevel , scaleFactor ) ; } } | Scales the text size of this RenderTheme by the given factor for a given zoom level . |
21,061 | protected void createMapViews ( ) { mapView = getMapView ( ) ; mapView . getModel ( ) . init ( this . preferencesFacade ) ; mapView . setClickable ( true ) ; mapView . getMapScaleBar ( ) . setVisible ( true ) ; mapView . setBuiltInZoomControls ( hasZoomControls ( ) ) ; mapView . getMapZoomControls ( ) . setAutoHide ( isZoomControlsAutoHide ( ) ) ; mapView . getMapZoomControls ( ) . setZoomLevelMin ( getZoomLevelMin ( ) ) ; mapView . getMapZoomControls ( ) . setZoomLevelMax ( getZoomLevelMax ( ) ) ; } | Template method to create the map views . |
21,062 | protected MapPosition getInitialPosition ( ) { MapDataStore mapFile = getMapFile ( ) ; if ( mapFile . startPosition ( ) != null ) { Byte startZoomLevel = mapFile . startZoomLevel ( ) ; if ( startZoomLevel == null ) { startZoomLevel = new Byte ( ( byte ) 12 ) ; } return new MapPosition ( mapFile . startPosition ( ) , startZoomLevel ) ; } else { return getDefaultInitialPosition ( ) ; } } | Extracts the initial position from the map file falling back onto the value supplied by getDefaultInitialPosition if there is no initial position coded into the map file . You will only need to override this method if you do not want the initial position extracted from the map file . |
21,063 | protected IMapViewPosition initializePosition ( IMapViewPosition mvp ) { LatLong center = mvp . getCenter ( ) ; if ( center . equals ( new LatLong ( 0 , 0 ) ) ) { mvp . setMapPosition ( this . getInitialPosition ( ) ) ; } mvp . setZoomLevelMax ( getZoomLevelMax ( ) ) ; mvp . setZoomLevelMin ( getZoomLevelMin ( ) ) ; return mvp ; } | initializes the map view position . |
21,064 | protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; createSharedPreferences ( ) ; createMapViews ( ) ; createTileCaches ( ) ; checkPermissionsAndCreateLayersAndControls ( ) ; } | Android Activity life cycle method . |
21,065 | public boolean onTap ( LatLong tapLatLong , Point layerXY , Point tapXY ) { this . expanded = ! this . expanded ; double centerX = layerXY . x + this . getHorizontalOffset ( ) ; double centerY = layerXY . y + this . getVerticalOffset ( ) ; double radiusX = this . getBitmap ( ) . getWidth ( ) / 2 ; double radiusY = this . getBitmap ( ) . getHeight ( ) / 2 ; double distX = Math . abs ( centerX - tapXY . x ) ; double distY = Math . abs ( centerY - tapXY . y ) ; if ( distX < radiusX && distY < radiusY ) { if ( this . expanded ) { for ( Layer elt : this . layers ) { if ( elt instanceof ChildMarker ) { this . layers . remove ( elt ) ; } } int i = this . children . size ( ) ; for ( ChildMarker marker : this . children ) { marker . init ( i , getBitmap ( ) , getHorizontalOffset ( ) , getVerticalOffset ( ) ) ; this . layers . add ( marker ) ; i -- ; } } else { for ( ChildMarker childMarker : this . children ) { this . layers . remove ( childMarker ) ; } } return true ; } return false ; } | Click on group marker shows all children on a spiral . |
21,066 | public boolean shouldYieldConnection ( SQLiteConnection connection , int connectionFlags ) { synchronized ( mLock ) { if ( ! mAcquiredConnections . containsKey ( connection ) ) { throw new IllegalStateException ( "Cannot perform this operation " + "because the specified connection was not acquired " + "from this pool or has already been released." ) ; } if ( ! mIsOpen ) { return false ; } return isSessionBlockingImportantConnectionWaitersLocked ( connection . isPrimaryConnection ( ) , connectionFlags ) ; } } | Returns true if the session should yield the connection due to contention over available database connections . |
21,067 | public void dump ( Printer printer , boolean verbose ) { Printer indentedPrinter = printer ; synchronized ( mLock ) { printer . println ( "Connection pool for " + mConfiguration . path + ":" ) ; printer . println ( " Open: " + mIsOpen ) ; printer . println ( " Max connections: " + mMaxConnectionPoolSize ) ; printer . println ( " Available primary connection:" ) ; if ( mAvailablePrimaryConnection != null ) { mAvailablePrimaryConnection . dump ( indentedPrinter , verbose ) ; } else { indentedPrinter . println ( "<none>" ) ; } printer . println ( " Available non-primary connections:" ) ; if ( ! mAvailableNonPrimaryConnections . isEmpty ( ) ) { final int count = mAvailableNonPrimaryConnections . size ( ) ; for ( int i = 0 ; i < count ; i ++ ) { mAvailableNonPrimaryConnections . get ( i ) . dump ( indentedPrinter , verbose ) ; } } else { indentedPrinter . println ( "<none>" ) ; } printer . println ( " Acquired connections:" ) ; if ( ! mAcquiredConnections . isEmpty ( ) ) { for ( Map . Entry < SQLiteConnection , AcquiredConnectionStatus > entry : mAcquiredConnections . entrySet ( ) ) { final SQLiteConnection connection = entry . getKey ( ) ; connection . dumpUnsafe ( indentedPrinter , verbose ) ; indentedPrinter . println ( " Status: " + entry . getValue ( ) ) ; } } else { indentedPrinter . println ( "<none>" ) ; } printer . println ( " Connection waiters:" ) ; if ( mConnectionWaiterQueue != null ) { int i = 0 ; final long now = SystemClock . uptimeMillis ( ) ; for ( ConnectionWaiter waiter = mConnectionWaiterQueue ; waiter != null ; waiter = waiter . mNext , i ++ ) { indentedPrinter . println ( i + ": waited for " + ( ( now - waiter . mStartTime ) * 0.001f ) + " ms - thread=" + waiter . mThread + ", priority=" + waiter . mPriority + ", sql='" + waiter . mSql + "'" ) ; } } else { indentedPrinter . println ( "<none>" ) ; } } } | Dumps debugging information about this connection pool . |
21,068 | private StatusLine readStatusLine ( WebSocketInputStream input ) throws WebSocketException { String line ; try { line = input . readLine ( ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . OPENING_HANDSHAKE_RESPONSE_FAILURE , "Failed to read an opening handshake response from the server: " + e . getMessage ( ) , e ) ; } if ( line == null || line . length ( ) == 0 ) { throw new WebSocketException ( WebSocketError . STATUS_LINE_EMPTY , "The status line of the opening handshake response is empty." ) ; } try { return new StatusLine ( line ) ; } catch ( Exception e ) { throw new WebSocketException ( WebSocketError . STATUS_LINE_BAD_FORMAT , "The status line of the opening handshake response is badly formatted. The status line is: " + line ) ; } } | Read a status line from an HTTP server . |
21,069 | private byte [ ] readBody ( Map < String , List < String > > headers , WebSocketInputStream input ) { int length = getContentLength ( headers ) ; if ( length <= 0 ) { return null ; } try { byte [ ] body = new byte [ length ] ; input . readBytes ( body , length ) ; return body ; } catch ( Throwable t ) { return null ; } } | Read the response body |
21,070 | private int getContentLength ( Map < String , List < String > > headers ) { try { return Integer . parseInt ( headers . get ( "Content-Length" ) . get ( 0 ) ) ; } catch ( Exception e ) { return - 1 ; } } | Get the value of Content - Length header . |
21,071 | public WebSocketExtension setParameter ( String key , String value ) { if ( Token . isValid ( key ) == false ) { throw new IllegalArgumentException ( "'key' is not a valid token." ) ; } if ( value != null ) { if ( Token . isValid ( value ) == false ) { throw new IllegalArgumentException ( "'value' is not a valid token." ) ; } } mParameters . put ( key , value ) ; return this ; } | Set a value to the specified parameter . |
21,072 | public WebSocketFrame setPayload ( byte [ ] payload ) { if ( payload != null && payload . length == 0 ) { payload = null ; } mPayload = payload ; return this ; } | Set the unmasked payload . |
21,073 | public WebSocketFrame setPayload ( String payload ) { if ( payload == null || payload . length ( ) == 0 ) { return setPayload ( ( byte [ ] ) null ) ; } return setPayload ( Misc . getBytesUTF8 ( payload ) ) ; } | Set the payload . The given string is converted to a byte array in UTF - 8 encoding . |
21,074 | public WebSocketFrame setCloseFramePayload ( int closeCode , String reason ) { byte [ ] encodedCloseCode = new byte [ ] { ( byte ) ( ( closeCode >> 8 ) & 0xFF ) , ( byte ) ( ( closeCode ) & 0xFF ) } ; if ( reason == null || reason . length ( ) == 0 ) { return setPayload ( encodedCloseCode ) ; } byte [ ] encodedReason = Misc . getBytesUTF8 ( reason ) ; byte [ ] payload = new byte [ 2 + encodedReason . length ] ; System . arraycopy ( encodedCloseCode , 0 , payload , 0 , 2 ) ; System . arraycopy ( encodedReason , 0 , payload , 2 , encodedReason . length ) ; return setPayload ( payload ) ; } | Set the payload that conforms to the payload format of close frames . |
21,075 | public int getCloseCode ( ) { if ( mPayload == null || mPayload . length < 2 ) { return WebSocketCloseCode . NONE ; } int closeCode = ( ( ( mPayload [ 0 ] & 0xFF ) << 8 ) | ( mPayload [ 1 ] & 0xFF ) ) ; return closeCode ; } | Parse the first two bytes of the payload as a close code . |
21,076 | public String getCloseReason ( ) { if ( mPayload == null || mPayload . length < 3 ) { return null ; } return Misc . toStringUTF8 ( mPayload , 2 , mPayload . length - 2 ) ; } | Parse the third and subsequent bytes of the payload as a close reason . |
21,077 | public static WebSocketFrame createTextFrame ( String payload ) { return new WebSocketFrame ( ) . setFin ( true ) . setOpcode ( TEXT ) . setPayload ( payload ) ; } | Create a text frame . |
21,078 | public static WebSocketFrame createBinaryFrame ( byte [ ] payload ) { return new WebSocketFrame ( ) . setFin ( true ) . setOpcode ( BINARY ) . setPayload ( payload ) ; } | Create a binary frame . |
21,079 | public byte get ( int index ) throws IndexOutOfBoundsException { if ( index < 0 || mLength <= index ) { throw new IndexOutOfBoundsException ( String . format ( "Bad index: index=%d, length=%d" , index , mLength ) ) ; } return mBuffer . get ( index ) ; } | Get a byte at the index . |
21,080 | private void expandBuffer ( int newBufferSize ) { ByteBuffer newBuffer = ByteBuffer . allocate ( newBufferSize ) ; int oldPosition = mBuffer . position ( ) ; mBuffer . position ( 0 ) ; newBuffer . put ( mBuffer ) ; newBuffer . position ( oldPosition ) ; mBuffer = newBuffer ; } | Expand the size of the internal buffer . |
21,081 | public void put ( int data ) { if ( mBuffer . capacity ( ) < ( mLength + 1 ) ) { expandBuffer ( mLength + ADDITIONAL_BUFFER_SIZE ) ; } mBuffer . put ( ( byte ) data ) ; ++ mLength ; } | Add a byte at the current position . |
21,082 | private void verifyReservedBit1 ( WebSocketFrame frame ) throws WebSocketException { if ( mPMCE != null ) { boolean verified = verifyReservedBit1ForPMCE ( frame ) ; if ( verified ) { return ; } } if ( frame . getRsv1 ( ) == false ) { return ; } throw new WebSocketException ( WebSocketError . UNEXPECTED_RESERVED_BIT , "The RSV1 bit of a frame is set unexpectedly." ) ; } | Verify the RSV1 bit of a frame . |
21,083 | private void verifyReservedBit2 ( WebSocketFrame frame ) throws WebSocketException { if ( frame . getRsv2 ( ) == false ) { return ; } throw new WebSocketException ( WebSocketError . UNEXPECTED_RESERVED_BIT , "The RSV2 bit of a frame is set unexpectedly." ) ; } | Verify the RSV2 bit of a frame . |
21,084 | private void verifyReservedBit3 ( WebSocketFrame frame ) throws WebSocketException { if ( frame . getRsv3 ( ) == false ) { return ; } throw new WebSocketException ( WebSocketError . UNEXPECTED_RESERVED_BIT , "The RSV3 bit of a frame is set unexpectedly." ) ; } | Verify the RSV3 bit of a frame . |
21,085 | private void verifyFrameOpcode ( WebSocketFrame frame ) throws WebSocketException { switch ( frame . getOpcode ( ) ) { case CONTINUATION : case TEXT : case BINARY : case CLOSE : case PING : case PONG : return ; default : break ; } if ( mWebSocket . isExtended ( ) ) { return ; } throw new WebSocketException ( WebSocketError . UNKNOWN_OPCODE , "A frame has an unknown opcode: 0x" + Integer . toHexString ( frame . getOpcode ( ) ) ) ; } | Ensure that the opcode of the give frame is a known one . |
21,086 | public ProxySettings reset ( ) { mSecure = false ; mHost = null ; mPort = - 1 ; mId = null ; mPassword = null ; mHeaders . clear ( ) ; mServerNames = null ; return this ; } | Reset the proxy settings . To be concrete parameter values are set as shown below . |
21,087 | public ProxySettings setServer ( URI uri ) { if ( uri == null ) { return this ; } String scheme = uri . getScheme ( ) ; String userInfo = uri . getUserInfo ( ) ; String host = uri . getHost ( ) ; int port = uri . getPort ( ) ; return setServer ( scheme , userInfo , host , port ) ; } | Set the proxy server by a URI . The parameters are updated as described below . |
21,088 | public ProxySettings addHeader ( String name , String value ) { if ( name == null || name . length ( ) == 0 ) { return this ; } List < String > list = mHeaders . get ( name ) ; if ( list == null ) { list = new ArrayList < String > ( ) ; mHeaders . put ( name , list ) ; } list . add ( value ) ; return this ; } | Add an additional HTTP header passed to the proxy server . |
21,089 | private void handshake ( ) throws WebSocketException { try { mProxyHandshaker . perform ( ) ; } catch ( IOException e ) { String message = String . format ( "Handshake with the proxy server (%s) failed: %s" , mAddress , e . getMessage ( ) ) ; throw new WebSocketException ( WebSocketError . PROXY_HANDSHAKE_ERROR , message , e ) ; } if ( mSSLSocketFactory == null ) { return ; } try { mSocket = mSSLSocketFactory . createSocket ( mSocket , mHost , mPort , true ) ; } catch ( IOException e ) { String message = "Failed to overlay an existing socket: " + e . getMessage ( ) ; throw new WebSocketException ( WebSocketError . SOCKET_OVERLAY_ERROR , message , e ) ; } try { ( ( SSLSocket ) mSocket ) . startHandshake ( ) ; if ( mSocket instanceof SSLSocket ) { verifyHostname ( ( SSLSocket ) mSocket , mProxyHandshaker . getProxiedHostname ( ) ) ; } } catch ( IOException e ) { String message = String . format ( "SSL handshake with the WebSocket endpoint (%s) failed: %s" , mAddress , e . getMessage ( ) ) ; throw new WebSocketException ( WebSocketError . SSL_HANDSHAKE_ERROR , message , e ) ; } } | Perform proxy handshake and optionally SSL handshake . |
21,090 | public WebSocket addHeader ( String name , String value ) { mHandshakeBuilder . addHeader ( name , value ) ; return this ; } | Add a pair of extra HTTP header . |
21,091 | public WebSocket setUserInfo ( String id , String password ) { mHandshakeBuilder . setUserInfo ( id , password ) ; return this ; } | Set the credentials to connect to the WebSocket endpoint . |
21,092 | public WebSocket flush ( ) { synchronized ( mStateManager ) { WebSocketState state = mStateManager . getState ( ) ; if ( state != OPEN && state != CLOSING ) { return this ; } } WritingThread wt = mWritingThread ; if ( wt != null ) { wt . queueFlush ( ) ; } return this ; } | Flush frames to the server . Flush is performed asynchronously . |
21,093 | public WebSocket connect ( ) throws WebSocketException { changeStateOnConnect ( ) ; Map < String , List < String > > headers ; try { mSocketConnector . connect ( ) ; headers = shakeHands ( ) ; } catch ( WebSocketException e ) { mSocketConnector . closeSilently ( ) ; mStateManager . setState ( CLOSED ) ; mListenerManager . callOnStateChanged ( CLOSED ) ; throw e ; } mServerHeaders = headers ; mPerMessageCompressionExtension = findAgreedPerMessageCompressionExtension ( ) ; mStateManager . setState ( OPEN ) ; mListenerManager . callOnStateChanged ( OPEN ) ; startThreads ( ) ; return this ; } | Connect to the server send an opening handshake to the server receive the response and then start threads to communicate with the server . |
21,094 | public WebSocket disconnect ( int closeCode , String reason , long closeDelay ) { synchronized ( mStateManager ) { switch ( mStateManager . getState ( ) ) { case CREATED : finishAsynchronously ( ) ; return this ; case OPEN : break ; default : return this ; } mStateManager . changeToClosing ( CloseInitiator . CLIENT ) ; WebSocketFrame frame = WebSocketFrame . createCloseFrame ( closeCode , reason ) ; sendFrame ( frame ) ; } mListenerManager . callOnStateChanged ( CLOSING ) ; if ( closeDelay < 0 ) { closeDelay = DEFAULT_CLOSE_DELAY ; } stopThreads ( closeDelay ) ; return this ; } | Disconnect the WebSocket . |
21,095 | public WebSocket sendFrame ( WebSocketFrame frame ) { if ( frame == null ) { return this ; } synchronized ( mStateManager ) { WebSocketState state = mStateManager . getState ( ) ; if ( state != OPEN && state != CLOSING ) { return this ; } } WritingThread wt = mWritingThread ; if ( wt == null ) { return this ; } List < WebSocketFrame > frames = splitIfNecessary ( frame ) ; if ( frames == null ) { wt . queueFrame ( frame ) ; } else { for ( WebSocketFrame f : frames ) { wt . queueFrame ( f ) ; } } return this ; } | Send a WebSocket frame to the server . |
21,096 | public WebSocket sendContinuation ( String payload , boolean fin ) { return sendFrame ( WebSocketFrame . createContinuationFrame ( payload ) . setFin ( fin ) ) ; } | Send a continuation frame to the server . |
21,097 | public WebSocket sendText ( String payload , boolean fin ) { return sendFrame ( WebSocketFrame . createTextFrame ( payload ) . setFin ( fin ) ) ; } | Send a text frame to the server . |
21,098 | public WebSocket sendBinary ( byte [ ] payload , boolean fin ) { return sendFrame ( WebSocketFrame . createBinaryFrame ( payload ) . setFin ( fin ) ) ; } | Send a binary frame to the server . |
21,099 | public WebSocket sendClose ( int closeCode , String reason ) { return sendFrame ( WebSocketFrame . createCloseFrame ( closeCode , reason ) ) ; } | Send a close frame to the server . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.