repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.getToleranceDistance
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; }
java
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; }
[ "public", "static", "double", "getToleranceDistance", "(", "LatLng", "latLng", ",", "View", "view", ",", "GoogleMap", "map", ",", "float", "screenClickPercentage", ")", "{", "LatLngBoundingBox", "latLngBoundingBox", "=", "buildClickLatLngBoundingBox", "(", "latLng", "...
Get the allowable tolerance distance in meters from the click location on the map view and map with the screen percentage tolerance. @param latLng click location @param view map view @param map map @param screenClickPercentage screen click percentage between 0.0 and 1.0 for how close a feature on the screen must be to be included in a click query @return tolerance distance in meters
[ "Get", "the", "allowable", "tolerance", "distance", "in", "meters", "from", "the", "click", "location", "on", "the", "map", "view", "and", "map", "with", "the", "screen", "percentage", "tolerance", "." ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L162-L172
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.buildClickLatLngBoundingBox
public static LatLngBoundingBox buildClickLatLngBoundingBox(LatLng latLng, View view, GoogleMap map, float screenClickPercentage) { // Get the screen width and height a click occurs from a feature int width = (int) Math.round(view.getWidth() * screenClickPercentage); int height = (int) Math.round(view.getHeight() * screenClickPercentage); // Get the screen click location Projection projection = map.getProjection(); android.graphics.Point clickLocation = projection.toScreenLocation(latLng); // Get the screen click locations in each width or height direction 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); // Get the coordinates of the bounding box points 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; }
java
public static LatLngBoundingBox buildClickLatLngBoundingBox(LatLng latLng, View view, GoogleMap map, float screenClickPercentage) { // Get the screen width and height a click occurs from a feature int width = (int) Math.round(view.getWidth() * screenClickPercentage); int height = (int) Math.round(view.getHeight() * screenClickPercentage); // Get the screen click location Projection projection = map.getProjection(); android.graphics.Point clickLocation = projection.toScreenLocation(latLng); // Get the screen click locations in each width or height direction 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); // Get the coordinates of the bounding box points 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; }
[ "public", "static", "LatLngBoundingBox", "buildClickLatLngBoundingBox", "(", "LatLng", "latLng", ",", "View", "view", ",", "GoogleMap", "map", ",", "float", "screenClickPercentage", ")", "{", "// Get the screen width and height a click occurs from a feature", "int", "width", ...
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 @param latLng click location @param view map view @param map map @param screenClickPercentage screen click percentage between 0.0 and 1.0 for how close a feature on the screen must be to be included in a click query @return lat lng bounding box
[ "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", "cli...
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L185-L214
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointOnShape
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; }
java
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; }
[ "public", "static", "boolean", "isPointOnShape", "(", "LatLng", "point", ",", "GoogleMapShape", "shape", ",", "boolean", "geodesic", ",", "double", "tolerance", ")", "{", "boolean", "onShape", "=", "false", ";", "switch", "(", "shape", ".", "getShapeType", "("...
Is the point on or near the shape @param point lat lng point @param shape map shape @param geodesic geodesic check flag @param tolerance distance tolerance @return true if point is on shape
[ "Is", "the", "point", "on", "or", "near", "the", "shape" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L225-L271
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointNearMarker
public static boolean isPointNearMarker(LatLng point, MarkerOptions shapeMarker, double tolerance) { return isPointNearPoint(point, shapeMarker.getPosition(), tolerance); }
java
public static boolean isPointNearMarker(LatLng point, MarkerOptions shapeMarker, double tolerance) { return isPointNearPoint(point, shapeMarker.getPosition(), tolerance); }
[ "public", "static", "boolean", "isPointNearMarker", "(", "LatLng", "point", ",", "MarkerOptions", "shapeMarker", ",", "double", "tolerance", ")", "{", "return", "isPointNearPoint", "(", "point", ",", "shapeMarker", ".", "getPosition", "(", ")", ",", "tolerance", ...
Is the point near the shape marker @param point point @param shapeMarker shape marker @param tolerance distance tolerance @return true if near
[ "Is", "the", "point", "near", "the", "shape", "marker" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L281-L283
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointNearPoint
public static boolean isPointNearPoint(LatLng point, LatLng shapePoint, double tolerance) { return SphericalUtil.computeDistanceBetween(point, shapePoint) <= tolerance; }
java
public static boolean isPointNearPoint(LatLng point, LatLng shapePoint, double tolerance) { return SphericalUtil.computeDistanceBetween(point, shapePoint) <= tolerance; }
[ "public", "static", "boolean", "isPointNearPoint", "(", "LatLng", "point", ",", "LatLng", "shapePoint", ",", "double", "tolerance", ")", "{", "return", "SphericalUtil", ".", "computeDistanceBetween", "(", "point", ",", "shapePoint", ")", "<=", "tolerance", ";", ...
Is the point near the shape point @param point point @param shapePoint shape point @param tolerance distance tolerance @return true if near
[ "Is", "the", "point", "near", "the", "shape", "point" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L293-L295
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointNearMultiLatLng
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; }
java
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; }
[ "public", "static", "boolean", "isPointNearMultiLatLng", "(", "LatLng", "point", ",", "MultiLatLng", "multiLatLng", ",", "double", "tolerance", ")", "{", "boolean", "near", "=", "false", ";", "for", "(", "LatLng", "multiPoint", ":", "multiLatLng", ".", "getLatLn...
Is the point near any points in the multi lat lng @param point point @param multiLatLng multi lat lng @param tolerance distance tolerance @return true if near
[ "Is", "the", "point", "near", "any", "points", "in", "the", "multi", "lat", "lng" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L305-L314
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointOnPolyline
public static boolean isPointOnPolyline(LatLng point, PolylineOptions polyline, boolean geodesic, double tolerance) { return PolyUtil.isLocationOnPath(point, polyline.getPoints(), geodesic, tolerance); }
java
public static boolean isPointOnPolyline(LatLng point, PolylineOptions polyline, boolean geodesic, double tolerance) { return PolyUtil.isLocationOnPath(point, polyline.getPoints(), geodesic, tolerance); }
[ "public", "static", "boolean", "isPointOnPolyline", "(", "LatLng", "point", ",", "PolylineOptions", "polyline", ",", "boolean", "geodesic", ",", "double", "tolerance", ")", "{", "return", "PolyUtil", ".", "isLocationOnPath", "(", "point", ",", "polyline", ".", "...
Is the point on the polyline @param point point @param polyline polyline @param geodesic geodesic check flag @param tolerance distance tolerance @return true if on the line
[ "Is", "the", "point", "on", "the", "polyline" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L325-L327
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointOnMultiPolyline
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; }
java
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; }
[ "public", "static", "boolean", "isPointOnMultiPolyline", "(", "LatLng", "point", ",", "MultiPolylineOptions", "multiPolyline", ",", "boolean", "geodesic", ",", "double", "tolerance", ")", "{", "boolean", "near", "=", "false", ";", "for", "(", "PolylineOptions", "p...
Is the point on the multi polyline @param point point @param multiPolyline multi polyline @param geodesic geodesic check flag @param tolerance distance tolerance @return true if on the multi line
[ "Is", "the", "point", "on", "the", "multi", "polyline" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L338-L347
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointOnPolygon
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; }
java
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; }
[ "public", "static", "boolean", "isPointOnPolygon", "(", "LatLng", "point", ",", "PolygonOptions", "polygon", ",", "boolean", "geodesic", ",", "double", "tolerance", ")", "{", "boolean", "onPolygon", "=", "PolyUtil", ".", "containsLocation", "(", "point", ",", "p...
Is the point of the polygon @param point point @param polygon polygon @param geodesic geodesic check flag @param tolerance distance tolerance @return true if on the polygon
[ "Is", "the", "point", "of", "the", "polygon" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L358-L373
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.isPointOnMultiPolygon
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; }
java
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; }
[ "public", "static", "boolean", "isPointOnMultiPolygon", "(", "LatLng", "point", ",", "MultiPolygonOptions", "multiPolygon", ",", "boolean", "geodesic", ",", "double", "tolerance", ")", "{", "boolean", "near", "=", "false", ";", "for", "(", "PolygonOptions", "polyg...
Is the point on the multi polygon @param point point @param multiPolygon multi polygon @param geodesic geodesic check flag @param tolerance distance tolerance @return true if on the multi polygon
[ "Is", "the", "point", "on", "the", "multi", "polygon" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L384-L393
train
SimplicityApks/ReminderDatePicker
lib/src/main/java/com/simplicityapks/reminderdatepicker/lib/TimeItem.java
TimeItem.getTime
public Calendar getTime() { Calendar result = Calendar.getInstance(); result.set(Calendar.HOUR_OF_DAY, hour); result.set(Calendar.MINUTE, minute); return result; }
java
public Calendar getTime() { Calendar result = Calendar.getInstance(); result.set(Calendar.HOUR_OF_DAY, hour); result.set(Calendar.MINUTE, minute); return result; }
[ "public", "Calendar", "getTime", "(", ")", "{", "Calendar", "result", "=", "Calendar", ".", "getInstance", "(", ")", ";", "result", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "hour", ")", ";", "result", ".", "set", "(", "Calendar", ".", "MIN...
Gets the current time set in this TimeItem. @return A new Calendar containing the time.
[ "Gets", "the", "current", "time", "set", "in", "this", "TimeItem", "." ]
7596fbac77a5d26f687fec11758935a2b7db156f
https://github.com/SimplicityApks/ReminderDatePicker/blob/7596fbac77a5d26f687fec11758935a2b7db156f/lib/src/main/java/com/simplicityapks/reminderdatepicker/lib/TimeItem.java#L69-L74
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getBoundedOverlay
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; }
java
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; }
[ "public", "static", "BoundedOverlay", "getBoundedOverlay", "(", "TileDao", "tileDao", ",", "float", "density", ")", "{", "BoundedOverlay", "overlay", "=", "null", ";", "if", "(", "tileDao", ".", "isGoogleTiles", "(", ")", ")", "{", "overlay", "=", "new", "Go...
Get a Bounded Overlay Tile Provider for the Tile DAO with the display density @param tileDao tile dao @param density display density: {@link android.util.DisplayMetrics#density} @return bounded overlay @since 3.2.0
[ "Get", "a", "Bounded", "Overlay", "Tile", "Provider", "for", "the", "Tile", "DAO", "with", "the", "display", "density" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L73-L84
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getBoundedOverlay
public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density, TileScaling scaling) { return new GeoPackageOverlay(tileDao, density, scaling); }
java
public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density, TileScaling scaling) { return new GeoPackageOverlay(tileDao, density, scaling); }
[ "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 @param tileDao tile dao @param density display density: {@link android.util.DisplayMetrics#density} @param scaling tile scaling options @return bounded overlay @since 3.2.0
[ "Get", "a", "Bounded", "Overlay", "Tile", "Provider", "for", "the", "Tile", "DAO", "with", "the", "display", "density", "and", "tile", "creator", "options" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L107-L109
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getCompositeOverlay
public static CompositeOverlay getCompositeOverlay(TileDao tileDao, BoundedOverlay overlay) { List<TileDao> tileDaos = new ArrayList<>(); tileDaos.add(tileDao); return getCompositeOverlay(tileDaos, overlay); }
java
public static CompositeOverlay getCompositeOverlay(TileDao tileDao, BoundedOverlay overlay) { List<TileDao> tileDaos = new ArrayList<>(); tileDaos.add(tileDao); return getCompositeOverlay(tileDaos, overlay); }
[ "public", "static", "CompositeOverlay", "getCompositeOverlay", "(", "TileDao", "tileDao", ",", "BoundedOverlay", "overlay", ")", "{", "List", "<", "TileDao", ">", "tileDaos", "=", "new", "ArrayList", "<>", "(", ")", ";", "tileDaos", ".", "add", "(", "tileDao",...
Create a composite overlay by first adding a tile overlay for the tile DAO followed by the provided overlay @param tileDao tile dao @param overlay bounded overlay @return composite overlay
[ "Create", "a", "composite", "overlay", "by", "first", "adding", "a", "tile", "overlay", "for", "the", "tile", "DAO", "followed", "by", "the", "provided", "overlay" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L118-L122
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getCompositeOverlay
public static CompositeOverlay getCompositeOverlay(Collection<TileDao> tileDaos, BoundedOverlay overlay) { CompositeOverlay compositeOverlay = getCompositeOverlay(tileDaos); compositeOverlay.addOverlay(overlay); return compositeOverlay; }
java
public static CompositeOverlay getCompositeOverlay(Collection<TileDao> tileDaos, BoundedOverlay overlay) { CompositeOverlay compositeOverlay = getCompositeOverlay(tileDaos); compositeOverlay.addOverlay(overlay); return compositeOverlay; }
[ "public", "static", "CompositeOverlay", "getCompositeOverlay", "(", "Collection", "<", "TileDao", ">", "tileDaos", ",", "BoundedOverlay", "overlay", ")", "{", "CompositeOverlay", "compositeOverlay", "=", "getCompositeOverlay", "(", "tileDaos", ")", ";", "compositeOverla...
Create a composite overlay by first adding tile overlays for the tile DAOs followed by the provided overlay @param tileDaos collection of tile daos @param overlay bounded overlay @return composite overlay
[ "Create", "a", "composite", "overlay", "by", "first", "adding", "tile", "overlays", "for", "the", "tile", "DAOs", "followed", "by", "the", "provided", "overlay" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L131-L138
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getCompositeOverlay
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; }
java
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; }
[ "public", "static", "CompositeOverlay", "getCompositeOverlay", "(", "Collection", "<", "TileDao", ">", "tileDaos", ")", "{", "CompositeOverlay", "compositeOverlay", "=", "new", "CompositeOverlay", "(", ")", ";", "for", "(", "TileDao", "tileDao", ":", "tileDaos", "...
Create a composite overlay by adding tile overlays for the tile DAOs @param tileDaos collection of tile daos @return composite overlay
[ "Create", "a", "composite", "overlay", "by", "adding", "tile", "overlays", "for", "the", "tile", "DAOs" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L146-L156
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getLinkedFeatureOverlay
public static BoundedOverlay getLinkedFeatureOverlay(FeatureOverlay featureOverlay, GeoPackage geoPackage) { BoundedOverlay overlay; // Get the linked tile daos FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage); List<TileDao> tileDaos = linker.getTileDaosForFeatureTable(featureOverlay.getFeatureTiles().getFeatureDao().getTableName()); if (!tileDaos.isEmpty()) { // Create a composite overlay to search for existing tiles before drawing from features overlay = getCompositeOverlay(tileDaos, featureOverlay); } else { overlay = featureOverlay; } return overlay; }
java
public static BoundedOverlay getLinkedFeatureOverlay(FeatureOverlay featureOverlay, GeoPackage geoPackage) { BoundedOverlay overlay; // Get the linked tile daos FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage); List<TileDao> tileDaos = linker.getTileDaosForFeatureTable(featureOverlay.getFeatureTiles().getFeatureDao().getTableName()); if (!tileDaos.isEmpty()) { // Create a composite overlay to search for existing tiles before drawing from features overlay = getCompositeOverlay(tileDaos, featureOverlay); } else { overlay = featureOverlay; } return overlay; }
[ "public", "static", "BoundedOverlay", "getLinkedFeatureOverlay", "(", "FeatureOverlay", "featureOverlay", ",", "GeoPackage", "geoPackage", ")", "{", "BoundedOverlay", "overlay", ";", "// Get the linked tile daos", "FeatureTileTableLinker", "linker", "=", "new", "FeatureTileTa...
Create a composite overlay linking the feature overly with @param featureOverlay feature overlay @param geoPackage GeoPackage @return linked bounded overlay
[ "Create", "a", "composite", "overlay", "linking", "the", "feature", "overly", "with" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L165-L181
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java
GeoPackageOverlayFactory.getTile
public static Tile getTile(GeoPackageTile geoPackageTile) { Tile tile = null; if (geoPackageTile != null) { tile = new Tile(geoPackageTile.getWidth(), geoPackageTile.getHeight(), geoPackageTile.getData()); } return tile; }
java
public static Tile getTile(GeoPackageTile geoPackageTile) { Tile tile = null; if (geoPackageTile != null) { tile = new Tile(geoPackageTile.getWidth(), geoPackageTile.getHeight(), geoPackageTile.getData()); } return tile; }
[ "public", "static", "Tile", "getTile", "(", "GeoPackageTile", "geoPackageTile", ")", "{", "Tile", "tile", "=", "null", ";", "if", "(", "geoPackageTile", "!=", "null", ")", "{", "tile", "=", "new", "Tile", "(", "geoPackageTile", ".", "getWidth", "(", ")", ...
Get a map tile from the GeoPackage tile @param geoPackageTile GeoPackage tile @return tile
[ "Get", "a", "map", "tile", "from", "the", "GeoPackage", "tile" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L190-L196
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java
FeatureInfoBuilder.projectGeometry
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); } } }
java
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); } } }
[ "public", "void", "projectGeometry", "(", "GeoPackageGeometryData", "geometryData", ",", "Projection", "projection", ")", "{", "if", "(", "geometryData", ".", "getGeometry", "(", ")", "!=", "null", ")", "{", "try", "{", "SpatialReferenceSystemDao", "srsDao", "=", ...
Project the geometry into the provided projection @param geometryData geometry data @param projection projection
[ "Project", "the", "geometry", "into", "the", "provided", "projection" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L528-L553
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java
FeatureInfoBuilder.getDataColumnsDao
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; }
java
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; }
[ "private", "DataColumnsDao", "getDataColumnsDao", "(", ")", "{", "DataColumnsDao", "dataColumnsDao", "=", "null", ";", "try", "{", "dataColumnsDao", "=", "DaoManager", ".", "createDao", "(", "featureDao", ".", "getDb", "(", ")", ".", "getConnectionSource", "(", ...
Get a Data Columns DAO @return data columns dao
[ "Get", "a", "Data", "Columns", "DAO" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L560-L572
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java
FeatureInfoBuilder.getColumnName
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; }
java
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; }
[ "private", "String", "getColumnName", "(", "DataColumnsDao", "dataColumnsDao", ",", "FeatureRow", "featureRow", ",", "String", "columnName", ")", "{", "String", "newColumnName", "=", "columnName", ";", "if", "(", "dataColumnsDao", "!=", "null", ")", "{", "try", ...
Get the column name by checking for a DataColumns name, otherwise returns the provided column name @param dataColumnsDao data columns dao @param featureRow feature row @param columnName column name @return column name
[ "Get", "the", "column", "name", "by", "checking", "for", "a", "DataColumns", "name", "otherwise", "returns", "the", "provided", "column", "name" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L582-L600
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java
FeatureInfoBuilder.fineFilterResults
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; }
java
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; }
[ "private", "FeatureIndexResults", "fineFilterResults", "(", "FeatureIndexResults", "results", ",", "double", "tolerance", ",", "LatLng", "clickLocation", ")", "{", "FeatureIndexResults", "filteredResults", "=", "null", ";", "if", "(", "ignoreGeometryTypes", ".", "contai...
Fine filter the index results verifying the click location is within the tolerance of each feature row @param results feature index results @param tolerance distance tolerance @param clickLocation click location @return filtered feature index results
[ "Fine", "filter", "the", "index", "results", "verifying", "the", "click", "location", "is", "within", "the", "tolerance", "of", "each", "feature", "row" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L610-L655
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeMarkers.java
GoogleMapShapeMarkers.delete
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; }
java
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; }
[ "public", "boolean", "delete", "(", "Marker", "marker", ")", "{", "boolean", "deleted", "=", "false", ";", "if", "(", "contains", "(", "marker", ")", ")", "{", "deleted", "=", "true", ";", "ShapeMarkers", "shapeMarkers", "=", "shapeMarkersMap", ".", "remov...
Get the shape markers for a marker, only returns a value of shapes that can be edited @param marker marker @return deleted flag
[ "Get", "the", "shape", "markers", "for", "a", "marker", "only", "returns", "a", "value", "of", "shapes", "that", "can", "be", "edited" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeMarkers.java#L166-L177
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeMarkers.java
GoogleMapShapeMarkers.addMarkerAsPolygon
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); }
java
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); }
[ "public", "static", "void", "addMarkerAsPolygon", "(", "Marker", "marker", ",", "List", "<", "Marker", ">", "markers", ")", "{", "LatLng", "position", "=", "marker", ".", "getPosition", "(", ")", ";", "int", "insertLocation", "=", "markers", ".", "size", "...
Polygon add a marker in the list of markers to where it is closest to the the surrounding points @param marker marker @param markers list of markers
[ "Polygon", "add", "a", "marker", "in", "the", "list", "of", "markers", "to", "where", "it", "is", "closest", "to", "the", "the", "surrounding", "points" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeMarkers.java#L217-L244
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createMarkerOptions
public static MarkerOptions createMarkerOptions(IconRow icon, float density, IconCache iconCache) { MarkerOptions markerOptions = new MarkerOptions(); setIcon(markerOptions, icon, density, iconCache); return markerOptions; }
java
public static MarkerOptions createMarkerOptions(IconRow icon, float density, IconCache iconCache) { MarkerOptions markerOptions = new MarkerOptions(); setIcon(markerOptions, icon, density, iconCache); return markerOptions; }
[ "public", "static", "MarkerOptions", "createMarkerOptions", "(", "IconRow", "icon", ",", "float", "density", ",", "IconCache", "iconCache", ")", "{", "MarkerOptions", "markerOptions", "=", "new", "MarkerOptions", "(", ")", ";", "setIcon", "(", "markerOptions", ","...
Create new marker options populated with the icon @param icon icon row @param density display density: {@link android.util.DisplayMetrics#density} @param iconCache icon cache @return marker options populated with the icon
[ "Create", "new", "marker", "options", "populated", "with", "the", "icon" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L235-L241
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createIcon
public static Bitmap createIcon(IconRow icon, float density, IconCache iconCache) { return iconCache.createIcon(icon, density); }
java
public static Bitmap createIcon(IconRow icon, float density, IconCache iconCache) { return iconCache.createIcon(icon, density); }
[ "public", "static", "Bitmap", "createIcon", "(", "IconRow", "icon", ",", "float", "density", ",", "IconCache", "iconCache", ")", "{", "return", "iconCache", ".", "createIcon", "(", "icon", ",", "density", ")", ";", "}" ]
Create the icon bitmap @param icon icon row @param density display density: {@link android.util.DisplayMetrics#density} @param iconCache icon cache @return icon bitmap
[ "Create", "the", "icon", "bitmap" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L303-L305
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createMarkerOptions
public static MarkerOptions createMarkerOptions(StyleRow style) { MarkerOptions markerOptions = new MarkerOptions(); setStyle(markerOptions, style); return markerOptions; }
java
public static MarkerOptions createMarkerOptions(StyleRow style) { MarkerOptions markerOptions = new MarkerOptions(); setStyle(markerOptions, style); return markerOptions; }
[ "public", "static", "MarkerOptions", "createMarkerOptions", "(", "StyleRow", "style", ")", "{", "MarkerOptions", "markerOptions", "=", "new", "MarkerOptions", "(", ")", ";", "setStyle", "(", "markerOptions", ",", "style", ")", ";", "return", "markerOptions", ";", ...
Create new marker options populated with the style @param style style row @return marker options populated with the style
[ "Create", "new", "marker", "options", "populated", "with", "the", "style" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L313-L319
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setStyle
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; }
java
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; }
[ "public", "static", "boolean", "setStyle", "(", "MarkerOptions", "markerOptions", ",", "StyleRow", "style", ")", "{", "boolean", "styleSet", "=", "false", ";", "if", "(", "style", "!=", "null", ")", "{", "Color", "color", "=", "style", ".", "getColorOrDefaul...
Set the style into the marker options @param markerOptions marker options @param style style row @return true if style was set into the marker options
[ "Set", "the", "style", "into", "the", "marker", "options" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L328-L340
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createPolylineOptions
public static PolylineOptions createPolylineOptions(FeatureStyle featureStyle, float density) { PolylineOptions polylineOptions = new PolylineOptions(); setFeatureStyle(polylineOptions, featureStyle, density); return polylineOptions; }
java
public static PolylineOptions createPolylineOptions(FeatureStyle featureStyle, float density) { PolylineOptions polylineOptions = new PolylineOptions(); setFeatureStyle(polylineOptions, featureStyle, density); return polylineOptions; }
[ "public", "static", "PolylineOptions", "createPolylineOptions", "(", "FeatureStyle", "featureStyle", ",", "float", "density", ")", "{", "PolylineOptions", "polylineOptions", "=", "new", "PolylineOptions", "(", ")", ";", "setFeatureStyle", "(", "polylineOptions", ",", ...
Create new polyline options populated with the feature style @param featureStyle feature style @param density display density: {@link android.util.DisplayMetrics#density} @return polyline options populated with the feature style
[ "Create", "new", "polyline", "options", "populated", "with", "the", "feature", "style" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L413-L419
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createPolylineOptions
public static PolylineOptions createPolylineOptions(StyleRow style, float density) { PolylineOptions polylineOptions = new PolylineOptions(); setStyle(polylineOptions, style, density); return polylineOptions; }
java
public static PolylineOptions createPolylineOptions(StyleRow style, float density) { PolylineOptions polylineOptions = new PolylineOptions(); setStyle(polylineOptions, style, density); return polylineOptions; }
[ "public", "static", "PolylineOptions", "createPolylineOptions", "(", "StyleRow", "style", ",", "float", "density", ")", "{", "PolylineOptions", "polylineOptions", "=", "new", "PolylineOptions", "(", ")", ";", "setStyle", "(", "polylineOptions", ",", "style", ",", ...
Create new polyline options populated with the style @param style style row @param density display density: {@link android.util.DisplayMetrics#density} @return polyline options populated with the style
[ "Create", "new", "polyline", "options", "populated", "with", "the", "style" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L449-L455
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createPolygonOptions
public static PolygonOptions createPolygonOptions(FeatureStyle featureStyle, float density) { PolygonOptions polygonOptions = new PolygonOptions(); setFeatureStyle(polygonOptions, featureStyle, density); return polygonOptions; }
java
public static PolygonOptions createPolygonOptions(FeatureStyle featureStyle, float density) { PolygonOptions polygonOptions = new PolygonOptions(); setFeatureStyle(polygonOptions, featureStyle, density); return polygonOptions; }
[ "public", "static", "PolygonOptions", "createPolygonOptions", "(", "FeatureStyle", "featureStyle", ",", "float", "density", ")", "{", "PolygonOptions", "polygonOptions", "=", "new", "PolygonOptions", "(", ")", ";", "setFeatureStyle", "(", "polygonOptions", ",", "featu...
Create new polygon options populated with the feature style @param featureStyle feature style @param density display density: {@link android.util.DisplayMetrics#density} @return polygon options populated with the feature style
[ "Create", "new", "polygon", "options", "populated", "with", "the", "feature", "style" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L551-L557
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createPolygonOptions
public static PolygonOptions createPolygonOptions(StyleRow style, float density) { PolygonOptions polygonOptions = new PolygonOptions(); setStyle(polygonOptions, style, density); return polygonOptions; }
java
public static PolygonOptions createPolygonOptions(StyleRow style, float density) { PolygonOptions polygonOptions = new PolygonOptions(); setStyle(polygonOptions, style, density); return polygonOptions; }
[ "public", "static", "PolygonOptions", "createPolygonOptions", "(", "StyleRow", "style", ",", "float", "density", ")", "{", "PolygonOptions", "polygonOptions", "=", "new", "PolygonOptions", "(", ")", ";", "setStyle", "(", "polygonOptions", ",", "style", ",", "densi...
Create new polygon options populated with the style @param style style row @param density display density: {@link android.util.DisplayMetrics#density} @return polygon options populated with the style
[ "Create", "new", "polygon", "options", "populated", "with", "the", "style" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L587-L593
train
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/TileBoundingBoxMapUtils.java
TileBoundingBoxMapUtils.getLatitudeDistance
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; }
java
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; }
[ "public", "static", "double", "getLatitudeDistance", "(", "double", "minLatitude", ",", "double", "maxLatitude", ")", "{", "LatLng", "lowerMiddle", "=", "new", "LatLng", "(", "minLatitude", ",", "0", ")", ";", "LatLng", "upperMiddle", "=", "new", "LatLng", "("...
Get the latitude distance @param minLatitude min latitude @param maxLatitude max latitude @return distance
[ "Get", "the", "latitude", "distance" ]
634d78468a5c52d2bc98791cc7ff03981ebf573b
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/TileBoundingBoxMapUtils.java#L86-L93
train
betfair/cougar
cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/jmx/HtmlAdaptorParser.java
HtmlAdaptorParser.isValid
private boolean isValid(String request) { String tmp = decodePercent(request); if(tmp.indexOf('<') != -1 || tmp.indexOf('>') != -1 ) { return false; } return true; }
java
private boolean isValid(String request) { String tmp = decodePercent(request); if(tmp.indexOf('<') != -1 || tmp.indexOf('>') != -1 ) { return false; } return true; }
[ "private", "boolean", "isValid", "(", "String", "request", ")", "{", "String", "tmp", "=", "decodePercent", "(", "request", ")", ";", "if", "(", "tmp", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", "||", "tmp", ".", "indexOf", "(", "'", "'", ...
Validates request string for not containing malicious characters. @param request a request string @return true - if request string is valid, false - otherwise
[ "Validates", "request", "string", "for", "not", "containing", "malicious", "characters", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/jmx/HtmlAdaptorParser.java#L218-L227
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/SessionRecycler.java
SessionRecycler.diff
private List<String> diff(Collection<String> first, Collection<String> second) { final ArrayList<String> list = new ArrayList<String>(first); list.removeAll(second); return list; }
java
private List<String> diff(Collection<String> first, Collection<String> second) { final ArrayList<String> list = new ArrayList<String>(first); list.removeAll(second); return list; }
[ "private", "List", "<", "String", ">", "diff", "(", "Collection", "<", "String", ">", "first", ",", "Collection", "<", "String", ">", "second", ")", "{", "final", "ArrayList", "<", "String", ">", "list", "=", "new", "ArrayList", "<", "String", ">", "("...
Returns a list of elements in the first collection which are not present in the second collection @param first First collection @param second Second collection @return Difference between the two collections
[ "Returns", "a", "list", "of", "elements", "in", "the", "first", "collection", "which", "are", "not", "present", "in", "the", "second", "collection" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/SessionRecycler.java#L147-L151
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/PropertyLoader.java
PropertyLoader.buildConsolidatedProperties
public Properties buildConsolidatedProperties() throws IOException { //Cannot use the spring classes here because they a) use the logger early, which //scuppers log4j and b) they're designed to do bean value overriding - not to be //used directly in this fashion Properties properties = new Properties(); //Read them from the list of resources then mix in System for (Resource r : constructResourceList()) { try (InputStream is = r.getInputStream()) { properties.load(is); } } //System for (String propertyName : System.getProperties().stringPropertyNames()) { properties.setProperty(propertyName, System.getProperty(propertyName)); } return properties; }
java
public Properties buildConsolidatedProperties() throws IOException { //Cannot use the spring classes here because they a) use the logger early, which //scuppers log4j and b) they're designed to do bean value overriding - not to be //used directly in this fashion Properties properties = new Properties(); //Read them from the list of resources then mix in System for (Resource r : constructResourceList()) { try (InputStream is = r.getInputStream()) { properties.load(is); } } //System for (String propertyName : System.getProperties().stringPropertyNames()) { properties.setProperty(propertyName, System.getProperty(propertyName)); } return properties; }
[ "public", "Properties", "buildConsolidatedProperties", "(", ")", "throws", "IOException", "{", "//Cannot use the spring classes here because they a) use the logger early, which", "//scuppers log4j and b) they're designed to do bean value overriding - not to be", "//used directly in this fashion"...
This will realise the set of resources returned from @see constructResourcesList and as a fully populated properties object, including System properties @return returns a fully populated Properties object with values from the config, the override and the System (in that order of precedence) @throws IOException
[ "This", "will", "realise", "the", "set", "of", "resources", "returned", "from" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/PropertyLoader.java#L61-L78
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java
AbstractHttpCommandProcessor.bind
@Override 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); }
java
@Override 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); }
[ "@", "Override", "public", "void", "bind", "(", "ServiceBindingDescriptor", "bindingDescriptor", ")", "{", "String", "servicePlusMajorVersion", "=", "bindingDescriptor", ".", "getServiceName", "(", ")", "+", "\"-v\"", "+", "bindingDescriptor", ".", "getServiceVersion", ...
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.
[ "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",...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java#L158-L171
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java
AbstractHttpCommandProcessor.resolveExecutionContext
protected DehydratedExecutionContext resolveExecutionContext(HttpCommand http, CredentialsContainer cc) { return contextResolution.resolveExecutionContext(protocol, http, cc); }
java
protected DehydratedExecutionContext resolveExecutionContext(HttpCommand http, CredentialsContainer cc) { return contextResolution.resolveExecutionContext(protocol, http, cc); }
[ "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. @param http contains the HttpServletRequest from which the contextual information is derived @return the ExecutionContext, populated with information from the HttpCommend
[ "Resolves", "an", "HttpCommand", "to", "an", "ExecutionContext", "which", "provides", "contextual", "information", "to", "the", "ExecutionVenue", "that", "the", "command", "will", "be", "executed", "in", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java#L254-L256
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java
AbstractHttpCommandProcessor.writeIdentity
public void writeIdentity(List<IdentityToken> tokens, IdentityTokenIOAdapter ioAdapter) { if (ioAdapter != null && ioAdapter.isRewriteSupported()) { ioAdapter.rewriteIdentityTokens(tokens); } }
java
public void writeIdentity(List<IdentityToken> tokens, IdentityTokenIOAdapter ioAdapter) { if (ioAdapter != null && ioAdapter.isRewriteSupported()) { ioAdapter.rewriteIdentityTokens(tokens); } }
[ "public", "void", "writeIdentity", "(", "List", "<", "IdentityToken", ">", "tokens", ",", "IdentityTokenIOAdapter", "ioAdapter", ")", "{", "if", "(", "ioAdapter", "!=", "null", "&&", "ioAdapter", ".", "isRewriteSupported", "(", ")", ")", "{", "ioAdapter", ".",...
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. @param tokens - the identity tokens to marshall @param ioAdapter - the adapter to detail with the transport specific IO requirements
[ "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"...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java#L270-L274
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java
AbstractHttpCommandProcessor.handleResponseWritingIOException
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; } //We arrive here when the output pipe is broken. Broken network connections are not //really exceptional and should not be reported by dumping the stack trace. //Instead a summary debug level log message with some relevant info 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); }
java
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; } //We arrive here when the output pipe is broken. Broken network connections are not //really exceptional and should not be reported by dumping the stack trace. //Instead a summary debug level log message with some relevant info 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); }
[ "protected", "CougarException", "handleResponseWritingIOException", "(", "Exception", "e", ",", "Class", "resultClass", ")", "{", "String", "errorMessage", "=", "\"Exception writing \"", "+", "resultClass", ".", "getCanonicalName", "(", ")", "+", "\" to http stream\"", ...
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.
[ "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", "igno...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java#L280-L304
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/geolocation/RemoteAddressUtils.java
RemoteAddressUtils.parse
public static List<String> parse(String address, String addresses) { List<String> result; // backwards compatibility - older clients only send a single address in the single address header and don't supply the multi-address header 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; }
java
public static List<String> parse(String address, String addresses) { List<String> result; // backwards compatibility - older clients only send a single address in the single address header and don't supply the multi-address header 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; }
[ "public", "static", "List", "<", "String", ">", "parse", "(", "String", "address", ",", "String", "addresses", ")", "{", "List", "<", "String", ">", "result", ";", "// backwards compatibility - older clients only send a single address in the single address header and don't ...
Parse a comma separated string of ip addresses into a list Only valid IP address are returned in the list
[ "Parse", "a", "comma", "separated", "string", "of", "ip", "addresses", "into", "a", "list", "Only", "valid", "IP", "address", "are", "returned", "in", "the", "list" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/geolocation/RemoteAddressUtils.java#L102-L122
train
betfair/cougar
cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/ev/ServiceRegistration.java
ServiceRegistration.introduceServiceToTransports
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 it's an event transport then we only want to notify if we've been told that the developer wanted to // bind to this particular transport (since you can have >1 instance of the event transport currently) if (eventTransports != null && eventTransports.contains(t)) { includedEventTransport = true; } } if (!eventTransport || includedEventTransport) { for (BindingDescriptor bindingDescriptor : getBindingDescriptors()) { t.notify(bindingDescriptor); } } } }
java
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 it's an event transport then we only want to notify if we've been told that the developer wanted to // bind to this particular transport (since you can have >1 instance of the event transport currently) if (eventTransports != null && eventTransports.contains(t)) { includedEventTransport = true; } } if (!eventTransport || includedEventTransport) { for (BindingDescriptor bindingDescriptor : getBindingDescriptors()) { t.notify(bindingDescriptor); } } } }
[ "public", "void", "introduceServiceToTransports", "(", "Iterator", "<", "?", "extends", "BindingDescriptorRegistrationListener", ">", "transports", ")", "{", "while", "(", "transports", ".", "hasNext", "(", ")", ")", "{", "BindingDescriptorRegistrationListener", "t", ...
Exports each binding descriptor to the supplied collection of transports @param transports
[ "Exports", "each", "binding", "descriptor", "to", "the", "supplied", "collection", "of", "transports" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/ev/ServiceRegistration.java#L58-L76
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java
FileUtil.resourceToFile
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); } }
java
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); } }
[ "public", "static", "void", "resourceToFile", "(", "String", "resourceName", ",", "File", "dest", ",", "Class", "src", ")", "{", "InputStream", "is", "=", "null", ";", "OutputStream", "os", "=", "null", ";", "try", "{", "is", "=", "src", ".", "getClassLo...
Copy the given resource to the given file. @param resourceName name of resource to copy @param destination file
[ "Copy", "the", "given", "resource", "to", "the", "given", "file", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/FileUtil.java#L34-L56
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/transformations/manglers/ResponseToSimpleResponseMangler.java
ResponseToSimpleResponseMangler.getNodeToBeReplaced
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)){ //This is the node that will need to be replaced with a copy with a localName of "simpleResponse" toBeReplaced=childNode; } } //If responseCount>1 This implies that both a simpleResponse and response have //been defined - this is allowed by the xsd, but makes no sense if (responseCount > 1) { throw new IllegalArgumentException("Only one of either simpleResponse or response should define the response type"); } } } return toBeReplaced; }
java
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)){ //This is the node that will need to be replaced with a copy with a localName of "simpleResponse" toBeReplaced=childNode; } } //If responseCount>1 This implies that both a simpleResponse and response have //been defined - this is allowed by the xsd, but makes no sense if (responseCount > 1) { throw new IllegalArgumentException("Only one of either simpleResponse or response should define the response type"); } } } return toBeReplaced; }
[ "private", "Node", "getNodeToBeReplaced", "(", "Node", "parametersNode", ")", "{", "Node", "toBeReplaced", "=", "null", ";", "int", "responseCount", "=", "0", ";", "NodeList", "childNodes", "=", "parametersNode", ".", "getChildNodes", "(", ")", ";", "if", "(",...
Also ensures only one of the two has been defined
[ "Also", "ensures", "only", "one", "of", "the", "two", "has", "been", "defined" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/transformations/manglers/ResponseToSimpleResponseMangler.java#L92-L115
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/XmlValidator.java
XmlValidator.validate
public void validate(Document doc) { try { doValidate(doc); } catch (Exception e) { throw new PluginException("Error validating document: " + e, e); } }
java
public void validate(Document doc) { try { doValidate(doc); } catch (Exception e) { throw new PluginException("Error validating document: " + e, e); } }
[ "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. @throws PluginException for any validation or IO errors.
[ "Validate", "the", "given", "xmlDocument", "using", "any", "schemas", "specified", "in", "the", "document", "itself", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/XmlValidator.java#L56-L63
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/jetty/JettyServerWrapper.java
JettyServerWrapper.setBufferSizes
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); } }
java
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); } }
[ "private", "void", "setBufferSizes", "(", "HttpConfiguration", "buffers", ")", "{", "if", "(", "requestHeaderSize", ">", "0", ")", "{", "LOGGER", ".", "info", "(", "\"Request header size set to {} for {}\"", ",", "requestHeaderSize", ",", "buffers", ".", "getClass",...
Sets the request and header buffer sizex if they are not zero
[ "Sets", "the", "request", "and", "header", "buffer", "sizex", "if", "they", "are", "not", "zero" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/jetty/JettyServerWrapper.java#L223-L237
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/jetty/JettyHttpTransport.java
JettyHttpTransport.registerHandler
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); }
java
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); }
[ "public", "void", "registerHandler", "(", "HttpServiceBindingDescriptor", "serviceBindingDescriptor", ")", "{", "for", "(", "ProtocolBinding", "protocolBinding", ":", "protocolBindingRegistry", ".", "getProtocolBindings", "(", ")", ")", "{", "if", "(", "protocolBinding", ...
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
[ "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", ...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/jetty/JettyHttpTransport.java#L272-L289
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/X509CertificateUtils.java
X509CertificateUtils.convert
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; }
java
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; }
[ "public", "static", "java", ".", "security", ".", "cert", ".", "X509Certificate", "convert", "(", "javax", ".", "security", ".", "cert", ".", "X509Certificate", "cert", ")", "{", "try", "{", "byte", "[", "]", "encoded", "=", "cert", ".", "getEncoded", "(...
Converts to java.security
[ "Converts", "to", "java", ".", "security" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/X509CertificateUtils.java#L40-L52
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/X509CertificateUtils.java
X509CertificateUtils.convert
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; }
java
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; }
[ "public", "static", "javax", ".", "security", ".", "cert", ".", "X509Certificate", "convert", "(", "java", ".", "security", ".", "cert", ".", "X509Certificate", "cert", ")", "{", "try", "{", "byte", "[", "]", "encoded", "=", "cert", ".", "getEncoded", "(...
Converts to javax.security
[ "Converts", "to", "javax", ".", "security" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/X509CertificateUtils.java#L55-L64
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/jsonrpc/JsonRpcTransportCommandProcessor.java
JsonRpcTransportCommandProcessor.writeErrorResponse
@Override 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()); } } }
java
@Override 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()); } } }
[ "@", "Override", "public", "void", "writeErrorResponse", "(", "HttpCommand", "command", ",", "DehydratedExecutionContext", "context", ",", "CougarException", "error", ",", "boolean", "traceStarted", ")", "{", "try", "{", "incrementErrorsWritten", "(", ")", ";", "fin...
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 @param command the command that caused the error @param context @param error @param traceStarted
[ "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"...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/jsonrpc/JsonRpcTransportCommandProcessor.java#L406-L446
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/ExecutionVenueNioClient.java
ExecutionVenueNioClient.start
public synchronized FutureTask<Boolean> start() { this.sessionFactory.start(); if (rpcTimeoutChecker != null) { rpcTimeoutChecker.getThread().start(); } final FutureTask<Boolean> futureTask = new FutureTask<Boolean>( new Callable<Boolean>() { @Override 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; }
java
public synchronized FutureTask<Boolean> start() { this.sessionFactory.start(); if (rpcTimeoutChecker != null) { rpcTimeoutChecker.getThread().start(); } final FutureTask<Boolean> futureTask = new FutureTask<Boolean>( new Callable<Boolean>() { @Override 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; }
[ "public", "synchronized", "FutureTask", "<", "Boolean", ">", "start", "(", ")", "{", "this", ".", "sessionFactory", ".", "start", "(", ")", ";", "if", "(", "rpcTimeoutChecker", "!=", "null", ")", "{", "rpcTimeoutChecker", ".", "getThread", "(", ")", ".", ...
Starts the client @return a Future<Boolean> that is true once the connection is established
[ "Starts", "the", "client" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/ExecutionVenueNioClient.java#L132-L151
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/ExecutionVenueNioClient.java
ExecutionVenueNioClient.notifyConnectionLost
private synchronized void notifyConnectionLost(final IoSession session) { new Thread("Connection-Closed-Notifier") { @Override public void run() { // todo: sml: should consider rationalising these so they're all HandlerListeners.. 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(); }
java
private synchronized void notifyConnectionLost(final IoSession session) { new Thread("Connection-Closed-Notifier") { @Override public void run() { // todo: sml: should consider rationalising these so they're all HandlerListeners.. 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(); }
[ "private", "synchronized", "void", "notifyConnectionLost", "(", "final", "IoSession", "session", ")", "{", "new", "Thread", "(", "\"Connection-Closed-Notifier\"", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "// todo: sml: should consider rationa...
Notify all observers that comms are lost
[ "Notify", "all", "observers", "that", "comms", "are", "lost" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/ExecutionVenueNioClient.java#L400-L417
train
betfair/cougar
cougar-framework/cougar-transport-impl/src/main/java/com/betfair/cougar/transport/impl/AbstractCommandProcessor.java
AbstractCommandProcessor.process
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); } }
java
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); } }
[ "public", "void", "process", "(", "final", "T", "command", ")", "{", "boolean", "traceStarted", "=", "false", ";", "incrementCommandsProcessed", "(", ")", ";", "DehydratedExecutionContext", "ctx", "=", "null", ";", "try", "{", "validateCommand", "(", "command", ...
Processes a TransportCommand. @param command
[ "Processes", "a", "TransportCommand", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-transport-impl/src/main/java/com/betfair/cougar/transport/impl/AbstractCommandProcessor.java#L87-L108
train
betfair/cougar
cougar-framework/cougar-transport-impl/src/main/java/com/betfair/cougar/transport/impl/AbstractCommandProcessor.java
AbstractCommandProcessor.executeCommand
protected void executeCommand(final ExecutionCommand finalExec, final ExecutionContext finalCtx) { executionsProcessed.incrementAndGet(); ev.execute(finalCtx, finalExec.getOperationKey(), finalExec.getArgs(), finalExec, executor, finalExec.getTimeConstraints()); }
java
protected void executeCommand(final ExecutionCommand finalExec, final ExecutionContext finalCtx) { executionsProcessed.incrementAndGet(); ev.execute(finalCtx, finalExec.getOperationKey(), finalExec.getArgs(), finalExec, executor, finalExec.getTimeConstraints()); }
[ "protected", "void", "executeCommand", "(", "final", "ExecutionCommand", "finalExec", ",", "final", "ExecutionContext", "finalCtx", ")", "{", "executionsProcessed", ".", "incrementAndGet", "(", ")", ";", "ev", ".", "execute", "(", "finalCtx", ",", "finalExec", "."...
Execute the supplied command @param finalExec @param finalCtx
[ "Execute", "the", "supplied", "command" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-transport-impl/src/main/java/com/betfair/cougar/transport/impl/AbstractCommandProcessor.java#L130-L138
train
betfair/cougar
baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java
BaselineServiceImpl.subscribeToTimeTick
@Override public void subscribeToTimeTick(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.timeTickPublishingObserver = executionObserver; } }
java
@Override public void subscribeToTimeTick(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.timeTickPublishingObserver = executionObserver; } }
[ "@", "Override", "public", "void", "subscribeToTimeTick", "(", "ExecutionContext", "ctx", ",", "Object", "[", "]", "args", ",", "ExecutionObserver", "executionObserver", ")", "{", "if", "(", "getEventTransportIdentity", "(", "ctx", ")", ".", "getPrincipal", "(", ...
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. @param ctx @param args @param 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...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java#L1913-L1918
train
betfair/cougar
baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java
BaselineServiceImpl.subscribeToMatchedBet
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
java
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
[ "@", "Override", "public", "void", "subscribeToMatchedBet", "(", "ExecutionContext", "ctx", ",", "Object", "[", "]", "args", ",", "ExecutionObserver", "executionObserver", ")", "{", "if", "(", "getEventTransportIdentity", "(", "ctx", ")", ".", "getPrincipal", "(",...
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. @param ctx @param args @param 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...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java#L1930-L1935
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/HttpCommandProcessorFactory.java
HttpCommandProcessorFactory.getCommandProcessor
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "HttpCommandProcessor", "getCommandProcessor", "(", "Protocol", "protocol", ")", "{", "String", "commandProcessorName", "=", "commandProcessorNames", ".", "get", "(", "protocol", ")", ";", "if", "(", "commandProcessorName", "==", "null", "...
Returns the command processor assocated with the supplied protocol @param @see Protocol @return returns you the command processor for the supplied protocol @throws PanicInTheCougar if there is no command processor for the requested protocol
[ "Returns", "the", "command", "processor", "assocated", "with", "the", "supplied", "protocol" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/HttpCommandProcessorFactory.java#L42-L57
train
betfair/cougar
cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java
JmsEventTransportImpl.publish
public void publish(Event event, String destinationName, EventServiceBindingDescriptor eventServiceBindingDescriptor) throws CougarException { try { EventPublisherRunnable publisherRunnable = new EventPublisherRunnable(event, destinationName, eventServiceBindingDescriptor); threadPool.execute(publisherRunnable); // Publish the event using a thread from the pool publisherRunnable.lock(); if (!publisherRunnable.isSuccess()) { // If publication failed for any reason pass out the exception thrown Exception e = publisherRunnable.getError(); LOGGER.error("Publication exception:", e); throw new CougarFrameworkException("Sonic JMS publication exception", e); } } catch (InterruptedException ex) { // Interrupted while waiting for event to be published LOGGER.error("Publication exception:", ex); throw new CougarFrameworkException("Sonic JMS publication exception", ex); } }
java
public void publish(Event event, String destinationName, EventServiceBindingDescriptor eventServiceBindingDescriptor) throws CougarException { try { EventPublisherRunnable publisherRunnable = new EventPublisherRunnable(event, destinationName, eventServiceBindingDescriptor); threadPool.execute(publisherRunnable); // Publish the event using a thread from the pool publisherRunnable.lock(); if (!publisherRunnable.isSuccess()) { // If publication failed for any reason pass out the exception thrown Exception e = publisherRunnable.getError(); LOGGER.error("Publication exception:", e); throw new CougarFrameworkException("Sonic JMS publication exception", e); } } catch (InterruptedException ex) { // Interrupted while waiting for event to be published LOGGER.error("Publication exception:", ex); throw new CougarFrameworkException("Sonic JMS publication exception", ex); } }
[ "public", "void", "publish", "(", "Event", "event", ",", "String", "destinationName", ",", "EventServiceBindingDescriptor", "eventServiceBindingDescriptor", ")", "throws", "CougarException", "{", "try", "{", "EventPublisherRunnable", "publisherRunnable", "=", "new", "Even...
Publish the supplied event to the destination. The event will be published using a thread from the pool and its associated jms session @param event @throws com.betfair.cougar.core.api.exception.CougarException @see com.betfair.cougar.transport.api.protocol.events.jms.JMSDestinationResolver
[ "Publish", "the", "supplied", "event", "to", "the", "destination", ".", "The", "event", "will", "be", "published", "using", "a", "thread", "from", "the", "pool", "and", "its", "associated", "jms", "session" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java#L347-L362
train
betfair/cougar
cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java
JmsEventTransportImpl.requestConnectionToBroker
public Future<Boolean> requestConnectionToBroker() { FutureTask futureTask = new FutureTask(new Callable<Boolean>() { @Override 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; }
java
public Future<Boolean> requestConnectionToBroker() { FutureTask futureTask = new FutureTask(new Callable<Boolean>() { @Override 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; }
[ "public", "Future", "<", "Boolean", ">", "requestConnectionToBroker", "(", ")", "{", "FutureTask", "futureTask", "=", "new", "FutureTask", "(", "new", "Callable", "<", "Boolean", ">", "(", ")", "{", "@", "Override", "public", "Boolean", "call", "(", ")", "...
Requests that this transports attempts to connect to the broker. Occurs asynchronously from the caller initiation.
[ "Requests", "that", "this", "transports", "attempts", "to", "connect", "to", "the", "broker", ".", "Occurs", "asynchronously", "from", "the", "caller", "initiation", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java#L481-L497
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/AbstractHttpExecutable.java
AbstractHttpExecutable.isDefinitelyCougarResponse
private boolean isDefinitelyCougarResponse(CougarHttpResponse response) { String ident = response.getServerIdentity(); if (ident != null && ident.contains("Cougar 2")) { return true; } return false; }
java
private boolean isDefinitelyCougarResponse(CougarHttpResponse response) { String ident = response.getServerIdentity(); if (ident != null && ident.contains("Cougar 2")) { return true; } return false; }
[ "private", "boolean", "isDefinitelyCougarResponse", "(", "CougarHttpResponse", "response", ")", "{", "String", "ident", "=", "response", ".", "getServerIdentity", "(", ")", ";", "if", "(", "ident", "!=", "null", "&&", "ident", ".", "contains", "(", "\"Cougar 2\"...
has the responding server identified itself as Cougar Note that due to legacy servers/network infrastructure a 'false negative' is possible. in other words although a 'true' response confirms that the server has identified itself Cougar, a 'false' does not confirm that a server IS NOT Cougar. The cougar header could have been stripped out by network infrastructure, or the server could still be a legacy Cougar which does not provide this header. @param response http response @return boolean has the responding server identified itself as Cougar
[ "has", "the", "responding", "server", "identified", "itself", "as", "Cougar" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/AbstractHttpExecutable.java#L338-L344
train
betfair/cougar
cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinManager.java
ZipkinManager.setSamplingLevel
@ManagedAttribute 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 + "["); } }
java
@ManagedAttribute 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 + "["); } }
[ "@", "ManagedAttribute", "public", "void", "setSamplingLevel", "(", "int", "samplingLevel", ")", "{", "if", "(", "samplingLevel", ">=", "MIN_LEVEL", "&&", "samplingLevel", "<=", "MAX_LEVEL", ")", "{", "this", ".", "samplingLevel", "=", "samplingLevel", ";", "}",...
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. @param samplingLevel The sampling level @throws IllegalArgumentException if the sampling level is off bounds
[ "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", "t...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinManager.java#L92-L99
train
betfair/cougar
cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinManager.java
ZipkinManager.getRandomLong
public static long getRandomLong() { byte[] rndBytes = new byte[8]; SECURE_RANDOM_TL.get().nextBytes(rndBytes); return ByteBuffer.wrap(rndBytes).getLong(); }
java
public static long getRandomLong() { byte[] rndBytes = new byte[8]; SECURE_RANDOM_TL.get().nextBytes(rndBytes); return ByteBuffer.wrap(rndBytes).getLong(); }
[ "public", "static", "long", "getRandomLong", "(", ")", "{", "byte", "[", "]", "rndBytes", "=", "new", "byte", "[", "8", "]", ";", "SECURE_RANDOM_TL", ".", "get", "(", ")", ".", "nextBytes", "(", "rndBytes", ")", ";", "return", "ByteBuffer", ".", "wrap"...
Retrieves a newly generated random long. @return A newly generated random long
[ "Retrieves", "a", "newly", "generated", "random", "long", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-zipkin-common/src/main/java/com/betfair/cougar/modules/zipkin/impl/ZipkinManager.java#L167-L171
train
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java
PooledServerConnectedObjectManager.getHeapsForSession
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; }
java
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; }
[ "public", "List", "<", "String", ">", "getHeapsForSession", "(", "IoSession", "session", ")", "{", "List", "<", "String", ">", "ret", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "try", "{", "subTermLock", ".", "lock", "(", ")", ";", "...
used for monitoring
[ "used", "for", "monitoring" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java#L110-L122
train
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java
PooledServerConnectedObjectManager.processHeapStateCreation
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()); // we're safe to lock this out of normal order as the HeapState isn't visible to other threads until the // end of this block. We have to have the lock before we make it visible.. newState.getUpdateLock().lock(); // new heap for this transport UpdateProducingHeapListener listener = new UpdateProducingHeapListener() { @Override protected void doUpdate(Update u) { if (u.getActions().size() > 0) { newState.getQueuedChanges().add(new QueuedHeapChange(u)); // bad luck, we just added the heap and it's just about to get terminated... 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; }
java
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()); // we're safe to lock this out of normal order as the HeapState isn't visible to other threads until the // end of this block. We have to have the lock before we make it visible.. newState.getUpdateLock().lock(); // new heap for this transport UpdateProducingHeapListener listener = new UpdateProducingHeapListener() { @Override protected void doUpdate(Update u) { if (u.getActions().size() > 0) { newState.getQueuedChanges().add(new QueuedHeapChange(u)); // bad luck, we just added the heap and it's just about to get terminated... 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; }
[ "private", "HeapState", "processHeapStateCreation", "(", "final", "ConnectedResponse", "result", ",", "final", "String", "heapUri", ")", "{", "if", "(", "!", "subTermLock", ".", "isHeldByCurrentThread", "(", ")", ")", "{", "throw", "new", "IllegalStateException", ...
note, you must have the subterm lock before calling this method
[ "note", "you", "must", "have", "the", "subterm", "lock", "before", "calling", "this", "method" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java#L185-L213
train
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java
PooledServerConnectedObjectManager.terminateSubscription
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); // notify client 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) { // if we can't tell them about it then something more serious has just happened. // the client will likely find out anyway since this will likely mean a dead session // we'll just log some info to the log to aid any debugging. We won't change the closure reason. 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"); // we'll request a closure of the session too to make sure everything gets cleaned up, although chances are it's already closed 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(); } } }
java
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); // notify client 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) { // if we can't tell them about it then something more serious has just happened. // the client will likely find out anyway since this will likely mean a dead session // we'll just log some info to the log to aid any debugging. We won't change the closure reason. 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"); // we'll request a closure of the session too to make sure everything gets cleaned up, although chances are it's already closed 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(); } } }
[ "public", "void", "terminateSubscription", "(", "IoSession", "session", ",", "String", "heapUri", ",", "String", "subscriptionId", ",", "Subscription", ".", "CloseReason", "reason", ")", "{", "Lock", "heapUpdateLock", "=", "null", ";", "try", "{", "HeapState", "...
Terminates a single subscription to a single heap
[ "Terminates", "a", "single", "subscription", "to", "a", "single", "heap" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java#L357-L407
train
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java
PooledServerConnectedObjectManager.terminateSubscriptions
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); } } }
java
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); } } }
[ "private", "void", "terminateSubscriptions", "(", "IoSession", "session", ",", "Subscription", ".", "CloseReason", "reason", ")", "{", "Multiset", "<", "String", ">", "heapsForThisClient", ";", "try", "{", "subTermLock", ".", "lock", "(", ")", ";", "heapsForThis...
Terminates all subscriptions for a given client
[ "Terminates", "all", "subscriptions", "for", "a", "given", "client" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java#L456-L470
train
betfair/cougar
cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java
PooledServerConnectedObjectManager.terminateSubscriptions
private void terminateSubscriptions(String heapUri, Subscription.CloseReason reason) { HeapState state = heapStates.get(heapUri); if (state != null) { try { state.getUpdateLock().lock(); subTermLock.lock(); // if someone got here first, don't bother doing the work 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(); } } }
java
private void terminateSubscriptions(String heapUri, Subscription.CloseReason reason) { HeapState state = heapStates.get(heapUri); if (state != null) { try { state.getUpdateLock().lock(); subTermLock.lock(); // if someone got here first, don't bother doing the work 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(); } } }
[ "private", "void", "terminateSubscriptions", "(", "String", "heapUri", ",", "Subscription", ".", "CloseReason", "reason", ")", "{", "HeapState", "state", "=", "heapStates", ".", "get", "(", "heapUri", ")", ";", "if", "(", "state", "!=", "null", ")", "{", "...
Terminates all subscriptions for a given heap
[ "Terminates", "all", "subscriptions", "for", "a", "given", "heap" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/socket-transport/src/main/java/com/betfair/cougar/transport/socket/PooledServerConnectedObjectManager.java#L475-L498
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java
BitmapBuilder.pad
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; }
java
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; }
[ "private", "static", "int", "[", "]", "pad", "(", "int", "[", "]", "list", ")", "{", "double", "m", "=", "list", ".", "length", "/", "(", "double", ")", "WORD_LENGTH", ";", "int", "size", "=", "(", "int", ")", "Math", ".", "ceil", "(", "m", ")"...
Increases the array size to a multiple of WORD_LENGTH @param list @return
[ "Increases", "the", "array", "size", "to", "a", "multiple", "of", "WORD_LENGTH" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java#L31-L38
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java
BitmapBuilder.listToMap
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; }
java
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; }
[ "public", "static", "int", "[", "]", "listToMap", "(", "int", "[", "]", "list", ")", "{", "list", "=", "pad", "(", "list", ")", ";", "int", "[", "]", "bitMap", "=", "new", "int", "[", "(", "int", ")", "(", "list", ".", "length", "/", "WORD_LENG...
Builds a bit map from the given list. The list should values of 0 or 1s @param list @return
[ "Builds", "a", "bit", "map", "from", "the", "given", "list", ".", "The", "list", "should", "values", "of", "0", "or", "1s" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java#L46-L58
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java
BitmapBuilder.mapToList
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; }
java
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; }
[ "public", "static", "int", "[", "]", "mapToList", "(", "int", "[", "]", "bitMap", ")", "{", "int", "[", "]", "list", "=", "new", "int", "[", "(", "int", ")", "(", "bitMap", ".", "length", "*", "WORD_LENGTH", ")", "]", ";", "Arrays", ".", "fill", ...
Builds a list from the given bit map. The list will contain values of 0 or 1s @param list @return
[ "Builds", "a", "list", "from", "the", "given", "bit", "map", ".", "The", "list", "will", "contain", "values", "of", "0", "or", "1s" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/BitmapBuilder.java#L67-L78
train
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/soap/SoapTransportCommandProcessor.java
SoapTransportCommandProcessor.toEnum
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); } }
java
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); } }
[ "private", "Object", "toEnum", "(", "ParameterType", "parameterType", ",", "String", "enumTextValue", ",", "String", "paramName", ",", "boolean", "hardFailEnumDeserialisation", ")", "{", "try", "{", "return", "EnumUtils", ".", "readEnum", "(", "parameterType", ".", ...
Deserialise enums explicitly
[ "Deserialise", "enums", "explicitly" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/soap/SoapTransportCommandProcessor.java#L326-L332
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java
IdlToDSMojo.processService
private void processService(Service service) throws Exception { getLog().info(" Service: " + service.getServiceName()); Document iddDoc = parseIddFile(service.getServiceName()); // 1. validate if (!isOffline()) { getLog().debug("Validating XML.."); new XmlValidator(resolver).validate(iddDoc); } // 2. generate outputs generateJavaCode(service, iddDoc); }
java
private void processService(Service service) throws Exception { getLog().info(" Service: " + service.getServiceName()); Document iddDoc = parseIddFile(service.getServiceName()); // 1. validate if (!isOffline()) { getLog().debug("Validating XML.."); new XmlValidator(resolver).validate(iddDoc); } // 2. generate outputs generateJavaCode(service, iddDoc); }
[ "private", "void", "processService", "(", "Service", "service", ")", "throws", "Exception", "{", "getLog", "(", ")", ".", "info", "(", "\" Service: \"", "+", "service", ".", "getServiceName", "(", ")", ")", ";", "Document", "iddDoc", "=", "parseIddFile", "(...
Various steps needing to be done for each IDD
[ "Various", "steps", "needing", "to", "be", "done", "for", "each", "IDD" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L346-L360
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java
IdlToDSMojo.initOutputDir
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."); } }
java
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."); } }
[ "private", "void", "initOutputDir", "(", "File", "outputDir", ")", "{", "if", "(", "!", "outputDir", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "outputDir", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"...
Set up and validate the creation of the specified output directory
[ "Set", "up", "and", "validate", "the", "creation", "of", "the", "specified", "output", "directory" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L589-L599
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java
IdlToDSMojo.readNamespaceAttr
private String readNamespaceAttr(Document doc) { // lazy loading is mostly pointless but it keeps things together 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); } // xpath returns an empty string if not found, null is cleaner for callers return (s == null || s.length() == 0) ? null : s; }
java
private String readNamespaceAttr(Document doc) { // lazy loading is mostly pointless but it keeps things together 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); } // xpath returns an empty string if not found, null is cleaner for callers return (s == null || s.length() == 0) ? null : s; }
[ "private", "String", "readNamespaceAttr", "(", "Document", "doc", ")", "{", "// lazy loading is mostly pointless but it keeps things together", "if", "(", "namespaceExpr", "==", "null", ")", "{", "namespaceExpr", "=", "initNamespaceAttrExpression", "(", ")", ";", "}", "...
Retrieve 'namespace' attr of interface definition or null if not found
[ "Retrieve", "namespace", "attr", "of", "interface", "definition", "or", "null", "if", "not", "found" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L653-L668
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/NetworkAddress.java
NetworkAddress.isValidIPAddress
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; }
java
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; }
[ "public", "static", "boolean", "isValidIPAddress", "(", "String", "networkAddress", ")", "{", "if", "(", "networkAddress", "!=", "null", ")", "{", "String", "[", "]", "split", "=", "networkAddress", ".", "split", "(", "\"\\\\.\"", ")", ";", "if", "(", "spl...
Verify if a given string is a valid dotted quad notation IP Address @param networkAddress The address string @return true if its valid, false otherwise
[ "Verify", "if", "a", "given", "string", "is", "a", "valid", "dotted", "quad", "notation", "IP", "Address" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/NetworkAddress.java#L212-L231
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/NetworkAddress.java
NetworkAddress.parseDottedQuad
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]); //a pox on java and it's signed bytes } return bytes; } else { throw new IllegalArgumentException("Address must be in dotted quad notation"); } }
java
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]); //a pox on java and it's signed bytes } return bytes; } else { throw new IllegalArgumentException("Address must be in dotted quad notation"); } }
[ "private", "static", "byte", "[", "]", "parseDottedQuad", "(", "String", "address", ")", "{", "String", "[", "]", "splitString", "=", "address", ".", "split", "(", "\"\\\\.\"", ")", ";", "if", "(", "splitString", ".", "length", "==", "4", ")", "{", "in...
parse ip4 address as dotted quad notation into bytes @param address @return
[ "parse", "ip4", "address", "as", "dotted", "quad", "notation", "into", "bytes" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/NetworkAddress.java#L238-L258
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/Sets.java
Sets.fromMap
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; }
java
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; }
[ "public", "static", "final", "Set", "fromMap", "(", "Map", "map", ",", "Object", "...", "keys", ")", "{", "if", "(", "keys", "!=", "null", "&&", "map", "!=", "null", ")", "{", "Set", "answer", "=", "new", "HashSet", "(", ")", ";", "for", "(", "Ob...
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.
[ "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"...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/Sets.java#L29-L40
train
betfair/cougar
cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/Sets.java
Sets.fromCommaSeparatedValues
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)); }
java
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)); }
[ "public", "static", "final", "Set", "<", "String", ">", "fromCommaSeparatedValues", "(", "String", "csv", ")", "{", "if", "(", "csv", "==", "null", "||", "csv", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "EMPTY_SET", ";", "}", "S...
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.
[ "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",...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-util/src/main/java/com/betfair/cougar/util/configuration/Sets.java#L47-L53
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IDLReader.java
IDLReader.mergeExtensionsIntoDocument
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); } }
java
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); } }
[ "private", "void", "mergeExtensionsIntoDocument", "(", "Node", "target", ",", "Node", "extensions", ")", "throws", "Exception", "{", "final", "XPathFactory", "factory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "final", "NodeList", "nodes", "=", "(...
Weave the extensions defined in the extensions doc into the target.
[ "Weave", "the", "extensions", "defined", "in", "the", "extensions", "doc", "into", "the", "target", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IDLReader.java#L369-L385
train
betfair/cougar
cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IDLReader.java
IDLReader.removeUndefinedOperations
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) { // This operation is not defined in the extensions doc log.debug("Ignoring IDL defined operation: " + getAttribute(targetNode, "name")); targetNode.getParentNode().removeChild(targetNode); } } }
java
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) { // This operation is not defined in the extensions doc log.debug("Ignoring IDL defined operation: " + getAttribute(targetNode, "name")); targetNode.getParentNode().removeChild(targetNode); } } }
[ "private", "void", "removeUndefinedOperations", "(", "Node", "target", ",", "Node", "extensions", ")", "throws", "Exception", "{", "final", "XPathFactory", "factory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "final", "NodeList", "nodes", "=", "(",...
Cycle through the target Node and remove any operations not defined in the extensions document.
[ "Cycle", "through", "the", "target", "Node", "and", "remove", "any", "operations", "not", "defined", "in", "the", "extensions", "document", "." ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IDLReader.java#L390-L405
train
betfair/cougar
cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/ev/ServiceRegisterableExecutionVenue.java
ServiceRegisterableExecutionVenue.getNamespaceServiceDefinitionMap
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); }
java
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); }
[ "public", "Map", "<", "String", ",", "Set", "<", "ServiceDefinition", ">", ">", "getNamespaceServiceDefinitionMap", "(", ")", "{", "Map", "<", "String", ",", "Set", "<", "ServiceDefinition", ">", ">", "namespaceServiceDefinitionMap", "=", "new", "HashMap", "<", ...
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 @return
[ "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"...
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-core-impl/src/main/java/com/betfair/cougar/core/impl/ev/ServiceRegisterableExecutionVenue.java#L146-L157
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java
IoSessionFactory.getCurrentSessionAddresses
public Set<SocketAddress> getCurrentSessionAddresses() { Set<SocketAddress> result = new HashSet<SocketAddress>(); synchronized (lock) { result.addAll(sessions.keySet()); result.addAll(pendingConnections.keySet()); } return result; }
java
public Set<SocketAddress> getCurrentSessionAddresses() { Set<SocketAddress> result = new HashSet<SocketAddress>(); synchronized (lock) { result.addAll(sessions.keySet()); result.addAll(pendingConnections.keySet()); } return result; }
[ "public", "Set", "<", "SocketAddress", ">", "getCurrentSessionAddresses", "(", ")", "{", "Set", "<", "SocketAddress", ">", "result", "=", "new", "HashSet", "<", "SocketAddress", ">", "(", ")", ";", "synchronized", "(", "lock", ")", "{", "result", ".", "add...
Returns a list of all server socket addresses to which sessions are already established or being established @return List of socket addresses
[ "Returns", "a", "list", "of", "all", "server", "socket", "addresses", "to", "which", "sessions", "are", "already", "established", "or", "being", "established" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java#L108-L115
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java
IoSessionFactory.getSession
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; } } }
java
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; } } }
[ "public", "IoSession", "getSession", "(", ")", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "sessions", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "final", "Object", "[", "]", "keys", "=", "sessions", ".", ...
Rotates via list of currently established sessions @return an IO session
[ "Rotates", "via", "list", "of", "currently", "established", "sessions" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java#L157-L174
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java
IoSessionFactory.openSession
public void openSession(SocketAddress endpoint) { synchronized (lock) { // Submit a reconnect task for this address if one is not already present if (!pendingConnections.containsKey(endpoint)) { final ReconnectTask task = new ReconnectTask(endpoint); pendingConnections.put(endpoint, task); this.reconnectExecutor.submit(task); } } }
java
public void openSession(SocketAddress endpoint) { synchronized (lock) { // Submit a reconnect task for this address if one is not already present if (!pendingConnections.containsKey(endpoint)) { final ReconnectTask task = new ReconnectTask(endpoint); pendingConnections.put(endpoint, task); this.reconnectExecutor.submit(task); } } }
[ "public", "void", "openSession", "(", "SocketAddress", "endpoint", ")", "{", "synchronized", "(", "lock", ")", "{", "// Submit a reconnect task for this address if one is not already present", "if", "(", "!", "pendingConnections", ".", "containsKey", "(", "endpoint", ")",...
Open a new session to the specified address. If session is being opened does nothing @param endpoint
[ "Open", "a", "new", "session", "to", "the", "specified", "address", ".", "If", "session", "is", "being", "opened", "does", "nothing" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java#L183-L192
train
betfair/cougar
cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java
IoSessionFactory.closeSession
public void closeSession(SocketAddress endpoint, boolean reconnect) { synchronized (lock) { // Submit a reconnect task for this address if one is not already present 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); } } } }
java
public void closeSession(SocketAddress endpoint, boolean reconnect) { synchronized (lock) { // Submit a reconnect task for this address if one is not already present 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); } } } }
[ "public", "void", "closeSession", "(", "SocketAddress", "endpoint", ",", "boolean", "reconnect", ")", "{", "synchronized", "(", "lock", ")", "{", "// Submit a reconnect task for this address if one is not already present", "if", "(", "pendingConnections", ".", "containsKey"...
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 @param endpoint @param reconnect whether to reconnect after closing the current session. Only used if the session is active
[ "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" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-client/src/main/java/com/betfair/cougar/client/socket/IoSessionFactory.java#L202-L217
train
betfair/cougar
cougar-framework/cougar-core-api/src/main/java/com/betfair/cougar/core/api/exception/CougarException.java
CougarException.getMessage
@Override public final String getMessage() { String additional = additionalInfo(); return additional == null ? super.getMessage() : super.getMessage() + ": " + additional; }
java
@Override public final String getMessage() { String additional = additionalInfo(); return additional == null ? super.getMessage() : super.getMessage() + ": " + additional; }
[ "@", "Override", "public", "final", "String", "getMessage", "(", ")", "{", "String", "additional", "=", "additionalInfo", "(", ")", ";", "return", "additional", "==", "null", "?", "super", ".", "getMessage", "(", ")", ":", "super", ".", "getMessage", "(", ...
Prevent defined services overriding the exception message
[ "Prevent", "defined", "services", "overriding", "the", "exception", "message" ]
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-core-api/src/main/java/com/betfair/cougar/core/api/exception/CougarException.java#L103-L107
train
profesorfalken/WMI4Java
src/main/java/com/profesorfalken/wmi4java/WMI4Java.java
WMI4Java.listClasses
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)); } } // Normalize results: remove duplicates and sort the list 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; }
java
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)); } } // Normalize results: remove duplicates and sort the list 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; }
[ "public", "List", "<", "String", ">", "listClasses", "(", ")", "throws", "WMIException", "{", "List", "<", "String", ">", "wmiClasses", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "String", "rawData", ";", "try", "{", "rawData", "=", "g...
Query and list the WMI classes @see <a href= "https://msdn.microsoft.com/fr-fr/library/windows/desktop/aa394554(v=vs.85).aspx">WMI Classes - MSDN</a> @return a list with the name of existing classes in the system
[ "Query", "and", "list", "the", "WMI", "classes" ]
a39b153a84a12b0c4c0583234fd2b32aba7f868c
https://github.com/profesorfalken/WMI4Java/blob/a39b153a84a12b0c4c0583234fd2b32aba7f868c/src/main/java/com/profesorfalken/wmi4java/WMI4Java.java#L174-L201
train
profesorfalken/WMI4Java
src/main/java/com/profesorfalken/wmi4java/WMI4Java.java
WMI4Java.listProperties
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; }
java
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; }
[ "public", "List", "<", "String", ">", "listProperties", "(", "String", "wmiClass", ")", "throws", "WMIException", "{", "List", "<", "String", ">", "foundPropertiesList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "try", "{", "String", "raw...
Query a WMI class and return all the available properties @param wmiClass the WMI class to query @return a list with the name of existing properties in the class
[ "Query", "a", "WMI", "class", "and", "return", "all", "the", "available", "properties" ]
a39b153a84a12b0c4c0583234fd2b32aba7f868c
https://github.com/profesorfalken/WMI4Java/blob/a39b153a84a12b0c4c0583234fd2b32aba7f868c/src/main/java/com/profesorfalken/wmi4java/WMI4Java.java#L210-L231
train
profesorfalken/WMI4Java
src/main/java/com/profesorfalken/wmi4java/WMI4Java.java
WMI4Java.getRawWMIObjectOutput
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; }
java
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; }
[ "public", "String", "getRawWMIObjectOutput", "(", "String", "wmiClass", ")", "throws", "WMIException", "{", "String", "rawData", ";", "try", "{", "if", "(", "this", ".", "properties", "!=", "null", "||", "this", ".", "filters", "!=", "null", ")", "{", "raw...
Query all the raw object data for an specific class @param wmiClass string with the name of the class to query @return string with all the properties of the object
[ "Query", "all", "the", "raw", "object", "data", "for", "an", "specific", "class" ]
a39b153a84a12b0c4c0583234fd2b32aba7f868c
https://github.com/profesorfalken/WMI4Java/blob/a39b153a84a12b0c4c0583234fd2b32aba7f868c/src/main/java/com/profesorfalken/wmi4java/WMI4Java.java#L378-L392
train
yan74/afplib
org.afplib/src/main/java/org/afplib/io/AfpInputStream.java
AfpInputStream.readStructuredField
public SF readStructuredField() throws IOException { int buf = 0; long thisOffset = offset; if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = read(); offset++; leadingLength++; } while((buf & 0xff) != 0x5a && buf != -1 && leadingLength < 5); if((buf & 0xff) != 0x5a) { has5a = false; leadingLength = 1; // so try if byte 3 is 0xd3 -> so this would be an afp without 5a magic byte 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; // if(buf == -1 && leadingLength > 1) // throw new IOException("found trailing garbage at the end of file."); } else { if(leadingLengthBytes > 0) read(data, 0, leadingLengthBytes); // just throw away those 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; // (byte) (buf & 0xff); 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; }
java
public SF readStructuredField() throws IOException { int buf = 0; long thisOffset = offset; if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = read(); offset++; leadingLength++; } while((buf & 0xff) != 0x5a && buf != -1 && leadingLength < 5); if((buf & 0xff) != 0x5a) { has5a = false; leadingLength = 1; // so try if byte 3 is 0xd3 -> so this would be an afp without 5a magic byte 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; // if(buf == -1 && leadingLength > 1) // throw new IOException("found trailing garbage at the end of file."); } else { if(leadingLengthBytes > 0) read(data, 0, leadingLengthBytes); // just throw away those 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; // (byte) (buf & 0xff); 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; }
[ "public", "SF", "readStructuredField", "(", ")", "throws", "IOException", "{", "int", "buf", "=", "0", ";", "long", "thisOffset", "=", "offset", ";", "if", "(", "leadingLengthBytes", "==", "-", "1", ")", "{", "// we haven't tested for mvs download leading length b...
Reads a new structured field from the input stream. This method is not thread-safe! @return structured field or null if end of input. @throws IOException
[ "Reads", "a", "new", "structured", "field", "from", "the", "input", "stream", ".", "This", "method", "is", "not", "thread", "-", "safe!" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/io/AfpInputStream.java#L58-L143
train
yan74/afplib
org.afplib/src/main/java/org/afplib/helper/formdef/FormdefScanner.java
FormdefScanner.scan
public static Formdef scan(AfpInputStream in) throws IOException { Formdef formdef = new FormdefImpl(); SF sf; LinkedList<SF> sfbuffer = null; while((sf = in.readStructuredField()) != null) { log.trace("{}", sf); switch(sf.eClass().getClassifierID()) { case AfplibPackage.ERG: case AfplibPackage.BDT: return null; case AfplibPackage.EFM: return formdef; case AfplibPackage.BDG: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EDG: sfbuffer.add(sf); formdef.setBDG((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; case AfplibPackage.BMM: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EMM: sfbuffer.add(sf); formdef.add((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; } if(sfbuffer != null) sfbuffer.add(sf); } return null; }
java
public static Formdef scan(AfpInputStream in) throws IOException { Formdef formdef = new FormdefImpl(); SF sf; LinkedList<SF> sfbuffer = null; while((sf = in.readStructuredField()) != null) { log.trace("{}", sf); switch(sf.eClass().getClassifierID()) { case AfplibPackage.ERG: case AfplibPackage.BDT: return null; case AfplibPackage.EFM: return formdef; case AfplibPackage.BDG: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EDG: sfbuffer.add(sf); formdef.setBDG((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; case AfplibPackage.BMM: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EMM: sfbuffer.add(sf); formdef.add((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; } if(sfbuffer != null) sfbuffer.add(sf); } return null; }
[ "public", "static", "Formdef", "scan", "(", "AfpInputStream", "in", ")", "throws", "IOException", "{", "Formdef", "formdef", "=", "new", "FormdefImpl", "(", ")", ";", "SF", "sf", ";", "LinkedList", "<", "SF", ">", "sfbuffer", "=", "null", ";", "while", "...
Scans the input for medium maps and adds to the formdef. This scanner will modify the AfpInputStreams position. If you need to keep position, please provide a new AfpInputStream. @param in formdef or afp file to read medium maps from @return formdef in memory representation of the formdef @throws IOException
[ "Scans", "the", "input", "for", "medium", "maps", "and", "adds", "to", "the", "formdef", "." ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/helper/formdef/FormdefScanner.java#L32-L68
train
yan74/afplib
org.afplib/src/main/java/org/afplib/Data.java
Data.decode
public static String decode(String urlString) { StringBuilder s = new StringBuilder(); UrlDecoderState state = UrlDecoderState.INITIAL; int hiNibble = 0; int lowNibble = 0; int length = urlString.length(); for (int i = 0; i < length; i++) { char c = urlString.charAt(i); switch (state) { case INITIAL: if (c == '%') { state = UrlDecoderState.FIRST_HEX; } else { s.append(c); } break; case FIRST_HEX: hiNibble = lookup(c); state = UrlDecoderState.SECOND_HEX; break; case SECOND_HEX: lowNibble = lookup(c); byte b = (byte) ((hiNibble << 4) | lowNibble); s.append((char) b); state = UrlDecoderState.INITIAL; break; } } return s.toString(); }
java
public static String decode(String urlString) { StringBuilder s = new StringBuilder(); UrlDecoderState state = UrlDecoderState.INITIAL; int hiNibble = 0; int lowNibble = 0; int length = urlString.length(); for (int i = 0; i < length; i++) { char c = urlString.charAt(i); switch (state) { case INITIAL: if (c == '%') { state = UrlDecoderState.FIRST_HEX; } else { s.append(c); } break; case FIRST_HEX: hiNibble = lookup(c); state = UrlDecoderState.SECOND_HEX; break; case SECOND_HEX: lowNibble = lookup(c); byte b = (byte) ((hiNibble << 4) | lowNibble); s.append((char) b); state = UrlDecoderState.INITIAL; break; } } return s.toString(); }
[ "public", "static", "String", "decode", "(", "String", "urlString", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", ")", ";", "UrlDecoderState", "state", "=", "UrlDecoderState", ".", "INITIAL", ";", "int", "hiNibble", "=", "0", ";", "int", ...
Like java.net.URLDecoder except no conversion of "+" to space
[ "Like", "java", ".", "net", ".", "URLDecoder", "except", "no", "conversion", "of", "+", "to", "space" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/Data.java#L304-L333
train
yan74/afplib
org.afplib/src/main/java/org/afplib/io/AfpMappedFile.java
AfpMappedFile.next
public SF next() throws IOException { int remaining = afpData.remaining(); if(remaining == 0) return null; if(remaining < 9) throw new IOException("trailing garbage at the end of file."); byte buf; long thisOffset = afpData.position(); try { if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = afpData.get(); leadingLength++; } while((buf & 0xff) != 0x5a && afpData.remaining() > 0 && leadingLength < 5); leadingLengthBytes = leadingLength-1; } else { if(leadingLengthBytes > 0) afpData.position(afpData.position() + leadingLengthBytes); // just throw away those buf = afpData.get(); } if((buf & 0xff) != 0x5a) throw new IOException("cannot find 5a magic byte"); data[0] = buf; buf = afpData.get(); data[1] = buf; length = (byte) buf << 8; buf = afpData.get(); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length + 3 > data.length) throw new IOException("length of structured field is too large: "+length); afpData.get(data, 3, length); } catch (BufferUnderflowException e) { return null; // FIXME could also be an error } SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
java
public SF next() throws IOException { int remaining = afpData.remaining(); if(remaining == 0) return null; if(remaining < 9) throw new IOException("trailing garbage at the end of file."); byte buf; long thisOffset = afpData.position(); try { if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = afpData.get(); leadingLength++; } while((buf & 0xff) != 0x5a && afpData.remaining() > 0 && leadingLength < 5); leadingLengthBytes = leadingLength-1; } else { if(leadingLengthBytes > 0) afpData.position(afpData.position() + leadingLengthBytes); // just throw away those buf = afpData.get(); } if((buf & 0xff) != 0x5a) throw new IOException("cannot find 5a magic byte"); data[0] = buf; buf = afpData.get(); data[1] = buf; length = (byte) buf << 8; buf = afpData.get(); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length + 3 > data.length) throw new IOException("length of structured field is too large: "+length); afpData.get(data, 3, length); } catch (BufferUnderflowException e) { return null; // FIXME could also be an error } SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
[ "public", "SF", "next", "(", ")", "throws", "IOException", "{", "int", "remaining", "=", "afpData", ".", "remaining", "(", ")", ";", "if", "(", "remaining", "==", "0", ")", "return", "null", ";", "if", "(", "remaining", "<", "9", ")", "throw", "new",...
Reads a new structured field from the mapped file. This method is not thread-safe! @return structured field or null if end of input. @throws IOException
[ "Reads", "a", "new", "structured", "field", "from", "the", "mapped", "file", ".", "This", "method", "is", "not", "thread", "-", "safe!" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/io/AfpMappedFile.java#L45-L99
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java
BankCardMagneticTrack.from
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
java
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
[ "public", "static", "BankCardMagneticTrack", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Track1FormatB", "track1", "=", "Track1FormatB", ".", "from", "(", "rawTrackData", ")", ";", "final", "Track2", "track2", "=", "Track2", ".", "from", ...
Parses magnetic track data into a BankCardMagneticTrack object. @param rawTrackData Raw track data as a string. Can include newlines, and all 3 tracks. @return A BankCardMagneticTrack instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "data", "into", "a", "BankCardMagneticTrack", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java#L48-L55
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java
BankCardMagneticTrack.toBankCard
public BankCard toBankCard() { final AccountNumber pan; if (track1.hasAccountNumber()) { pan = track1.getAccountNumber(); } else { pan = track2.getAccountNumber(); } final Name name; if (track1.hasName()) { name = track1.getName(); } else { name = new Name(); } final ExpirationDate expirationDate; if (track1.hasExpirationDate()) { expirationDate = track1.getExpirationDate(); } else { expirationDate = track2.getExpirationDate(); } final ServiceCode serviceCode; if (track1.hasServiceCode()) { serviceCode = track1.getServiceCode(); } else { serviceCode = track2.getServiceCode(); } final BankCard cardInfo = new BankCard(pan, expirationDate, name, serviceCode); return cardInfo; }
java
public BankCard toBankCard() { final AccountNumber pan; if (track1.hasAccountNumber()) { pan = track1.getAccountNumber(); } else { pan = track2.getAccountNumber(); } final Name name; if (track1.hasName()) { name = track1.getName(); } else { name = new Name(); } final ExpirationDate expirationDate; if (track1.hasExpirationDate()) { expirationDate = track1.getExpirationDate(); } else { expirationDate = track2.getExpirationDate(); } final ServiceCode serviceCode; if (track1.hasServiceCode()) { serviceCode = track1.getServiceCode(); } else { serviceCode = track2.getServiceCode(); } final BankCard cardInfo = new BankCard(pan, expirationDate, name, serviceCode); return cardInfo; }
[ "public", "BankCard", "toBankCard", "(", ")", "{", "final", "AccountNumber", "pan", ";", "if", "(", "track1", ".", "hasAccountNumber", "(", ")", ")", "{", "pan", "=", "track1", ".", "getAccountNumber", "(", ")", ";", "}", "else", "{", "pan", "=", "trac...
Constructs and returns bank card information, if all the track data is consistent. That is, if any bank card information is repeated in track 1 and track 2, it should be the same data. @return Bank card information.
[ "Constructs", "and", "returns", "bank", "card", "information", "if", "all", "the", "track", "data", "is", "consistent", ".", "That", "is", "if", "any", "bank", "card", "information", "is", "repeated", "in", "track", "1", "and", "track", "2", "it", "should"...
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java#L129-L176
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BaseBankCardTrackData.java
BaseBankCardTrackData.isConsistentWith
public boolean isConsistentWith(final BaseBankCardTrackData other) { if (this == other) { return true; } if (other == null) { return false; } boolean equals = true; if (hasAccountNumber() && other.hasAccountNumber()) { if (!getAccountNumber().equals(other.getAccountNumber())) { equals = false; } } if (hasExpirationDate() && other.hasExpirationDate()) { if (!getExpirationDate().equals(other.getExpirationDate())) { equals = false; } } if (hasServiceCode() && other.hasServiceCode()) { if (!getServiceCode().equals(other.getServiceCode())) { equals = false; } } return equals; }
java
public boolean isConsistentWith(final BaseBankCardTrackData other) { if (this == other) { return true; } if (other == null) { return false; } boolean equals = true; if (hasAccountNumber() && other.hasAccountNumber()) { if (!getAccountNumber().equals(other.getAccountNumber())) { equals = false; } } if (hasExpirationDate() && other.hasExpirationDate()) { if (!getExpirationDate().equals(other.getExpirationDate())) { equals = false; } } if (hasServiceCode() && other.hasServiceCode()) { if (!getServiceCode().equals(other.getServiceCode())) { equals = false; } } return equals; }
[ "public", "boolean", "isConsistentWith", "(", "final", "BaseBankCardTrackData", "other", ")", "{", "if", "(", "this", "==", "other", ")", "{", "return", "true", ";", "}", "if", "(", "other", "==", "null", ")", "{", "return", "false", ";", "}", "boolean",...
Verifies that the available data is consistent between Track 1 and Track 2, or any other track. @return True if the data is consistent.
[ "Verifies", "that", "the", "available", "data", "is", "consistent", "between", "Track", "1", "and", "Track", "2", "or", "any", "other", "track", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BaseBankCardTrackData.java#L186-L223
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java
Track1FormatB.from
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
java
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
[ "public", "static", "Track1FormatB", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track1FormatBPattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack1Data", ...
Parses magnetic track 1 format B data into a Track1FormatB object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track1FormatB instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "1", "format", "B", "data", "into", "a", "Track1FormatB", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java#L78-L119
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track3.java
Track3.from
public static Track3 from(final String rawTrackData) { final Matcher matcher = track3Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack3Data; final String discretionaryData; if (matcher.matches()) { rawTrack3Data = getGroup(matcher, 1); discretionaryData = getGroup(matcher, 2); } else { rawTrack3Data = null; discretionaryData = ""; } return new Track3(rawTrack3Data, discretionaryData); }
java
public static Track3 from(final String rawTrackData) { final Matcher matcher = track3Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack3Data; final String discretionaryData; if (matcher.matches()) { rawTrack3Data = getGroup(matcher, 1); discretionaryData = getGroup(matcher, 2); } else { rawTrack3Data = null; discretionaryData = ""; } return new Track3(rawTrack3Data, discretionaryData); }
[ "public", "static", "Track3", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track3Pattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack3Data", ";", "final...
Parses magnetic track 3 data into a Track3 object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track3instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "3", "data", "into", "a", "Track3", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track3.java#L50-L67
train
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track2.java
Track2.from
public static Track2 from(final String rawTrackData) { final Matcher matcher = track2Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack2Data; final AccountNumber pan; final ExpirationDate expirationDate; final ServiceCode serviceCode; final String discretionaryData; if (matcher.matches()) { rawTrack2Data = getGroup(matcher, 1); pan = new AccountNumber(getGroup(matcher, 2)); expirationDate = new ExpirationDate(getGroup(matcher, 3)); serviceCode = new ServiceCode(getGroup(matcher, 4)); discretionaryData = getGroup(matcher, 5); } else { rawTrack2Data = null; pan = new AccountNumber(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track2(rawTrack2Data, pan, expirationDate, serviceCode, discretionaryData); }
java
public static Track2 from(final String rawTrackData) { final Matcher matcher = track2Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack2Data; final AccountNumber pan; final ExpirationDate expirationDate; final ServiceCode serviceCode; final String discretionaryData; if (matcher.matches()) { rawTrack2Data = getGroup(matcher, 1); pan = new AccountNumber(getGroup(matcher, 2)); expirationDate = new ExpirationDate(getGroup(matcher, 3)); serviceCode = new ServiceCode(getGroup(matcher, 4)); discretionaryData = getGroup(matcher, 5); } else { rawTrack2Data = null; pan = new AccountNumber(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track2(rawTrack2Data, pan, expirationDate, serviceCode, discretionaryData); }
[ "public", "static", "Track2", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track2Pattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack2Data", ";", "final...
Parses magnetic track 2 data into a Track2 object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track2 instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "2", "data", "into", "a", "Track2", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track2.java#L72-L104
train
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.ensureRequiredZnodesExist
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
java
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
[ "void", "ensureRequiredZnodesExist", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "mkdirp", "(", "zookeeper", ",", "znode", ")", ";", "createIfNotThere", "(", "zookeeper", ",", "QUEUE_NODE...
Make sure the required znodes are present on the quorum. @param zookeeper ZooKeeper connection to use. @param znode Base-path for our znodes.
[ "Make", "sure", "the", "required", "znodes", "are", "present", "on", "the", "quorum", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L93-L97
train