idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
9,000 | public boolean isWithinBoundingBox ( int x , int y , int zoom ) { boolean withinBounds = true ; if ( webMercatorBoundingBox != null ) { BoundingBox tileWebMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; BoundingBox adjustedWebMercatorBoundingBox = getWebMercatorBoundingBox ( tileWebMercatorBoundingBox ) ; withinBounds = adjustedWebMercatorBoundingBox . intersects ( tileWebMercatorBoundingBox , true ) ; } return withinBounds ; } | Check if the tile request is within the desired tile bounds |
9,001 | public boolean isOnAtCurrentZoom ( GoogleMap map , LatLng latLng ) { float zoom = MapUtils . getCurrentZoom ( map ) ; boolean on = isOnAtCurrentZoom ( zoom , latLng ) ; return on ; } | Determine if the the feature overlay is on for the current zoom level of the map at the location |
9,002 | public boolean isOnAtCurrentZoom ( double zoom , LatLng latLng ) { Point point = new Point ( latLng . longitude , latLng . latitude ) ; TileGrid tileGrid = TileBoundingBoxUtils . getTileGridFromWGS84 ( point , ( int ) zoom ) ; boolean on = boundedOverlay . hasTile ( ( int ) tileGrid . getMinX ( ) , ( int ) tileGrid . getMinY ( ) , ( int ) zoom ) ; return on ; } | Determine if the feature overlay is on for the provided zoom level at the location |
9,003 | public BoundingBox buildClickBoundingBox ( LatLng latLng , BoundingBox mapBounds ) { double width = TileBoundingBoxMapUtils . getLongitudeDistance ( mapBounds ) * screenClickPercentage ; double height = TileBoundingBoxMapUtils . getLatitudeDistance ( mapBounds ) * screenClickPercentage ; LatLng leftCoordinate = SphericalUtil . computeOffset ( latLng , width , 270 ) ; LatLng upCoordinate = SphericalUtil . computeOffset ( latLng , height , 0 ) ; LatLng rightCoordinate = SphericalUtil . computeOffset ( latLng , width , 90 ) ; LatLng downCoordinate = SphericalUtil . computeOffset ( latLng , height , 180 ) ; BoundingBox boundingBox = new BoundingBox ( leftCoordinate . longitude , downCoordinate . latitude , rightCoordinate . longitude , upCoordinate . latitude ) ; return boundingBox ; } | Build a bounding box using the location coordinate click location and map view bounds |
9,004 | public FeatureIndexResults queryFeatures ( BoundingBox boundingBox ) { FeatureIndexResults results = queryFeatures ( boundingBox , null ) ; return results ; } | Query for features in the WGS84 projected bounding box |
9,005 | public FeatureIndexResults queryFeatures ( BoundingBox boundingBox , Projection projection ) { if ( projection == null ) { projection = ProjectionFactory . getProjection ( ProjectionConstants . EPSG_WORLD_GEODETIC_SYSTEM ) ; } FeatureIndexManager indexManager = featureTiles . getIndexManager ( ) ; if ( indexManager == null ) { throw new GeoPackageException ( "Index Manager is not set on the Feature Tiles and is required to query indexed features" ) ; } FeatureIndexResults results = indexManager . query ( boundingBox , projection ) ; return results ; } | Query for features in the bounding box |
9,006 | public static double getToleranceDistance ( View view , GoogleMap map ) { BoundingBox boundingBox = getBoundingBox ( map ) ; double boundingBoxWidth = TileBoundingBoxMapUtils . getLongitudeDistance ( boundingBox ) ; double boundingBoxHeight = TileBoundingBoxMapUtils . getLatitudeDistance ( boundingBox ) ; int viewWidth = view . getWidth ( ) ; int viewHeight = view . getHeight ( ) ; double meters = 0 ; if ( viewWidth > 0 && viewHeight > 0 ) { double widthMeters = boundingBoxWidth / viewWidth ; double heightMeters = boundingBoxHeight / viewHeight ; meters = Math . min ( widthMeters , heightMeters ) ; } return meters ; } | Get the tolerance distance meters in the current region of the map |
9,007 | public static BoundingBox getBoundingBox ( GoogleMap map ) { LatLngBounds visibleBounds = map . getProjection ( ) . getVisibleRegion ( ) . latLngBounds ; LatLng southwest = visibleBounds . southwest ; LatLng northeast = visibleBounds . northeast ; double minLatitude = southwest . latitude ; double maxLatitude = northeast . latitude ; double minLongitude = southwest . longitude ; double maxLongitude = northeast . longitude ; if ( maxLongitude < minLongitude ) { maxLongitude += ( 2 * ProjectionConstants . WGS84_HALF_WORLD_LON_WIDTH ) ; } BoundingBox boundingBox = new BoundingBox ( minLongitude , minLatitude , maxLongitude , maxLatitude ) ; return boundingBox ; } | Get the WGS84 bounding box of the current map view screen . The max longitude will be larger than the min resulting in values larger than 180 . 0 . |
9,008 | public static BoundingBox buildClickBoundingBox ( LatLng latLng , View view , GoogleMap map , float screenClickPercentage ) { LatLngBoundingBox latLngBoundingBox = buildClickLatLngBoundingBox ( latLng , view , map , screenClickPercentage ) ; BoundingBox boundingBox = new BoundingBox ( latLngBoundingBox . getLeftCoordinate ( ) . longitude , latLngBoundingBox . getDownCoordinate ( ) . latitude , latLngBoundingBox . getRightCoordinate ( ) . longitude , latLngBoundingBox . getUpCoordinate ( ) . latitude ) ; return boundingBox ; } | Build a bounding box using the click location map view map and screen percentage tolerance . The bounding box can be used to query for features that were clicked |
9,009 | public static LatLngBounds buildClickLatLngBounds ( LatLng latLng , View view , GoogleMap map , float screenClickPercentage ) { LatLngBoundingBox latLngBoundingBox = buildClickLatLngBoundingBox ( latLng , view , map , screenClickPercentage ) ; double southWestLongitude = Math . min ( latLngBoundingBox . getLeftCoordinate ( ) . longitude , latLngBoundingBox . getDownCoordinate ( ) . longitude ) ; LatLng southWest = new LatLng ( latLngBoundingBox . getDownCoordinate ( ) . latitude , latLngBoundingBox . getLeftCoordinate ( ) . longitude ) ; LatLng northEast = new LatLng ( latLngBoundingBox . getUpCoordinate ( ) . latitude , latLngBoundingBox . getRightCoordinate ( ) . longitude ) ; LatLngBounds latLngBounds = new LatLngBounds ( southWest , northEast ) ; return latLngBounds ; } | Build a lat lng bounds using the click location map view map and screen percentage tolerance . The bounding box can be used to query for features that were clicked |
9,010 | public static double getToleranceDistance ( LatLng latLng , View view , GoogleMap map , float screenClickPercentage ) { LatLngBoundingBox latLngBoundingBox = buildClickLatLngBoundingBox ( latLng , view , map , screenClickPercentage ) ; double longitudeDistance = SphericalUtil . computeDistanceBetween ( latLngBoundingBox . getLeftCoordinate ( ) , latLngBoundingBox . getRightCoordinate ( ) ) ; double latitudeDistance = SphericalUtil . computeDistanceBetween ( latLngBoundingBox . getDownCoordinate ( ) , latLngBoundingBox . getUpCoordinate ( ) ) ; double distance = Math . max ( longitudeDistance , latitudeDistance ) ; return distance ; } | Get the allowable tolerance distance in meters from the click location on the map view and map with the screen percentage tolerance . |
9,011 | public static LatLngBoundingBox buildClickLatLngBoundingBox ( LatLng latLng , View view , GoogleMap map , float screenClickPercentage ) { int width = ( int ) Math . round ( view . getWidth ( ) * screenClickPercentage ) ; int height = ( int ) Math . round ( view . getHeight ( ) * screenClickPercentage ) ; Projection projection = map . getProjection ( ) ; android . graphics . Point clickLocation = projection . toScreenLocation ( latLng ) ; android . graphics . Point left = new android . graphics . Point ( clickLocation ) ; android . graphics . Point up = new android . graphics . Point ( clickLocation ) ; android . graphics . Point right = new android . graphics . Point ( clickLocation ) ; android . graphics . Point down = new android . graphics . Point ( clickLocation ) ; left . offset ( - width , 0 ) ; up . offset ( 0 , - height ) ; right . offset ( width , 0 ) ; down . offset ( 0 , height ) ; LatLng leftCoordinate = projection . fromScreenLocation ( left ) ; LatLng upCoordinate = projection . fromScreenLocation ( up ) ; LatLng rightCoordinate = projection . fromScreenLocation ( right ) ; LatLng downCoordinate = projection . fromScreenLocation ( down ) ; LatLngBoundingBox latLngBoundingBox = new LatLngBoundingBox ( leftCoordinate , upCoordinate , rightCoordinate , downCoordinate ) ; return latLngBoundingBox ; } | Build a lat lng bounding box using the click location map view map and screen percentage tolerance . The bounding box can be used to query for features that were clicked |
9,012 | public static boolean isPointOnShape ( LatLng point , GoogleMapShape shape , boolean geodesic , double tolerance ) { boolean onShape = false ; switch ( shape . getShapeType ( ) ) { case LAT_LNG : onShape = isPointNearPoint ( point , ( LatLng ) shape . getShape ( ) , tolerance ) ; break ; case MARKER_OPTIONS : onShape = isPointNearMarker ( point , ( MarkerOptions ) shape . getShape ( ) , tolerance ) ; break ; case POLYLINE_OPTIONS : onShape = isPointOnPolyline ( point , ( PolylineOptions ) shape . getShape ( ) , geodesic , tolerance ) ; break ; case POLYGON_OPTIONS : onShape = isPointOnPolygon ( point , ( PolygonOptions ) shape . getShape ( ) , geodesic , tolerance ) ; break ; case MULTI_LAT_LNG : onShape = isPointNearMultiLatLng ( point , ( MultiLatLng ) shape . getShape ( ) , tolerance ) ; break ; case MULTI_POLYLINE_OPTIONS : onShape = isPointOnMultiPolyline ( point , ( MultiPolylineOptions ) shape . getShape ( ) , geodesic , tolerance ) ; break ; case MULTI_POLYGON_OPTIONS : onShape = isPointOnMultiPolygon ( point , ( MultiPolygonOptions ) shape . getShape ( ) , geodesic , tolerance ) ; break ; case COLLECTION : @ SuppressWarnings ( "unchecked" ) List < GoogleMapShape > shapeList = ( List < GoogleMapShape > ) shape . getShape ( ) ; for ( GoogleMapShape shapeListItem : shapeList ) { onShape = isPointOnShape ( point , shapeListItem , geodesic , tolerance ) ; if ( onShape ) { break ; } } break ; default : throw new GeoPackageException ( "Unsupported Shape Type: " + shape . getShapeType ( ) ) ; } return onShape ; } | Is the point on or near the shape |
9,013 | public static boolean isPointNearMarker ( LatLng point , MarkerOptions shapeMarker , double tolerance ) { return isPointNearPoint ( point , shapeMarker . getPosition ( ) , tolerance ) ; } | Is the point near the shape marker |
9,014 | public static boolean isPointNearPoint ( LatLng point , LatLng shapePoint , double tolerance ) { return SphericalUtil . computeDistanceBetween ( point , shapePoint ) <= tolerance ; } | Is the point near the shape point |
9,015 | public static boolean isPointNearMultiLatLng ( LatLng point , MultiLatLng multiLatLng , double tolerance ) { boolean near = false ; for ( LatLng multiPoint : multiLatLng . getLatLngs ( ) ) { near = isPointNearPoint ( point , multiPoint , tolerance ) ; if ( near ) { break ; } } return near ; } | Is the point near any points in the multi lat lng |
9,016 | public static boolean isPointOnPolyline ( LatLng point , PolylineOptions polyline , boolean geodesic , double tolerance ) { return PolyUtil . isLocationOnPath ( point , polyline . getPoints ( ) , geodesic , tolerance ) ; } | Is the point on the polyline |
9,017 | public static boolean isPointOnMultiPolyline ( LatLng point , MultiPolylineOptions multiPolyline , boolean geodesic , double tolerance ) { boolean near = false ; for ( PolylineOptions polyline : multiPolyline . getPolylineOptions ( ) ) { near = isPointOnPolyline ( point , polyline , geodesic , tolerance ) ; if ( near ) { break ; } } return near ; } | Is the point on the multi polyline |
9,018 | public static boolean isPointOnPolygon ( LatLng point , PolygonOptions polygon , boolean geodesic , double tolerance ) { boolean onPolygon = PolyUtil . containsLocation ( point , polygon . getPoints ( ) , geodesic ) || PolyUtil . isLocationOnEdge ( point , polygon . getPoints ( ) , geodesic , tolerance ) ; if ( onPolygon ) { for ( List < LatLng > hole : polygon . getHoles ( ) ) { if ( PolyUtil . containsLocation ( point , hole , geodesic ) ) { onPolygon = false ; break ; } } } return onPolygon ; } | Is the point of the polygon |
9,019 | public static boolean isPointOnMultiPolygon ( LatLng point , MultiPolygonOptions multiPolygon , boolean geodesic , double tolerance ) { boolean near = false ; for ( PolygonOptions polygon : multiPolygon . getPolygonOptions ( ) ) { near = isPointOnPolygon ( point , polygon , geodesic , tolerance ) ; if ( near ) { break ; } } return near ; } | Is the point on the multi polygon |
9,020 | public Calendar getTime ( ) { Calendar result = Calendar . getInstance ( ) ; result . set ( Calendar . HOUR_OF_DAY , hour ) ; result . set ( Calendar . MINUTE , minute ) ; return result ; } | Gets the current time set in this TimeItem . |
9,021 | public static BoundedOverlay getBoundedOverlay ( TileDao tileDao , float density ) { BoundedOverlay overlay = null ; if ( tileDao . isGoogleTiles ( ) ) { overlay = new GoogleAPIGeoPackageOverlay ( tileDao ) ; } else { overlay = new GeoPackageOverlay ( tileDao , density ) ; } return overlay ; } | Get a Bounded Overlay Tile Provider for the Tile DAO with the display density |
9,022 | public static BoundedOverlay getBoundedOverlay ( TileDao tileDao , float density , TileScaling scaling ) { return new GeoPackageOverlay ( tileDao , density , scaling ) ; } | Get a Bounded Overlay Tile Provider for the Tile DAO with the display density and tile creator options |
9,023 | public static CompositeOverlay getCompositeOverlay ( TileDao tileDao , BoundedOverlay overlay ) { List < TileDao > tileDaos = new ArrayList < > ( ) ; tileDaos . add ( tileDao ) ; return getCompositeOverlay ( tileDaos , overlay ) ; } | Create a composite overlay by first adding a tile overlay for the tile DAO followed by the provided overlay |
9,024 | public static CompositeOverlay getCompositeOverlay ( Collection < TileDao > tileDaos , BoundedOverlay overlay ) { CompositeOverlay compositeOverlay = getCompositeOverlay ( tileDaos ) ; compositeOverlay . addOverlay ( overlay ) ; return compositeOverlay ; } | Create a composite overlay by first adding tile overlays for the tile DAOs followed by the provided overlay |
9,025 | public static CompositeOverlay getCompositeOverlay ( Collection < TileDao > tileDaos ) { CompositeOverlay compositeOverlay = new CompositeOverlay ( ) ; for ( TileDao tileDao : tileDaos ) { BoundedOverlay boundedOverlay = GeoPackageOverlayFactory . getBoundedOverlay ( tileDao ) ; compositeOverlay . addOverlay ( boundedOverlay ) ; } return compositeOverlay ; } | Create a composite overlay by adding tile overlays for the tile DAOs |
9,026 | public static BoundedOverlay getLinkedFeatureOverlay ( FeatureOverlay featureOverlay , GeoPackage geoPackage ) { BoundedOverlay overlay ; FeatureTileTableLinker linker = new FeatureTileTableLinker ( geoPackage ) ; List < TileDao > tileDaos = linker . getTileDaosForFeatureTable ( featureOverlay . getFeatureTiles ( ) . getFeatureDao ( ) . getTableName ( ) ) ; if ( ! tileDaos . isEmpty ( ) ) { overlay = getCompositeOverlay ( tileDaos , featureOverlay ) ; } else { overlay = featureOverlay ; } return overlay ; } | Create a composite overlay linking the feature overly with |
9,027 | public static Tile getTile ( GeoPackageTile geoPackageTile ) { Tile tile = null ; if ( geoPackageTile != null ) { tile = new Tile ( geoPackageTile . getWidth ( ) , geoPackageTile . getHeight ( ) , geoPackageTile . getData ( ) ) ; } return tile ; } | Get a map tile from the GeoPackage tile |
9,028 | public void projectGeometry ( GeoPackageGeometryData geometryData , Projection projection ) { if ( geometryData . getGeometry ( ) != null ) { try { SpatialReferenceSystemDao srsDao = DaoManager . createDao ( featureDao . getDb ( ) . getConnectionSource ( ) , SpatialReferenceSystem . class ) ; int srsId = geometryData . getSrsId ( ) ; SpatialReferenceSystem srs = srsDao . queryForId ( ( long ) srsId ) ; if ( ! projection . equals ( srs . getOrganization ( ) , srs . getOrganizationCoordsysId ( ) ) ) { Projection geomProjection = srs . getProjection ( ) ; ProjectionTransform transform = geomProjection . getTransformation ( projection ) ; Geometry projectedGeometry = transform . transform ( geometryData . getGeometry ( ) ) ; geometryData . setGeometry ( projectedGeometry ) ; SpatialReferenceSystem projectionSrs = srsDao . getOrCreateCode ( projection . getAuthority ( ) , Long . parseLong ( projection . getCode ( ) ) ) ; geometryData . setSrsId ( ( int ) projectionSrs . getSrsId ( ) ) ; } } catch ( SQLException e ) { throw new GeoPackageException ( "Failed to project geometry to projection with Authority: " + projection . getAuthority ( ) + ", Code: " + projection . getCode ( ) , e ) ; } } } | Project the geometry into the provided projection |
9,029 | private DataColumnsDao getDataColumnsDao ( ) { DataColumnsDao dataColumnsDao = null ; try { dataColumnsDao = DaoManager . createDao ( featureDao . getDb ( ) . getConnectionSource ( ) , DataColumns . class ) ; if ( ! dataColumnsDao . isTableExists ( ) ) { dataColumnsDao = null ; } } catch ( SQLException e ) { dataColumnsDao = null ; Log . e ( FeatureOverlayQuery . class . getSimpleName ( ) , "Failed to get a Data Columns DAO" , e ) ; } return dataColumnsDao ; } | Get a Data Columns DAO |
9,030 | private String getColumnName ( DataColumnsDao dataColumnsDao , FeatureRow featureRow , String columnName ) { String newColumnName = columnName ; if ( dataColumnsDao != null ) { try { DataColumns dataColumn = dataColumnsDao . getDataColumn ( featureRow . getTable ( ) . getTableName ( ) , columnName ) ; if ( dataColumn != null ) { newColumnName = dataColumn . getName ( ) ; } } catch ( SQLException e ) { Log . e ( FeatureOverlayQuery . class . getSimpleName ( ) , "Failed to search for Data Column name for column: " + columnName + ", Feature Table: " + featureRow . getTable ( ) . getTableName ( ) , e ) ; } } return newColumnName ; } | Get the column name by checking for a DataColumns name otherwise returns the provided column name |
9,031 | private FeatureIndexResults fineFilterResults ( FeatureIndexResults results , double tolerance , LatLng clickLocation ) { FeatureIndexResults filteredResults = null ; if ( ignoreGeometryTypes . contains ( geometryType ) ) { filteredResults = new FeatureIndexListResults ( ) ; } else if ( clickLocation == null && ignoreGeometryTypes . isEmpty ( ) ) { filteredResults = results ; } else { FeatureIndexListResults filteredListResults = new FeatureIndexListResults ( ) ; GoogleMapShapeConverter converter = new GoogleMapShapeConverter ( featureDao . getProjection ( ) ) ; for ( FeatureRow featureRow : results ) { GeoPackageGeometryData geomData = featureRow . getGeometry ( ) ; if ( geomData != null ) { Geometry geometry = geomData . getGeometry ( ) ; if ( geometry != null ) { if ( ! ignoreGeometryTypes . contains ( geometry . getGeometryType ( ) ) ) { if ( clickLocation != null ) { GoogleMapShape mapShape = converter . toShape ( geometry ) ; if ( MapUtils . isPointOnShape ( clickLocation , mapShape , geodesic , tolerance ) ) { filteredListResults . addRow ( featureRow ) ; } } else { filteredListResults . addRow ( featureRow ) ; } } } } } filteredResults = filteredListResults ; } return filteredResults ; } | Fine filter the index results verifying the click location is within the tolerance of each feature row |
9,032 | public boolean delete ( Marker marker ) { boolean deleted = false ; if ( contains ( marker ) ) { deleted = true ; ShapeMarkers shapeMarkers = shapeMarkersMap . remove ( marker . getId ( ) ) ; if ( shapeMarkers != null ) { shapeMarkers . delete ( marker ) ; } marker . remove ( ) ; } return deleted ; } | Get the shape markers for a marker only returns a value of shapes that can be edited |
9,033 | public static void addMarkerAsPolygon ( Marker marker , List < Marker > markers ) { LatLng position = marker . getPosition ( ) ; int insertLocation = markers . size ( ) ; if ( markers . size ( ) > 2 ) { double [ ] distances = new double [ markers . size ( ) ] ; insertLocation = 0 ; distances [ 0 ] = SphericalUtil . computeDistanceBetween ( position , markers . get ( 0 ) . getPosition ( ) ) ; for ( int i = 1 ; i < markers . size ( ) ; i ++ ) { distances [ i ] = SphericalUtil . computeDistanceBetween ( position , markers . get ( i ) . getPosition ( ) ) ; if ( distances [ i ] < distances [ insertLocation ] ) { insertLocation = i ; } } int beforeLocation = insertLocation > 0 ? insertLocation - 1 : distances . length - 1 ; int afterLocation = insertLocation < distances . length - 1 ? insertLocation + 1 : 0 ; if ( distances [ beforeLocation ] > distances [ afterLocation ] ) { insertLocation = afterLocation ; } } markers . add ( insertLocation , marker ) ; } | Polygon add a marker in the list of markers to where it is closest to the the surrounding points |
9,034 | public static MarkerOptions createMarkerOptions ( IconRow icon , float density , IconCache iconCache ) { MarkerOptions markerOptions = new MarkerOptions ( ) ; setIcon ( markerOptions , icon , density , iconCache ) ; return markerOptions ; } | Create new marker options populated with the icon |
9,035 | public static Bitmap createIcon ( IconRow icon , float density , IconCache iconCache ) { return iconCache . createIcon ( icon , density ) ; } | Create the icon bitmap |
9,036 | public static MarkerOptions createMarkerOptions ( StyleRow style ) { MarkerOptions markerOptions = new MarkerOptions ( ) ; setStyle ( markerOptions , style ) ; return markerOptions ; } | Create new marker options populated with the style |
9,037 | public static boolean setStyle ( MarkerOptions markerOptions , StyleRow style ) { boolean styleSet = false ; if ( style != null ) { Color color = style . getColorOrDefault ( ) ; float hue = color . getHue ( ) ; markerOptions . icon ( BitmapDescriptorFactory . defaultMarker ( hue ) ) ; styleSet = true ; } return styleSet ; } | Set the style into the marker options |
9,038 | public static PolylineOptions createPolylineOptions ( FeatureStyle featureStyle , float density ) { PolylineOptions polylineOptions = new PolylineOptions ( ) ; setFeatureStyle ( polylineOptions , featureStyle , density ) ; return polylineOptions ; } | Create new polyline options populated with the feature style |
9,039 | public static PolylineOptions createPolylineOptions ( StyleRow style , float density ) { PolylineOptions polylineOptions = new PolylineOptions ( ) ; setStyle ( polylineOptions , style , density ) ; return polylineOptions ; } | Create new polyline options populated with the style |
9,040 | public static PolygonOptions createPolygonOptions ( FeatureStyle featureStyle , float density ) { PolygonOptions polygonOptions = new PolygonOptions ( ) ; setFeatureStyle ( polygonOptions , featureStyle , density ) ; return polygonOptions ; } | Create new polygon options populated with the feature style |
9,041 | public static PolygonOptions createPolygonOptions ( StyleRow style , float density ) { PolygonOptions polygonOptions = new PolygonOptions ( ) ; setStyle ( polygonOptions , style , density ) ; return polygonOptions ; } | Create new polygon options populated with the style |
9,042 | public static double getLatitudeDistance ( double minLatitude , double maxLatitude ) { LatLng lowerMiddle = new LatLng ( minLatitude , 0 ) ; LatLng upperMiddle = new LatLng ( maxLatitude , 0 ) ; double latDistance = SphericalUtil . computeDistanceBetween ( lowerMiddle , upperMiddle ) ; return latDistance ; } | Get the latitude distance |
9,043 | private boolean isValid ( String request ) { String tmp = decodePercent ( request ) ; if ( tmp . indexOf ( '<' ) != - 1 || tmp . indexOf ( '>' ) != - 1 ) { return false ; } return true ; } | Validates request string for not containing malicious characters . |
9,044 | private List < String > diff ( Collection < String > first , Collection < String > second ) { final ArrayList < String > list = new ArrayList < String > ( first ) ; list . removeAll ( second ) ; return list ; } | Returns a list of elements in the first collection which are not present in the second collection |
9,045 | public Properties buildConsolidatedProperties ( ) throws IOException { Properties properties = new Properties ( ) ; for ( Resource r : constructResourceList ( ) ) { try ( InputStream is = r . getInputStream ( ) ) { properties . load ( is ) ; } } for ( String propertyName : System . getProperties ( ) . stringPropertyNames ( ) ) { properties . setProperty ( propertyName , System . getProperty ( propertyName ) ) ; } return properties ; } | This will realise the set of resources returned from |
9,046 | public void bind ( ServiceBindingDescriptor bindingDescriptor ) { String servicePlusMajorVersion = bindingDescriptor . getServiceName ( ) + "-v" + bindingDescriptor . getServiceVersion ( ) . getMajor ( ) ; if ( serviceBindingDescriptors . containsKey ( servicePlusMajorVersion ) ) { throw new PanicInTheCougar ( "More than one version of service [" + bindingDescriptor . getServiceName ( ) + "] is attempting to be bound for the same major version. The clashing versions are [" + serviceBindingDescriptors . get ( servicePlusMajorVersion ) . getServiceVersion ( ) + ", " + bindingDescriptor . getServiceVersion ( ) + "] - only one instance of a service is permissable for each major version" ) ; } serviceBindingDescriptors . put ( servicePlusMajorVersion , bindingDescriptor ) ; } | Adds the binding descriptor to a list for binding later . The actual binding occurs onCougarStart to be implemented by subclasses when it can be guaranteed that all services have been registered with the EV . |
9,047 | protected DehydratedExecutionContext resolveExecutionContext ( HttpCommand http , CredentialsContainer cc ) { return contextResolution . resolveExecutionContext ( protocol , http , cc ) ; } | Resolves an HttpCommand to an ExecutionContext which provides contextual information to the ExecutionVenue that the command will be executed in . |
9,048 | public void writeIdentity ( List < IdentityToken > tokens , IdentityTokenIOAdapter ioAdapter ) { if ( ioAdapter != null && ioAdapter . isRewriteSupported ( ) ) { ioAdapter . rewriteIdentityTokens ( tokens ) ; } } | Rewrites the caller s credentials back into the HTTP response . The main use case for this is rewriting SSO tokens which may change and the client needs to know the new value . |
9,049 | protected CougarException handleResponseWritingIOException ( Exception e , Class resultClass ) { String errorMessage = "Exception writing " + resultClass . getCanonicalName ( ) + " to http stream" ; IOException ioe = getIOException ( e ) ; if ( ioe == null ) { CougarException ce ; if ( e instanceof CougarException ) { ce = ( CougarException ) e ; } else { ce = new CougarFrameworkException ( errorMessage , e ) ; } return ce ; } incrementIoErrorsEncountered ( ) ; LOGGER . debug ( "Failed to marshall object of class {} to the output channel. Exception ({}) message is: {}" , resultClass . getCanonicalName ( ) , e . getClass ( ) . getCanonicalName ( ) , e . getMessage ( ) ) ; return new CougarServiceException ( ServerFaultCode . OutputChannelClosedCantWrite , errorMessage , e ) ; } | If an exception is received while writing a response to the client it might be because the that client has closed their connection . If so the problem should be ignored . |
9,050 | public static List < String > parse ( String address , String addresses ) { List < String > result ; if ( addresses == null || addresses . isEmpty ( ) ) { addresses = address ; } if ( addresses == null ) { result = Collections . emptyList ( ) ; } else { String [ ] parts = addresses . split ( "," ) ; result = new ArrayList < String > ( parts . length ) ; for ( String part : parts ) { part = part . trim ( ) ; if ( NetworkAddress . isValidIPAddress ( part ) ) { result . add ( part ) ; } } } return result ; } | Parse a comma separated string of ip addresses into a list Only valid IP address are returned in the list |
9,051 | public void introduceServiceToTransports ( Iterator < ? extends BindingDescriptorRegistrationListener > transports ) { while ( transports . hasNext ( ) ) { BindingDescriptorRegistrationListener t = transports . next ( ) ; boolean eventTransport = t instanceof EventTransport ; boolean includedEventTransport = false ; if ( eventTransport ) { if ( eventTransports != null && eventTransports . contains ( t ) ) { includedEventTransport = true ; } } if ( ! eventTransport || includedEventTransport ) { for ( BindingDescriptor bindingDescriptor : getBindingDescriptors ( ) ) { t . notify ( bindingDescriptor ) ; } } } } | Exports each binding descriptor to the supplied collection of transports |
9,052 | public static void resourceToFile ( String resourceName , File dest , Class src ) { InputStream is = null ; OutputStream os = null ; try { is = src . getClassLoader ( ) . getResourceAsStream ( resourceName ) ; if ( is == null ) { throw new RuntimeException ( "Could not load resource: " + resourceName ) ; } dest . getParentFile ( ) . mkdirs ( ) ; os = new FileOutputStream ( dest ) ; IOUtils . copy ( is , os ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error copying resource '" + resourceName + "' to file '" + dest . getPath ( ) + "': " + e , e ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( os ) ; } } | Copy the given resource to the given file . |
9,053 | private Node getNodeToBeReplaced ( Node parametersNode ) { Node toBeReplaced = null ; int responseCount = 0 ; NodeList childNodes = parametersNode . getChildNodes ( ) ; if ( childNodes != null ) { for ( int j = 0 ; j < childNodes . getLength ( ) ; j ++ ) { Node childNode = childNodes . item ( j ) ; String name = childNode . getLocalName ( ) ; if ( "simpleResponse" . equals ( name ) || "response" . equals ( name ) ) { responseCount ++ ; if ( "response" . equals ( name ) ) { toBeReplaced = childNode ; } } if ( responseCount > 1 ) { throw new IllegalArgumentException ( "Only one of either simpleResponse or response should define the response type" ) ; } } } return toBeReplaced ; } | Also ensures only one of the two has been defined |
9,054 | public void validate ( Document doc ) { try { doValidate ( doc ) ; } catch ( Exception e ) { throw new PluginException ( "Error validating document: " + e , e ) ; } } | Validate the given xmlDocument using any schemas specified in the document itself . |
9,055 | private void setBufferSizes ( HttpConfiguration buffers ) { if ( requestHeaderSize > 0 ) { LOGGER . info ( "Request header size set to {} for {}" , requestHeaderSize , buffers . getClass ( ) . getCanonicalName ( ) ) ; buffers . setRequestHeaderSize ( requestHeaderSize ) ; } if ( responseBufferSize > 0 ) { LOGGER . info ( "Response buffer size set to {} for {}" , responseBufferSize , buffers . getClass ( ) . getCanonicalName ( ) ) ; buffers . setOutputBufferSize ( responseBufferSize ) ; } if ( responseHeaderSize > 0 ) { LOGGER . info ( "Response header size set to {} for {}" , responseHeaderSize , buffers . getClass ( ) . getCanonicalName ( ) ) ; buffers . setResponseHeaderSize ( responseHeaderSize ) ; } } | Sets the request and header buffer sizex if they are not zero |
9,056 | public void registerHandler ( HttpServiceBindingDescriptor serviceBindingDescriptor ) { for ( ProtocolBinding protocolBinding : protocolBindingRegistry . getProtocolBindings ( ) ) { if ( protocolBinding . getProtocol ( ) == serviceBindingDescriptor . getServiceProtocol ( ) ) { String contextPath = protocolBinding . getContextRoot ( ) + serviceBindingDescriptor . getServiceContextPath ( ) ; JettyHandlerSpecification handlerSpec = handlerSpecificationMap . get ( contextPath ) ; if ( handlerSpec == null ) { handlerSpec = new JettyHandlerSpecification ( protocolBinding . getContextRoot ( ) , protocolBinding . getProtocol ( ) , serviceBindingDescriptor . getServiceContextPath ( ) ) ; handlerSpecificationMap . put ( contextPath , handlerSpec ) ; } if ( protocolBinding . getIdentityTokenResolver ( ) != null ) { handlerSpec . addServiceVersionToTokenResolverEntry ( serviceBindingDescriptor . getServiceVersion ( ) , protocolBinding . getIdentityTokenResolver ( ) ) ; } } } commandProcessorFactory . getCommandProcessor ( serviceBindingDescriptor . getServiceProtocol ( ) ) . bind ( serviceBindingDescriptor ) ; } | This method adds the service binding descriptor and all the appropriate protocol binding combos into the handlerSpecMap before binding the serviceBindingDescriptor to the appropriate command processor |
9,057 | public static java . security . cert . X509Certificate convert ( javax . security . cert . X509Certificate cert ) { try { byte [ ] encoded = cert . getEncoded ( ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( encoded ) ; java . security . cert . CertificateFactory cf = java . security . cert . CertificateFactory . getInstance ( "X.509" ) ; return ( java . security . cert . X509Certificate ) cf . generateCertificate ( bis ) ; } catch ( java . security . cert . CertificateEncodingException e ) { } catch ( javax . security . cert . CertificateEncodingException e ) { } catch ( java . security . cert . CertificateException e ) { } return null ; } | Converts to java . security |
9,058 | public static javax . security . cert . X509Certificate convert ( java . security . cert . X509Certificate cert ) { try { byte [ ] encoded = cert . getEncoded ( ) ; return javax . security . cert . X509Certificate . getInstance ( encoded ) ; } catch ( java . security . cert . CertificateEncodingException e ) { } catch ( javax . security . cert . CertificateEncodingException e ) { } catch ( javax . security . cert . CertificateException e ) { } return null ; } | Converts to javax . security |
9,059 | public void writeErrorResponse ( HttpCommand command , DehydratedExecutionContext context , CougarException error , boolean traceStarted ) { try { incrementErrorsWritten ( ) ; final HttpServletResponse response = command . getResponse ( ) ; try { long bytesWritten = 0 ; if ( error . getResponseCode ( ) != ResponseCode . CantWriteToSocket ) { ResponseCodeMapper . setResponseStatus ( response , error . getResponseCode ( ) ) ; ByteCountingOutputStream out = null ; try { int jsonErrorCode = mapServerFaultCodeToJsonErrorCode ( error . getServerFaultCode ( ) ) ; JsonRpcError rpcError = new JsonRpcError ( jsonErrorCode , error . getFault ( ) . getErrorCode ( ) , null ) ; JsonRpcErrorResponse jsonRpcErrorResponse = JsonRpcErrorResponse . buildErrorResponse ( null , rpcError ) ; out = new ByteCountingOutputStream ( response . getOutputStream ( ) ) ; mapper . writeValue ( out , jsonRpcErrorResponse ) ; bytesWritten = out . getCount ( ) ; } catch ( IOException ex ) { handleResponseWritingIOException ( ex , error . getClass ( ) ) ; } finally { closeStream ( out ) ; } } else { LOGGER . debug ( "Skipping error handling for a request where the output channel/socket has been prematurely closed" ) ; } logAccess ( command , resolveContextForErrorHandling ( context , command ) , - 1 , bytesWritten , MediaType . APPLICATION_JSON_TYPE , MediaType . APPLICATION_JSON_TYPE , error . getResponseCode ( ) ) ; } finally { command . onComplete ( ) ; } } finally { if ( context != null && traceStarted ) { tracer . end ( context . getRequestUUID ( ) ) ; } } } | Please note this should only be used when the JSON rpc call itself fails - the answer will not contain any mention of the requests that caused the failure nor their ID |
9,060 | public synchronized FutureTask < Boolean > start ( ) { this . sessionFactory . start ( ) ; if ( rpcTimeoutChecker != null ) { rpcTimeoutChecker . getThread ( ) . start ( ) ; } final FutureTask < Boolean > futureTask = new FutureTask < Boolean > ( new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { while ( ! ExecutionVenueNioClient . this . sessionFactory . isConnected ( ) ) { Thread . sleep ( 50 ) ; } return true ; } } ) ; final Thread thread = new Thread ( futureTask ) ; thread . setDaemon ( true ) ; thread . start ( ) ; return futureTask ; } | Starts the client |
9,061 | private synchronized void notifyConnectionLost ( final IoSession session ) { new Thread ( "Connection-Closed-Notifier" ) { public void run ( ) { if ( connectedObjectManager != null ) { connectedObjectManager . sessionTerminated ( session ) ; } for ( HandlerListener listener : handlerListeners ) { listener . sessionClosed ( session ) ; } RequestResponseManager requestResponseManager = ( RequestResponseManager ) session . getAttribute ( RequestResponseManager . SESSION_KEY ) ; if ( requestResponseManager != null ) { requestResponseManager . sessionClosed ( session ) ; } } } . start ( ) ; } | Notify all observers that comms are lost |
9,062 | public void process ( final T command ) { boolean traceStarted = false ; incrementCommandsProcessed ( ) ; DehydratedExecutionContext ctx = null ; try { validateCommand ( command ) ; CommandResolver < T > resolver = createCommandResolver ( command , tracer ) ; ctx = resolver . resolveExecutionContext ( ) ; List < ExecutionCommand > executionCommands = resolver . resolveExecutionCommands ( ) ; if ( executionCommands . size ( ) > 1 ) { throw new CougarFrameworkException ( "Resolved >1 command in a non-batch call!" ) ; } ExecutionCommand exec = executionCommands . get ( 0 ) ; tracer . start ( ctx . getRequestUUID ( ) , exec . getOperationKey ( ) ) ; traceStarted = true ; executeCommand ( exec , ctx ) ; } catch ( CougarException ce ) { executeError ( command , ctx , ce , traceStarted ) ; } catch ( Exception e ) { executeError ( command , ctx , new CougarFrameworkException ( "Unexpected exception while processing transport command" , e ) , traceStarted ) ; } } | Processes a TransportCommand . |
9,063 | protected void executeCommand ( final ExecutionCommand finalExec , final ExecutionContext finalCtx ) { executionsProcessed . incrementAndGet ( ) ; ev . execute ( finalCtx , finalExec . getOperationKey ( ) , finalExec . getArgs ( ) , finalExec , executor , finalExec . getTimeConstraints ( ) ) ; } | Execute the supplied command |
9,064 | public void subscribeToTimeTick ( ExecutionContext ctx , Object [ ] args , ExecutionObserver executionObserver ) { if ( getEventTransportIdentity ( ctx ) . getPrincipal ( ) . getName ( ) . equals ( SONIC_TRANSPORT_INSTANCE_ONE ) ) { this . timeTickPublishingObserver = executionObserver ; } } | Please note that this Service method is called by the Execution Venue to establish a communication channel from the transport to the Application to publish events . In essence the transport subscribes to the app so this method is called once for each publisher . The application should hold onto the passed in observer and call onResult on that observer to emit an event . |
9,065 | public void subscribeToMatchedBet ( ExecutionContext ctx , Object [ ] args , ExecutionObserver executionObserver ) { if ( getEventTransportIdentity ( ctx ) . getPrincipal ( ) . getName ( ) . equals ( SONIC_TRANSPORT_INSTANCE_ONE ) ) { this . matchedBetObserver = executionObserver ; } } | Please note that this Service method is called by the Execution Venue to establish a communication channel from the transport to the Application to publish events . In essence the transport subscribes to the app so this method is called once for each publisher at application initialisation . You should never be calling this directly . The application should hold onto the passed in observer and call onResult on that observer to emit an event . |
9,066 | public HttpCommandProcessor getCommandProcessor ( Protocol protocol ) { String commandProcessorName = commandProcessorNames . get ( protocol ) ; if ( commandProcessorName == null ) { throw new PanicInTheCougar ( "No HTTP Command Processor has been configured for protocol " + protocol ) ; } HttpCommandProcessor commandProcessor = ( HttpCommandProcessor ) applicationContext . getBean ( commandProcessorName ) ; if ( commandProcessor == null ) { throw new PanicInTheCougar ( "No HTTP Command Processor has been configured for the name " + commandProcessorName ) ; } return commandProcessor ; } | Returns the command processor assocated with the supplied protocol |
9,067 | public void publish ( Event event , String destinationName , EventServiceBindingDescriptor eventServiceBindingDescriptor ) throws CougarException { try { EventPublisherRunnable publisherRunnable = new EventPublisherRunnable ( event , destinationName , eventServiceBindingDescriptor ) ; threadPool . execute ( publisherRunnable ) ; publisherRunnable . lock ( ) ; if ( ! publisherRunnable . isSuccess ( ) ) { Exception e = publisherRunnable . getError ( ) ; LOGGER . error ( "Publication exception:" , e ) ; throw new CougarFrameworkException ( "Sonic JMS publication exception" , e ) ; } } catch ( InterruptedException ex ) { LOGGER . error ( "Publication exception:" , ex ) ; throw new CougarFrameworkException ( "Sonic JMS publication exception" , ex ) ; } } | Publish the supplied event to the destination . The event will be published using a thread from the pool and its associated jms session |
9,068 | public Future < Boolean > requestConnectionToBroker ( ) { FutureTask futureTask = new FutureTask ( new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { boolean ok = false ; try { getConnection ( ) ; ok = true ; } catch ( JMSException e ) { LOGGER . warn ( "Error connecting to JMS" , e ) ; } return ok ; } } ) ; reconnectorService . schedule ( futureTask , 0 , TimeUnit . SECONDS ) ; return futureTask ; } | Requests that this transports attempts to connect to the broker . Occurs asynchronously from the caller initiation . |
9,069 | private boolean isDefinitelyCougarResponse ( CougarHttpResponse response ) { String ident = response . getServerIdentity ( ) ; if ( ident != null && ident . contains ( "Cougar 2" ) ) { return true ; } return false ; } | has the responding server identified itself as Cougar |
9,070 | public void setSamplingLevel ( int samplingLevel ) { if ( samplingLevel >= MIN_LEVEL && samplingLevel <= MAX_LEVEL ) { this . samplingLevel = samplingLevel ; } else { throw new IllegalArgumentException ( "Sampling level " + samplingLevel + " is not in the range [" + MIN_LEVEL + ";" + MAX_LEVEL + "[" ) ; } } | Sets a new sampling level . The sampling level must be within the range 0 - 1000 representing the permillage of requests to be sampled . Setting the sampling level to 0 disabled sampling . |
9,071 | public static long getRandomLong ( ) { byte [ ] rndBytes = new byte [ 8 ] ; SECURE_RANDOM_TL . get ( ) . nextBytes ( rndBytes ) ; return ByteBuffer . wrap ( rndBytes ) . getLong ( ) ; } | Retrieves a newly generated random long . |
9,072 | public List < String > getHeapsForSession ( IoSession session ) { List < String > ret = new ArrayList < String > ( ) ; try { subTermLock . lock ( ) ; Multiset < String > s = heapsByClient . get ( session ) ; if ( s != null ) { ret . addAll ( s . keySet ( ) ) ; } } finally { subTermLock . unlock ( ) ; } return ret ; } | used for monitoring |
9,073 | private HeapState processHeapStateCreation ( final ConnectedResponse result , final String heapUri ) { if ( ! subTermLock . isHeldByCurrentThread ( ) ) { throw new IllegalStateException ( "You must have the subTermLock before calling this method" ) ; } final HeapState newState = new HeapState ( result . getHeap ( ) ) ; newState . getUpdateLock ( ) . lock ( ) ; UpdateProducingHeapListener listener = new UpdateProducingHeapListener ( ) { protected void doUpdate ( Update u ) { if ( u . getActions ( ) . size ( ) > 0 ) { newState . getQueuedChanges ( ) . add ( new QueuedHeapChange ( u ) ) ; if ( u . getActions ( ) . contains ( TerminateHeap . INSTANCE ) ) { newState . getQueuedChanges ( ) . add ( new HeapTermination ( ) ) ; } heapsWaitingForUpdate . add ( heapUri ) ; } } } ; newState . setHeapListener ( listener ) ; result . getHeap ( ) . addListener ( listener , false ) ; heapStates . put ( heapUri , newState ) ; heapUris . put ( newState . getHeapId ( ) , heapUri ) ; return newState ; } | note you must have the subterm lock before calling this method |
9,074 | public void terminateSubscription ( IoSession session , String heapUri , String subscriptionId , Subscription . CloseReason reason ) { Lock heapUpdateLock = null ; try { HeapState state = heapStates . get ( heapUri ) ; if ( state != null ) { heapUpdateLock = state . getUpdateLock ( ) ; heapUpdateLock . lock ( ) ; } subTermLock . lock ( ) ; if ( state != null ) { if ( ! state . isTerminated ( ) ) { state . terminateSubscription ( session , subscriptionId , reason ) ; if ( reason == REQUESTED_BY_PUBLISHER || reason == Subscription . CloseReason . REQUESTED_BY_PUBLISHER_ADMINISTRATOR ) { try { nioLogger . log ( NioLogger . LoggingLevel . TRANSPORT , session , "Notifying client that publisher has terminated subscription %s" , subscriptionId ) ; NioUtils . writeEventMessageToSession ( session , new TerminateSubscription ( state . getHeapId ( ) , subscriptionId , reason . name ( ) ) , objectIOFactory ) ; } catch ( Exception e ) { LOGGER . info ( "Error occurred whilst trying to inform client of subscription termination" , e ) ; nioLogger . log ( NioLogger . LoggingLevel . SESSION , session , "Error occurred whilst trying to inform client of subscription termination, closing session" ) ; session . close ( ) ; } } if ( state . hasSubscriptions ( ) ) { terminateSubscriptions ( heapUri , reason ) ; } else if ( state . getSubscriptions ( session ) . isEmpty ( ) ) { terminateSubscriptions ( session , heapUri , reason ) ; } } } Multiset < String > heapsForSession = heapsByClient . get ( session ) ; if ( heapsForSession != null ) { heapsForSession . remove ( heapUri ) ; if ( heapsForSession . isEmpty ( ) ) { terminateSubscriptions ( session , reason ) ; } } } finally { subTermLock . unlock ( ) ; if ( heapUpdateLock != null ) { heapUpdateLock . unlock ( ) ; } } } | Terminates a single subscription to a single heap |
9,075 | private void terminateSubscriptions ( IoSession session , Subscription . CloseReason reason ) { Multiset < String > heapsForThisClient ; try { subTermLock . lock ( ) ; heapsForThisClient = heapsByClient . remove ( session ) ; } finally { subTermLock . unlock ( ) ; } if ( heapsForThisClient != null ) { for ( String s : heapsForThisClient . keySet ( ) ) { terminateSubscriptions ( session , s , reason ) ; } } } | Terminates all subscriptions for a given client |
9,076 | private void terminateSubscriptions ( String heapUri , Subscription . CloseReason reason ) { HeapState state = heapStates . get ( heapUri ) ; if ( state != null ) { try { state . getUpdateLock ( ) . lock ( ) ; subTermLock . lock ( ) ; if ( ! state . isTerminated ( ) ) { heapStates . remove ( heapUri ) ; heapUris . remove ( state . getHeapId ( ) ) ; List < IoSession > sessions = state . getSessions ( ) ; for ( IoSession session : sessions ) { terminateSubscriptions ( session , state , heapUri , reason ) ; } LOGGER . error ( "Terminating heap state '{}'" , heapUri ) ; state . terminate ( ) ; state . removeListener ( ) ; } } finally { subTermLock . unlock ( ) ; state . getUpdateLock ( ) . unlock ( ) ; } } } | Terminates all subscriptions for a given heap |
9,077 | private static int [ ] pad ( int [ ] list ) { double m = list . length / ( double ) WORD_LENGTH ; int size = ( int ) Math . ceil ( m ) ; int [ ] ret = new int [ size * WORD_LENGTH ] ; Arrays . fill ( ret , 0 ) ; System . arraycopy ( list , 0 , ret , 0 , list . length ) ; return ret ; } | Increases the array size to a multiple of WORD_LENGTH |
9,078 | public static int [ ] listToMap ( int [ ] list ) { list = pad ( list ) ; int [ ] bitMap = new int [ ( int ) ( list . length / WORD_LENGTH ) ] ; Arrays . fill ( bitMap , 0 ) ; int j = - 1 ; for ( int i = 0 ; i < list . length ; i ++ ) { if ( i % WORD_LENGTH == 0 ) { j ++ ; } bitMap [ j ] |= ( list [ i ] << ( ( WORD_LENGTH - 1 ) - ( i % WORD_LENGTH ) ) ) ; } return bitMap ; } | Builds a bit map from the given list . The list should values of 0 or 1s |
9,079 | public static int [ ] mapToList ( int [ ] bitMap ) { int [ ] list = new int [ ( int ) ( bitMap . length * WORD_LENGTH ) ] ; Arrays . fill ( list , 0 ) ; int j = - 1 ; for ( int i = 0 ; i < list . length ; i ++ ) { if ( i % WORD_LENGTH == 0 ) { j ++ ; } list [ i ] = ( bitMap [ j ] & ( 1 << ( ( WORD_LENGTH - 1 ) - ( i % WORD_LENGTH ) ) ) ) == 0 ? 0 : 1 ; } return list ; } | Builds a list from the given bit map . The list will contain values of 0 or 1s |
9,080 | private Object toEnum ( ParameterType parameterType , String enumTextValue , String paramName , boolean hardFailEnumDeserialisation ) { try { return EnumUtils . readEnum ( parameterType . getImplementationClass ( ) , enumTextValue , hardFailEnumDeserialisation ) ; } catch ( Exception e ) { throw XMLTranscriptionInput . exceptionDuringDeserialisation ( parameterType , paramName , e , false ) ; } } | Deserialise enums explicitly |
9,081 | private void processService ( Service service ) throws Exception { getLog ( ) . info ( " Service: " + service . getServiceName ( ) ) ; Document iddDoc = parseIddFile ( service . getServiceName ( ) ) ; if ( ! isOffline ( ) ) { getLog ( ) . debug ( "Validating XML.." ) ; new XmlValidator ( resolver ) . validate ( iddDoc ) ; } generateJavaCode ( service , iddDoc ) ; } | Various steps needing to be done for each IDD |
9,082 | private void initOutputDir ( File outputDir ) { if ( ! outputDir . exists ( ) ) { if ( ! outputDir . mkdirs ( ) ) { throw new IllegalArgumentException ( "Output Directory " + outputDir + " could not be created" ) ; } } if ( ! outputDir . isDirectory ( ) || ( ! outputDir . canWrite ( ) ) ) { throw new IllegalArgumentException ( "Output Directory " + outputDir + " is not a directory or cannot be written to." ) ; } } | Set up and validate the creation of the specified output directory |
9,083 | private String readNamespaceAttr ( Document doc ) { if ( namespaceExpr == null ) { namespaceExpr = initNamespaceAttrExpression ( ) ; } String s ; try { s = namespaceExpr . evaluate ( doc ) ; } catch ( XPathExpressionException e ) { throw new PluginException ( "Error evaluating namespace XPath expression: " + e , e ) ; } return ( s == null || s . length ( ) == 0 ) ? null : s ; } | Retrieve namespace attr of interface definition or null if not found |
9,084 | public static boolean isValidIPAddress ( String networkAddress ) { if ( networkAddress != null ) { String [ ] split = networkAddress . split ( "\\." ) ; if ( split . length == 4 ) { int [ ] octets = new int [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { try { octets [ i ] = Integer . parseInt ( split [ i ] ) ; } catch ( NumberFormatException e ) { return false ; } if ( octets [ i ] < 0 || octets [ i ] > 255 ) { return false ; } } return true ; } } return false ; } | Verify if a given string is a valid dotted quad notation IP Address |
9,085 | private static byte [ ] parseDottedQuad ( String address ) { String [ ] splitString = address . split ( "\\." ) ; if ( splitString . length == 4 ) { int [ ] ints = new int [ 4 ] ; byte [ ] bytes = new byte [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { ints [ i ] = Integer . parseInt ( splitString [ i ] ) ; if ( ints [ i ] < 0 || ints [ i ] > 255 ) { throw new IllegalArgumentException ( "Invalid ip4Address or netmask" ) ; } bytes [ i ] = toByte ( ints [ i ] ) ; } return bytes ; } else { throw new IllegalArgumentException ( "Address must be in dotted quad notation" ) ; } } | parse ip4 address as dotted quad notation into bytes |
9,086 | public static final Set fromMap ( Map map , Object ... keys ) { if ( keys != null && map != null ) { Set answer = new HashSet ( ) ; for ( Object key : keys ) { if ( map . containsKey ( key ) ) { answer . add ( map . get ( key ) ) ; } } return Collections . unmodifiableSet ( answer ) ; } return Collections . EMPTY_SET ; } | Given a map and a set of keys return a set containing the values referred - to by the keys . If the map is null or the keys are null the EMPTY_SET is returned . If a passed key does not exist in the map nothing is added to the set . However if the key is present and maps to null null is added to the set . |
9,087 | public static final Set < String > fromCommaSeparatedValues ( String csv ) { if ( csv == null || csv . isEmpty ( ) ) { return Collections . EMPTY_SET ; } String [ ] tokens = csv . split ( "," ) ; return new HashSet < String > ( Arrays . asList ( tokens ) ) ; } | Given a comma - separated list of values return a set of those values . If the passed string is null the EMPTY_SET is returned . If the passed string is empty the EMPTY_SET is returned . |
9,088 | private void mergeExtensionsIntoDocument ( Node target , Node extensions ) throws Exception { final XPathFactory factory = XPathFactory . newInstance ( ) ; final NodeList nodes = ( NodeList ) factory . newXPath ( ) . evaluate ( "//extensions" , extensions , XPathConstants . NODESET ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { final Node extensionNode = nodes . item ( i ) ; String nameBasedXpath = DomUtils . getNameBasedXPath ( extensionNode , false ) ; log . debug ( "Processing extension node: " + nameBasedXpath ) ; final NodeList targetNodes = ( NodeList ) factory . newXPath ( ) . evaluate ( nameBasedXpath , target , XPathConstants . NODESET ) ; if ( targetNodes . getLength ( ) != 1 ) { throw new IllegalArgumentException ( "XPath " + nameBasedXpath + " not found in target" ) ; } Node targetNode = targetNodes . item ( 0 ) ; Node importedNode = targetNode . getOwnerDocument ( ) . importNode ( extensionNode , true ) ; targetNode . appendChild ( importedNode ) ; } } | Weave the extensions defined in the extensions doc into the target . |
9,089 | private void removeUndefinedOperations ( Node target , Node extensions ) throws Exception { final XPathFactory factory = XPathFactory . newInstance ( ) ; final NodeList nodes = ( NodeList ) factory . newXPath ( ) . evaluate ( "//operation" , target , XPathConstants . NODESET ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { final Node targetNode = nodes . item ( i ) ; String nameBasedXpath = DomUtils . getNameBasedXPath ( targetNode , true ) ; log . debug ( "Checking operation: " + nameBasedXpath ) ; final NodeList targetNodes = ( NodeList ) factory . newXPath ( ) . evaluate ( nameBasedXpath , extensions , XPathConstants . NODESET ) ; if ( targetNodes . getLength ( ) == 0 ) { log . debug ( "Ignoring IDL defined operation: " + getAttribute ( targetNode , "name" ) ) ; targetNode . getParentNode ( ) . removeChild ( targetNode ) ; } } } | Cycle through the target Node and remove any operations not defined in the extensions document . |
9,090 | public Map < String , Set < ServiceDefinition > > getNamespaceServiceDefinitionMap ( ) { Map < String , Set < ServiceDefinition > > namespaceServiceDefinitionMap = new HashMap < String , Set < ServiceDefinition > > ( ) ; for ( String namespace : serviceImplementationMap . keySet ( ) ) { Set < ServiceDefinition > serviceDefinitions = new HashSet < ServiceDefinition > ( ) ; namespaceServiceDefinitionMap . put ( namespace , serviceDefinitions ) ; for ( ServiceDefinition sd : serviceImplementationMap . get ( namespace ) . keySet ( ) ) { serviceDefinitions . add ( sd ) ; } } return Collections . unmodifiableMap ( namespaceServiceDefinitionMap ) ; } | This method returns an unmodifiable map between each namespace and the set of serviceDefinitions bound to that namespace . Note that by default the namespace is null so there could be a null namespace with services enumerated within |
9,091 | public Set < SocketAddress > getCurrentSessionAddresses ( ) { Set < SocketAddress > result = new HashSet < SocketAddress > ( ) ; synchronized ( lock ) { result . addAll ( sessions . keySet ( ) ) ; result . addAll ( pendingConnections . keySet ( ) ) ; } return result ; } | Returns a list of all server socket addresses to which sessions are already established or being established |
9,092 | public IoSession getSession ( ) { synchronized ( lock ) { if ( sessions . isEmpty ( ) ) { return null ; } else { final Object [ ] keys = sessions . keySet ( ) . toArray ( ) ; for ( int i = 0 ; i < sessions . size ( ) ; i ++ ) { counter ++ ; final int pos = Math . abs ( counter % sessions . size ( ) ) ; final IoSession session = sessions . get ( keys [ pos ] ) ; if ( isAvailable ( session ) ) { return session ; } } return null ; } } } | Rotates via list of currently established sessions |
9,093 | public void openSession ( SocketAddress endpoint ) { synchronized ( lock ) { if ( ! pendingConnections . containsKey ( endpoint ) ) { final ReconnectTask task = new ReconnectTask ( endpoint ) ; pendingConnections . put ( endpoint , task ) ; this . reconnectExecutor . submit ( task ) ; } } } | Open a new session to the specified address . If session is being opened does nothing |
9,094 | public void closeSession ( SocketAddress endpoint , boolean reconnect ) { synchronized ( lock ) { if ( pendingConnections . containsKey ( endpoint ) ) { final ReconnectTask task = pendingConnections . get ( endpoint ) ; if ( task != null ) { task . stop ( ) ; } } else { final IoSession ioSession = sessions . get ( endpoint ) ; if ( ioSession != null ) { close ( ioSession , reconnect ) ; } } } } | If there is an active session to the specified endpoint it will be closed If not the reconnection task for the endpoint will be stopped |
9,095 | public final String getMessage ( ) { String additional = additionalInfo ( ) ; return additional == null ? super . getMessage ( ) : super . getMessage ( ) + ": " + additional ; } | Prevent defined services overriding the exception message |
9,096 | public List < String > listClasses ( ) throws WMIException { List < String > wmiClasses = new ArrayList < String > ( ) ; String rawData ; try { rawData = getWMIStub ( ) . listClasses ( this . namespace , this . computerName ) ; String [ ] dataStringLines = rawData . split ( NEWLINE_REGEX ) ; for ( String line : dataStringLines ) { if ( ! line . isEmpty ( ) && ! line . startsWith ( "_" ) ) { String [ ] infos = line . split ( SPACE_REGEX ) ; wmiClasses . addAll ( Arrays . asList ( infos ) ) ; } } Set < String > hs = new HashSet < String > ( ) ; hs . addAll ( wmiClasses ) ; wmiClasses . clear ( ) ; wmiClasses . addAll ( hs ) ; } catch ( Exception ex ) { Logger . getLogger ( WMI4Java . class . getName ( ) ) . log ( Level . SEVERE , GENERIC_ERROR_MSG , ex ) ; throw new WMIException ( ex ) ; } return wmiClasses ; } | Query and list the WMI classes |
9,097 | public List < String > listProperties ( String wmiClass ) throws WMIException { List < String > foundPropertiesList = new ArrayList < String > ( ) ; try { String rawData = getWMIStub ( ) . listProperties ( wmiClass , this . namespace , this . computerName ) ; String [ ] dataStringLines = rawData . split ( NEWLINE_REGEX ) ; for ( final String line : dataStringLines ) { if ( ! line . isEmpty ( ) ) { foundPropertiesList . add ( line . trim ( ) ) ; } } List < String > notAllowed = Arrays . asList ( new String [ ] { "Equals" , "GetHashCode" , "GetType" , "ToString" } ) ; foundPropertiesList . removeAll ( notAllowed ) ; } catch ( Exception ex ) { Logger . getLogger ( WMI4Java . class . getName ( ) ) . log ( Level . SEVERE , GENERIC_ERROR_MSG , ex ) ; throw new WMIException ( ex ) ; } return foundPropertiesList ; } | Query a WMI class and return all the available properties |
9,098 | public String getRawWMIObjectOutput ( String wmiClass ) throws WMIException { String rawData ; try { if ( this . properties != null || this . filters != null ) { rawData = getWMIStub ( ) . queryObject ( wmiClass , this . properties , this . filters , this . namespace , this . computerName ) ; } else { rawData = getWMIStub ( ) . listObject ( wmiClass , this . namespace , this . computerName ) ; } } catch ( WMIException ex ) { Logger . getLogger ( WMI4Java . class . getName ( ) ) . log ( Level . SEVERE , GENERIC_ERROR_MSG , ex ) ; throw new WMIException ( ex ) ; } return rawData ; } | Query all the raw object data for an specific class |
9,099 | public SF readStructuredField ( ) throws IOException { int buf = 0 ; long thisOffset = offset ; if ( leadingLengthBytes == - 1 ) { int leadingLength = 0 ; do { buf = read ( ) ; offset ++ ; leadingLength ++ ; } while ( ( buf & 0xff ) != 0x5a && buf != - 1 && leadingLength < 5 ) ; if ( ( buf & 0xff ) != 0x5a ) { has5a = false ; leadingLength = 1 ; offset = 2 ; buf = read ( ) ; if ( buf == - 1 ) return null ; if ( ( buf & 0xff ) != 0xd3 ) { throw new IOException ( "cannot find 5a magic byte nor d3 -> this is no AFP" ) ; } offset = 0 ; } leadingLengthBytes = leadingLength - 1 ; } else { if ( leadingLengthBytes > 0 ) read ( data , 0 , leadingLengthBytes ) ; if ( has5a ) { buf = read ( ) ; offset ++ ; } } if ( buf == - 1 ) { return null ; } if ( has5a && ( buf & 0xff ) != 0x5a ) { throw new IOException ( "cannot find 5a magic byte" ) ; } data [ 0 ] = 0x5a ; buf = read ( ) ; offset ++ ; if ( buf == - 1 && ! has5a ) { return null ; } if ( buf == - 1 ) { throw new IOException ( "premature end of file." ) ; } data [ 1 ] = ( byte ) ( buf & 0xff ) ; length = ( byte ) buf << 8 ; buf = read ( ) ; offset ++ ; if ( buf == - 1 ) throw new IOException ( "premature end of file." ) ; data [ 2 ] = ( byte ) ( buf & 0xff ) ; length |= ( byte ) buf & 0xff ; length -= 2 ; if ( length > data . length ) throw new IOException ( "length of structured field is too large: " + length ) ; int read = read ( data , 3 , length ) ; offset += read ; if ( read < length ) throw new IOException ( "premature end of file." ) ; SF sf = factory . sf ( data , 0 , getLength ( ) + 2 ) ; sf . setLength ( length + 3 ) ; sf . setOffset ( thisOffset ) ; sf . setNumber ( number ++ ) ; return sf ; } | Reads a new structured field from the input stream . This method is not thread - safe! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.