index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/MapboxWebMapViewBuilder.java
package com.airbnb.android.airmapview; /** * AirMapView map that uses the web based Mapbox implementation. */ public class MapboxWebMapViewBuilder implements AirMapViewBuilder<WebViewMapFragment, AirMapType> { private AirMapType options; private final String accessToken; private final String mapId; /** * Constructor * * @param accessToken Mapbox Access Token * @param mapId Mapbox Map Id */ public MapboxWebMapViewBuilder(String accessToken, String mapId) { super(); this.accessToken = accessToken; this.mapId = mapId; } @Override public AirMapViewBuilder<WebViewMapFragment, AirMapType> withOptions(AirMapType options) { this.options = options; return this; } /** * Build the map fragment with the requested options * * @return The {@link WebViewMapFragment} map fragment. */ @Override public WebViewMapFragment build() { if (options == null) { options = new MapboxWebMapType(accessToken, mapId); } if (options instanceof MapboxWebMapType) { return MapboxWebViewMapFragment.newInstance(options); } throw new IllegalStateException("Unable to build MapboxWebMapViewFragment." + " options == '" + options + "'"); } }
9,300
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/MapboxWebViewMapFragment.java
package com.airbnb.android.airmapview; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.Locale; public class MapboxWebViewMapFragment extends WebViewMapFragment { public static MapboxWebViewMapFragment newInstance(AirMapType mapType) { return (MapboxWebViewMapFragment) new MapboxWebViewMapFragment().setArguments(mapType); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); MapboxWebMapType mapType = MapboxWebMapType.fromBundle(getArguments()); webView.loadDataWithBaseURL(mapType.getDomain(), mapType.getMapData(getResources()), "text/html", "base64", null); return view; } @Override public void setMapType(MapType type) { String mapBoxType = null; switch (type) { case MAP_TYPE_NORMAL: mapBoxType = "mapbox.streets"; break; case MAP_TYPE_SATELLITE: mapBoxType = "mapbox.satellite"; break; case MAP_TYPE_TERRAIN: mapBoxType = "mapbox.outdoors"; break; } webView.loadUrl(String.format(Locale.US, "javascript:setMapTypeId(\"%1$s\");", mapBoxType)); } }
9,301
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/MapboxWebMapType.java
package com.airbnb.android.airmapview; import android.content.res.Resources; import android.os.Bundle; public class MapboxWebMapType extends AirMapType { private final String mapId; private final String accessToken; protected static final String ARG_MAPBOX_ACCESS_TOKEN = "MAPBOX_ACCESS_TOKEN"; protected static final String ARG_MAPBOX_MAPID = "MAPBOX_MAPID"; /** * Primary Constructor * * @param accessToken Mapbox Access Token * @param mapId Mapbox Map Id */ public MapboxWebMapType(String accessToken, String mapId) { super("mapbox.html", "https://api.tiles.mapbox.com/mapbox.js/v2.2.1", "www.mapbox.com"); this.accessToken = accessToken; this.mapId = mapId; } /** * Private Constructor used for Bundle Serialization * * @param fileName File Name * @param mapUrl Map URL * @param domain Map Domain * @param accessToken Mapbox Access Token * @param mapId Mapbox Map Id */ private MapboxWebMapType(String fileName, String mapUrl, String domain, String accessToken, String mapId) { super(fileName, mapUrl, domain); this.accessToken = accessToken; this.mapId = mapId; } public Bundle toBundle(Bundle bundle) { super.toBundle(bundle); bundle.putString(ARG_MAPBOX_ACCESS_TOKEN, accessToken); bundle.putString(ARG_MAPBOX_MAPID, mapId); return bundle; } public static MapboxWebMapType fromBundle(Bundle bundle) { AirMapType airMapType = AirMapType.fromBundle(bundle); String mapboxAccessToken = bundle.getString(ARG_MAPBOX_ACCESS_TOKEN, ""); String mapboxMapId = bundle.getString(ARG_MAPBOX_MAPID, ""); return new MapboxWebMapType(airMapType.getFileName(), airMapType.getMapUrl(), airMapType.getDomain(), mapboxAccessToken, mapboxMapId); } @Override public String getMapData(Resources resources) { String mapData = super.getMapData(resources); mapData = mapData.replace(ARG_MAPBOX_ACCESS_TOKEN, accessToken); mapData = mapData.replace(ARG_MAPBOX_MAPID, mapId); return mapData; } }
9,302
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletGaodeMapType.java
package com.airbnb.android.airmapview; public class LeafletGaodeMapType extends LeafletMapType { public LeafletGaodeMapType() { super("Gaode"); } }
9,303
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/WebViewMapFragment.java
package com.airbnb.android.airmapview; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.GeolocationPermissions; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.collection.LongSparseArray; import androidx.fragment.app.Fragment; import com.airbnb.android.airmapview.listeners.InfoWindowCreator; import com.airbnb.android.airmapview.listeners.OnCameraChangeListener; import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener; import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback; import com.airbnb.android.airmapview.listeners.OnMapBoundsCallback; import com.airbnb.android.airmapview.listeners.OnMapClickListener; import com.airbnb.android.airmapview.listeners.OnMapLoadedListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerDragListener; import com.airbnb.android.airmapview.listeners.OnSnapshotReadyListener; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale; public abstract class WebViewMapFragment extends Fragment implements AirMapInterface { private static final String TAG = WebViewMapFragment.class.getSimpleName(); protected WebView webView; private ViewGroup mLayout; private OnMapClickListener onMapClickListener; private OnCameraChangeListener onCameraChangeListener; private OnMapLoadedListener onMapLoadedListener; private OnMapMarkerClickListener onMapMarkerClickListener; private OnMapMarkerDragListener onMapMarkerDragListener; private OnInfoWindowClickListener onInfoWindowClickListener; private InfoWindowCreator infoWindowCreator; private OnMapBoundsCallback onMapBoundsCallback; private OnLatLngScreenLocationCallback onLatLngScreenLocationCallback; private LatLng center; private int zoom; private boolean loaded; private boolean ignoreNextMapMove; private View infoWindowView; protected final LongSparseArray<AirMapMarker<?>> markers = new LongSparseArray<>(); private boolean trackUserLocation = false; public WebViewMapFragment setArguments(AirMapType mapType) { setArguments(mapType.toBundle()); return this; } public class GeoWebChromeClient extends WebChromeClient { @Override public void onGeolocationPermissionsShowPrompt( String origin, GeolocationPermissions.Callback callback) { // Always grant permission since the app itself requires location // permission and the user has therefore already granted it callback.invoke(origin, true, false); } } @SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" }) @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_webview, container, false); webView = (WebView) view.findViewById(R.id.webview); mLayout = (ViewGroup) view; WebSettings webViewSettings = webView.getSettings(); webViewSettings.setSupportZoom(true); webViewSettings.setBuiltInZoomControls(false); webViewSettings.setJavaScriptEnabled(true); webViewSettings.setGeolocationEnabled(true); webViewSettings.setAllowFileAccess(false); webViewSettings.setAllowContentAccess(false); webView.setWebChromeClient(new GeoWebChromeClient()); AirMapType mapType = AirMapType.fromBundle(getArguments()); webView.loadDataWithBaseURL(mapType.getDomain(), mapType.getMapData(getResources()), "text/html", "base64", null); webView.addJavascriptInterface(new MapsJavaScriptInterface(), "AirMapView"); return view; } public int getZoom() { return zoom; } public LatLng getCenter() { return center; } public void setCenter(LatLng latLng) { webView.loadUrl(String.format(Locale.US, "javascript:centerMap(%1$f, %2$f);", latLng.latitude, latLng.longitude)); } public void animateCenter(LatLng latLng) { setCenter(latLng); } public void setZoom(int zoom) { webView.loadUrl(String.format(Locale.US, "javascript:setZoom(%1$d);", zoom)); } public void drawCircle(LatLng latLng, int radius) { drawCircle(latLng, radius, CIRCLE_BORDER_COLOR); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor) { drawCircle(latLng, radius, borderColor, CIRCLE_BORDER_WIDTH); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth) { drawCircle(latLng, radius, borderColor, borderWidth, CIRCLE_FILL_COLOR); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth, int fillColor) { webView.loadUrl( String.format(Locale.US, "javascript:addCircle(%1$f, %2$f, %3$d, %4$d, %5$d, %6$d);", latLng.latitude, latLng.longitude, radius, borderColor, borderWidth, fillColor)); } public void highlightMarker(long markerId) { if (markerId != -1) { webView.loadUrl(String.format(Locale.US, "javascript:highlightMarker(%1$d);", markerId)); } } public void unhighlightMarker(long markerId) { if (markerId != -1) { webView.loadUrl(String.format(Locale.US, "javascript:unhighlightMarker(%1$d);", markerId)); } } @Override public boolean isInitialized() { return webView != null && loaded; } @Override public void addMarker(AirMapMarker<?> marker) { LatLng latLng = marker.getLatLng(); markers.put(marker.getId(), marker); webView.loadUrl( String.format(Locale.US, "javascript:addMarkerWithId(%1$f, %2$f, %3$d, '%4$s', '%5$s', %6$b);", latLng.latitude, latLng.longitude, marker.getId(), marker.getTitle(), marker.getSnippet(), marker.getMarkerOptions().isDraggable())); } @Override public void moveMarker(AirMapMarker<?> marker, LatLng to) { marker.setLatLng(to); webView.loadUrl( String.format(Locale.US, "javascript:moveMarker(%1$f, %2$f, '%3$s');", to.latitude, to.longitude, marker.getId())); } @Override public void removeMarker(AirMapMarker<?> marker) { markers.remove(marker.getId()); webView.loadUrl(String.format(Locale.US, "javascript:removeMarker(%1$d);", marker.getId())); } public void clearMarkers() { markers.clear(); webView.loadUrl("javascript:clearMarkers();"); } public void setOnCameraChangeListener(OnCameraChangeListener listener) { onCameraChangeListener = listener; } public void setOnMapLoadedListener(OnMapLoadedListener listener) { onMapLoadedListener = listener; if (loaded) { onMapLoadedListener.onMapLoaded(); } } @Override public void setCenterZoom(LatLng latLng, int zoom) { setCenter(latLng); setZoom(zoom); } @Override public void animateCenterZoom(LatLng latLng, int zoom) { setCenterZoom(latLng, zoom); } public void setOnMarkerClickListener(OnMapMarkerClickListener listener) { onMapMarkerClickListener = listener; } @Override public void setOnMarkerDragListener(OnMapMarkerDragListener listener) { onMapMarkerDragListener = listener; } @Override public void setPadding(int left, int top, int right, int bottom) { // is available in leafletWebViewMap webView.loadUrl(String.format(Locale.US, "javascript:setPadding(%1$d, %2$d, %3$d, %4$d);", left, top, right, bottom)); } @Override public void setMyLocationEnabled(boolean trackUserLocationEnabled) { trackUserLocation = trackUserLocationEnabled; if (trackUserLocationEnabled) { RuntimePermissionUtils.checkLocationPermissions(getActivity(), this); } else { webView.loadUrl("javascript:stopTrackingUserLocation();"); } } @Override public void onLocationPermissionsGranted() { webView.loadUrl("javascript:startTrackingUserLocation();"); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); } @Override public boolean isMyLocationEnabled() { return trackUserLocation; } @Override public void setMyLocationButtonEnabled(boolean enabled) { // no-op } @Override public void setMapToolbarEnabled(boolean enabled) { // no-op } @Override public <T> void addPolyline(AirMapPolyline<T> polyline) { try { JSONArray array = new JSONArray(); for (LatLng point : polyline.getPoints()) { JSONObject json = new JSONObject(); json.put("lat", point.latitude); json.put("lng", point.longitude); array.put(json); } webView.loadUrl(String.format( "javascript:addPolyline(" + array.toString() + ", %1$d, %2$d, %3$d);", polyline.getId(), polyline.getStrokeWidth(), polyline.getStrokeColor())); } catch (JSONException e) { Log.e(TAG, "error constructing polyline JSON", e); } } @Override public <T> void removePolyline(AirMapPolyline<T> polyline) { webView.loadUrl(String.format(Locale.US, "javascript:removePolyline(%1$d);", polyline.getId())); } @Override public <T> void addPolygon(AirMapPolygon<T> polygon) { try { JSONArray array = new JSONArray(); for (LatLng point : polygon.getPolygonOptions().getPoints()) { JSONObject json = new JSONObject(); json.put("lat", point.latitude); json.put("lng", point.longitude); array.put(json); } webView.loadUrl(String.format(Locale.US, "javascript:addPolygon(" + array.toString() + ", %1$d, %2$d, %3$d, %4$d);", polygon.getId(), (int) polygon.getPolygonOptions().getStrokeWidth(), polygon.getPolygonOptions().getStrokeColor(), polygon.getPolygonOptions().getFillColor())); } catch (JSONException e) { Log.e(TAG, "error constructing polyline JSON", e); } } @Override public <T> void removePolygon(AirMapPolygon<T> polygon) { webView.loadUrl(String.format(Locale.US, "javascript:removePolygon(%1$d);", polygon.getId())); } @Override public void setOnMapClickListener(final OnMapClickListener listener) { onMapClickListener = listener; } public void setOnInfoWindowClickListener(OnInfoWindowClickListener listener) { onInfoWindowClickListener = listener; } @Override public void setInfoWindowCreator(GoogleMap.InfoWindowAdapter adapter, InfoWindowCreator creator) { infoWindowCreator = creator; } @Override public void getMapScreenBounds(OnMapBoundsCallback callback) { onMapBoundsCallback = callback; webView.loadUrl("javascript:getBounds();"); } @Override public void getScreenLocation(LatLng latLng, OnLatLngScreenLocationCallback callback) { onLatLngScreenLocationCallback = callback; webView.loadUrl(String.format(Locale.US, "javascript:getScreenLocation(%1$f, %2$f);", latLng.latitude, latLng.longitude)); } @Override public void setCenter(LatLngBounds bounds, int boundsPadding) { webView.loadUrl(String.format(Locale.US, "javascript:setBounds(%1$f, %2$f, %3$f, %4$f);", bounds.northeast.latitude, bounds.northeast.longitude, bounds.southwest.latitude, bounds.southwest.longitude)); } protected boolean isChinaMode() { return false; } private class MapsJavaScriptInterface { private final Handler handler = new Handler(Looper.getMainLooper()); @JavascriptInterface public boolean isChinaMode() { return WebViewMapFragment.this.isChinaMode(); } @JavascriptInterface public void onMapLoaded() { handler.post(new Runnable() { @Override public void run() { if (!loaded) { loaded = true; if (onMapLoadedListener != null) { onMapLoadedListener.onMapLoaded(); } } } }); } @JavascriptInterface public void mapClick(final double lat, final double lng) { handler.post(new Runnable() { @Override public void run() { if (onMapClickListener != null) { onMapClickListener.onMapClick(new LatLng(lat, lng)); } if (infoWindowView != null) { mLayout.removeView(infoWindowView); } } }); } @JavascriptInterface public void getBoundsCallback( double neLat, double neLng, double swLat, double swLng) { final LatLngBounds bounds = new LatLngBounds(new LatLng(swLat, swLng), new LatLng(neLat, neLng)); handler.post(new Runnable() { @Override public void run() { onMapBoundsCallback.onMapBoundsReady(bounds); } }); } @JavascriptInterface public void getLatLngScreenLocationCallback(int x, int y) { final Point point = new Point(x, y); handler.post(new Runnable() { @Override public void run() { onLatLngScreenLocationCallback.onLatLngScreenLocationReady(point); } }); } @JavascriptInterface public void mapMove(double lat, double lng, int zoom) { center = new LatLng(lat, lng); WebViewMapFragment.this.zoom = zoom; handler.post(new Runnable() { @Override public void run() { if (onCameraChangeListener != null) { onCameraChangeListener.onCameraChanged(center, WebViewMapFragment.this.zoom); } if (ignoreNextMapMove) { ignoreNextMapMove = false; return; } if (infoWindowView != null) { mLayout.removeView(infoWindowView); } } }); } @JavascriptInterface public void markerClick(final long markerId) { final AirMapMarker<?> airMapMarker = markers.get(markerId); handler.post(new Runnable() { @Override public void run() { if (onMapMarkerClickListener != null) { onMapMarkerClickListener.onMapMarkerClick(airMapMarker); } if (infoWindowView != null) { mLayout.removeView(infoWindowView); } // TODO convert to custom dialog fragment if (infoWindowCreator != null) { infoWindowView = infoWindowCreator.createInfoWindow(airMapMarker); if (infoWindowView != null) { mLayout.addView(infoWindowView); infoWindowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(@NonNull View v) { if (onInfoWindowClickListener != null) { onInfoWindowClickListener.onInfoWindowClick(airMapMarker); } } }); } } else { webView.loadUrl( String.format(Locale.US, "javascript:showDefaultInfoWindow(%1$d);", markerId)); } ignoreNextMapMove = true; } }); } @JavascriptInterface public void markerDragStart(final long markerId, final double lat, final double lng) { handler.post(new Runnable() { @Override public void run() { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragStart(markerId, new LatLng(lat, lng)); } } }); } @JavascriptInterface public void markerDrag(final long markerId, final double lat, final double lng) { handler.post(new Runnable() { @Override public void run() { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDrag(markerId, new LatLng(lat, lng)); } } }); } @JavascriptInterface public void markerDragEnd(final long markerId, final double lat, final double lng) { handler.post(new Runnable() { @Override public void run() { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragEnd(markerId, new LatLng(lat, lng)); } } }); } @JavascriptInterface public void defaultInfoWindowClick(long markerId) { final AirMapMarker<?> airMapMarker = markers.get(markerId); handler.post(new Runnable() { @Override public void run() { if (onInfoWindowClickListener != null) { onInfoWindowClickListener.onInfoWindowClick(airMapMarker); } } }); } } @Override public void setGeoJsonLayer(AirMapGeoJsonLayer layer) { // clear any existing layer clearGeoJsonLayer(); webView.loadUrl(String.format(Locale.US, "javascript:addGeoJsonLayer(%1$s, %2$f, %3$d, %4$d);", layer.geoJson, layer.strokeWidth, layer.strokeColor, layer.fillColor)); } @Override public void clearGeoJsonLayer() { webView.loadUrl("javascript:removeGeoJsonLayer();"); } @Override public void getSnapshot(OnSnapshotReadyListener listener) { boolean isDrawingCacheEnabled = webView.isDrawingCacheEnabled(); webView.setDrawingCacheEnabled(true); // copy to a new bitmap, otherwise the bitmap will be // destroyed when the drawing cache is destroyed // webView.getDrawingCache can return null if drawing cache is disabled or if the size is 0 Bitmap bitmap = webView.getDrawingCache(); Bitmap newBitmap = null; if (bitmap != null) { newBitmap = bitmap.copy(Bitmap.Config.RGB_565, false); } webView.destroyDrawingCache(); webView.setDrawingCacheEnabled(isDrawingCacheEnabled); listener.onSnapshotReady(newBitmap); } }
9,304
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletGoogleChinaMapType.java
package com.airbnb.android.airmapview; public class LeafletGoogleChinaMapType extends LeafletMapType { public LeafletGoogleChinaMapType() { super("GoogleChina"); } }
9,305
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/FixedWebView.java
package com.airbnb.android.airmapview; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.util.AttributeSet; import android.webkit.WebView; /** * FIXME: Remove this class when AppCompat bug is fixed. * In short, AppCompat 1.1.0 makes WebView crashes on Android 5.0~5.1.1 (Lollipop). * See https://stackoverflow.com/questions/41025200/android-view-inflateexception-error-inflating-class-android-webkit-webview. */ public class FixedWebView extends WebView { public FixedWebView(Context context) { super(fixedContext(context)); } public FixedWebView(Context context, AttributeSet attrs) { super(fixedContext(context), attrs); } public FixedWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(fixedContext(context), attrs, defStyleAttr); } private static Context fixedContext(Context context) { if (Build.VERSION_CODES.LOLLIPOP == Build.VERSION.SDK_INT || Build.VERSION_CODES.LOLLIPOP_MR1 == Build.VERSION.SDK_INT) { return context.createConfigurationContext(new Configuration()); } return context; } }
9,306
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirMapViewTypes.java
package com.airbnb.android.airmapview; /** * Lists all available AirMapView implementations. Types are listed in order of preference. */ public enum AirMapViewTypes { NATIVE, WEB }
9,307
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/MapType.java
package com.airbnb.android.airmapview; public enum MapType { MAP_TYPE_NORMAL, MAP_TYPE_SATELLITE, MAP_TYPE_TERRAIN }
9,308
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirMapInterface.java
package com.airbnb.android.airmapview; import com.airbnb.android.airmapview.listeners.InfoWindowCreator; import com.airbnb.android.airmapview.listeners.OnCameraChangeListener; import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener; import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback; import com.airbnb.android.airmapview.listeners.OnMapBoundsCallback; import com.airbnb.android.airmapview.listeners.OnMapClickListener; import com.airbnb.android.airmapview.listeners.OnMapLoadedListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerDragListener; import com.airbnb.android.airmapview.listeners.OnSnapshotReadyListener; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import org.json.JSONException; public interface AirMapInterface { int CIRCLE_FILL_COLOR = 0xFF00D1C1; int CIRCLE_BORDER_COLOR = 0xFF000000; int CIRCLE_BORDER_WIDTH = 0; /** @return true if the map is fully loaded/initialized. */ boolean isInitialized(); /** Clear all markers from the map */ void clearMarkers(); /** * Add the given marker to the map * * @param marker {@link AirMapMarker} instance to add */ void addMarker(AirMapMarker<?> marker); /** * Move the marker to the given coordinates * * @param marker {@link AirMapMarker} instance to move * @param to {@link LatLng} new destination of the marker */ void moveMarker(AirMapMarker<?> marker, LatLng to); /** * Remove the given marker from the map * * @param marker {@link AirMapMarker} instance to remove */ void removeMarker(AirMapMarker<?> marker); /** * Set the callback for info window click events * * @param listener {@link com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener} * instance */ void setOnInfoWindowClickListener(OnInfoWindowClickListener listener); /** * Specific to Google Play Services maps. Sets the {@link GoogleMap.InfoWindowAdapter} and {@link * com.airbnb.android.airmapview.listeners.InfoWindowCreator} */ void setInfoWindowCreator(GoogleMap.InfoWindowAdapter adapter, InfoWindowCreator creator); /** Draw a circle at the given LatLng, with the given radius */ void drawCircle(LatLng latLng, int radius); /** Draw a circle at the given LatLng, with the given radius and stroke width */ void drawCircle(LatLng latLng, int radius, int borderColor); /** Draw a circle at the given LatLng, with the given radius, stroke width, and stroke color */ void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth); /** * Draw a circle at the given LatLng, with the given radius, stroke width, stroke and fill colors */ void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth, int fillColor); /** * Returns the map screen bounds to the supplied * {@link com.airbnb.android.airmapview.listeners.OnMapBoundsCallback} */ void getMapScreenBounds(OnMapBoundsCallback callback); /** * Returns the point coordinates of the LatLng in the container to the supplied * {@link OnLatLngScreenLocationCallback} */ void getScreenLocation(LatLng latLng, OnLatLngScreenLocationCallback callback); /** Sets the given {@link LatLngBounds} on the map with the specified padding */ void setCenter(LatLngBounds latLngBounds, int boundsPadding); /** Set the map zoom level */ void setZoom(int zoom); /** * Animate the map to center the given {@link LatLng}. Web maps will currently only center the map * (no animation). */ void animateCenter(LatLng latLng); /** Center the map to the given {@link LatLng} */ void setCenter(LatLng latLng); /** @return {@link LatLng} of the center of the map */ LatLng getCenter(); /** @return the zoom level of the map */ int getZoom(); /** Register a callback to be invoked when the camera of the map has changed */ void setOnCameraChangeListener(OnCameraChangeListener onCameraChangeListener); void setOnMapLoadedListener(OnMapLoadedListener onMapLoadedListener); /** * Set the center of the map, and zoom level * * @param latLng the {@link LatLng} to set as center * @param zoom the zoom level */ void setCenterZoom(LatLng latLng, int zoom); /** * Animate the center of the map to the given location and zoom level * * @param latLng the {@link LatLng} to animate to center * @param zoom the zoom level */ void animateCenterZoom(LatLng latLng, int zoom); /** * Register a callback to be invoked when a map marker is clicked * * @param listener {@link com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener} * callback */ void setOnMarkerClickListener(OnMapMarkerClickListener listener); /** * Register a callback to be invoked when a map marker is dragged * * @param listener {@link com.airbnb.android.airmapview.listeners.OnMapMarkerDragListener} * callback */ void setOnMarkerDragListener(OnMapMarkerDragListener listener); /** * Register a callback to be invoked when the map is clicked * * @param listener {@link com.airbnb.android.airmapview.listeners.OnMapClickListener} callback */ void setOnMapClickListener(OnMapClickListener listener); /** Set the map's padding. Currently only works with Google Play Services maps. */ void setPadding(int left, int top, int right, int bottom); /** Enable an indicator for the user's location on the map. */ void setMyLocationEnabled(boolean enabled); /** Check if the user location is being tracked and shown on te map. */ boolean isMyLocationEnabled(); /** Enable a button for centering on user location button. Works with GooglePlay Services maps. */ void setMyLocationButtonEnabled(boolean enabled); /** Enable a toolbar that displays various context-dependent actions. */ void setMapToolbarEnabled(boolean enabled); /** * Add the given polyline to the map * * @param polyline {@link AirMapPolyline} instance to add */ <T> void addPolyline(AirMapPolyline<T> polyline); /** * Remove the given {@link AirMapPolyline} * * @param polyline the {@link AirMapPolyline} to remove */ <T> void removePolyline(AirMapPolyline<T> polyline); /** Sets the type of map tiles that should be displayed */ void setMapType(MapType type); /** * Getting called when runtime location permissions got granted. Any action needing location * permissions should be executed here. */ void onLocationPermissionsGranted(); /** * Add the given polygon to the map * * @param polygon {@link AirMapPolygon} instance to add */ <T> void addPolygon(AirMapPolygon<T> polygon); /** * Remove the given {@link AirMapPolygon} * * @param polygon the {@link AirMapPolygon} to remove */ <T> void removePolygon(AirMapPolygon<T> polygon); /** * Adds a GeoJson layer to the map. Currently only supports adding one layer. * Note: this layer is automatically removed when the map view is destroyed. * * @param layer An {@link AirMapGeoJsonLayer} layer with GeoJson and optional styling attributes */ void setGeoJsonLayer(AirMapGeoJsonLayer layer) throws JSONException; /** Remove GeoJson layer from map, if any. */ void clearGeoJsonLayer(); /** Get a Bitmap snapshot of the current */ void getSnapshot(OnSnapshotReadyListener listener); }
9,309
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletMapType.java
package com.airbnb.android.airmapview; public abstract class LeafletMapType extends AirMapType { // For leaflet, we define some map provider in leaflet_map.html file. // So need to supply a provider name here. (like Google, GoogleChina, Baidu, Gaode) public LeafletMapType(String mapProvider) { super("leaflet_map.html", mapProvider, ""); } }
9,310
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/NativeGoogleMapFragment.java
package com.airbnb.android.airmapview; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import com.airbnb.android.airmapview.listeners.InfoWindowCreator; import com.airbnb.android.airmapview.listeners.OnCameraChangeListener; import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener; import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback; import com.airbnb.android.airmapview.listeners.OnMapBoundsCallback; import com.airbnb.android.airmapview.listeners.OnMapClickListener; import com.airbnb.android.airmapview.listeners.OnMapLoadedListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerDragListener; import com.airbnb.android.airmapview.listeners.OnSnapshotReadyListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.maps.android.geojson.GeoJsonLayer; import com.google.maps.android.geojson.GeoJsonPolygonStyle; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class NativeGoogleMapFragment extends SupportMapFragment implements AirMapInterface { private GoogleMap googleMap; private OnMapLoadedListener onMapLoadedListener; private boolean myLocationEnabled; private GeoJsonLayer layerOnMap; private final Map<Marker, AirMapMarker<?>> markers = new HashMap<>(); public static NativeGoogleMapFragment newInstance(AirGoogleMapOptions options) { return new NativeGoogleMapFragment().setArguments(options); } public NativeGoogleMapFragment setArguments(AirGoogleMapOptions options) { setArguments(options.toBundle()); return this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = super.onCreateView(inflater, container, savedInstanceState); init(); return v; } public void init() { getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { if (googleMap != null && getActivity() != null) { NativeGoogleMapFragment.this.googleMap = googleMap; UiSettings settings = NativeGoogleMapFragment.this.googleMap.getUiSettings(); settings.setZoomControlsEnabled(false); settings.setMyLocationButtonEnabled(false); setMyLocationEnabled(myLocationEnabled); if (onMapLoadedListener != null) { onMapLoadedListener.onMapLoaded(); } } } }); } @Override public boolean isInitialized() { return googleMap != null && getActivity() != null; } @Override public void clearMarkers() { markers.clear(); googleMap.clear(); } @Override public void addMarker(AirMapMarker<?> airMarker) { Marker marker = googleMap.addMarker(airMarker.getMarkerOptions()); airMarker.setGoogleMarker(marker); markers.put(marker, airMarker); } @Override public void moveMarker(AirMapMarker<?> marker, LatLng to) { marker.setLatLng(to); marker.getMarker().setPosition(to); } @Override public void removeMarker(AirMapMarker<?> marker) { Marker nativeMarker = marker.getMarker(); if (nativeMarker != null) { nativeMarker.remove(); markers.remove(nativeMarker); } } @Override public void setOnInfoWindowClickListener(final OnInfoWindowClickListener listener) { googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { AirMapMarker<?> airMarker = markers.get(marker); if (airMarker != null) { listener.onInfoWindowClick(airMarker); } } }); } @Override public void setInfoWindowCreator(GoogleMap.InfoWindowAdapter adapter, InfoWindowCreator creator) { googleMap.setInfoWindowAdapter(adapter); } @Override public void drawCircle(LatLng latLng, int radius) { drawCircle(latLng, radius, CIRCLE_BORDER_COLOR); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor) { drawCircle(latLng, radius, borderColor, CIRCLE_BORDER_WIDTH); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth) { drawCircle(latLng, radius, borderColor, borderWidth, CIRCLE_FILL_COLOR); } @Override public void drawCircle(LatLng latLng, int radius, int borderColor, int borderWidth, int fillColor) { googleMap.addCircle(new CircleOptions() .center(latLng) .strokeColor(borderColor) .strokeWidth(borderWidth) .fillColor(fillColor) .radius(radius)); } @Override public void getMapScreenBounds(OnMapBoundsCallback callback) { final Projection projection = googleMap.getProjection(); int hOffset = getResources().getDimensionPixelOffset(R.dimen.map_horizontal_padding); int vOffset = getResources().getDimensionPixelOffset(R.dimen.map_vertical_padding); LatLngBounds.Builder builder = LatLngBounds.builder(); builder.include(projection.fromScreenLocation(new Point(hOffset, vOffset))); // top-left builder.include(projection.fromScreenLocation( new Point(getView().getWidth() - hOffset, vOffset))); // top-right builder.include(projection.fromScreenLocation( new Point(hOffset, getView().getHeight() - vOffset))); // bottom-left builder.include(projection.fromScreenLocation(new Point(getView().getWidth() - hOffset, getView().getHeight() - vOffset))); // bottom-right callback.onMapBoundsReady(builder.build()); } @Override public void getScreenLocation(LatLng latLng, OnLatLngScreenLocationCallback callback) { callback.onLatLngScreenLocationReady(googleMap.getProjection().toScreenLocation(latLng)); } @Override public void setCenter(LatLngBounds latLngBounds, int boundsPadding) { googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, boundsPadding)); } @Override public void setZoom(int zoom) { googleMap.animateCamera( CameraUpdateFactory.newLatLngZoom(googleMap.getCameraPosition().target, zoom)); } @Override public void animateCenter(LatLng latLng) { googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } @Override public void setCenter(LatLng latLng) { googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); } @Override public LatLng getCenter() { return googleMap.getCameraPosition().target; } @Override public int getZoom() { return (int) googleMap.getCameraPosition().zoom; } @Override public void setOnCameraChangeListener(final OnCameraChangeListener onCameraChangeListener) { googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition cameraPosition) { // camera change can occur programmatically. if (isResumed()) { onCameraChangeListener.onCameraChanged(cameraPosition.target, (int) cameraPosition.zoom); } } }); } @Override public void setOnMapLoadedListener(OnMapLoadedListener onMapLoadedListener) { this.onMapLoadedListener = onMapLoadedListener; } @Override public void setCenterZoom(LatLng latLng, int zoom) { googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom)); } @Override public void animateCenterZoom(LatLng latLng, int zoom) { googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom)); } @Override public void setOnMarkerClickListener(final OnMapMarkerClickListener listener) { googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { AirMapMarker<?> airMarker = markers.get(marker); if (airMarker != null) { return listener.onMapMarkerClick(airMarker); } return false; } }); } @Override public void setOnMarkerDragListener(final OnMapMarkerDragListener listener) { if (listener == null) { googleMap.setOnMarkerDragListener(null); return; } googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { listener.onMapMarkerDragStart(marker); } @Override public void onMarkerDrag(Marker marker) { listener.onMapMarkerDrag(marker); } @Override public void onMarkerDragEnd(Marker marker) { listener.onMapMarkerDragEnd(marker); } }); } @Override public void setOnMapClickListener(final OnMapClickListener listener) { googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { listener.onMapClick(latLng); } }); } @Override public void setPadding(int left, int top, int right, int bottom) { googleMap.setPadding(left, top, right, bottom); } @Override public void setMyLocationEnabled(boolean enabled) { if (myLocationEnabled != enabled) { myLocationEnabled = enabled; if (!RuntimePermissionUtils.checkLocationPermissions(getActivity(), this)) { myLocationEnabled = false; } } } @Override public void onLocationPermissionsGranted() { //noinspection MissingPermission googleMap.setMyLocationEnabled(myLocationEnabled); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); } @Override public boolean isMyLocationEnabled() { return googleMap.isMyLocationEnabled(); } @Override public void setMyLocationButtonEnabled(boolean enabled) { googleMap.getUiSettings().setMyLocationButtonEnabled(enabled); } @Override public void setMapToolbarEnabled(boolean enabled) { googleMap.getUiSettings().setMapToolbarEnabled(enabled); } @Override public <T> void addPolyline(AirMapPolyline<T> polyline) { polyline.addToGoogleMap(googleMap); } @Override public <T> void removePolyline(AirMapPolyline<T> polyline) { polyline.removeFromGoogleMap(); } @Override public <T> void addPolygon(AirMapPolygon<T> polygon) { Polygon googlePolygon = googleMap.addPolygon(polygon.getPolygonOptions()); polygon.setGooglePolygon(googlePolygon); } @Override public <T> void removePolygon(AirMapPolygon<T> polygon) { Polygon nativePolygon = polygon.getGooglePolygon(); if (nativePolygon != null) { nativePolygon.remove(); } } @Override public void setMapType(MapType type) { int nativeType = 0; switch (type) { case MAP_TYPE_NORMAL: nativeType = GoogleMap.MAP_TYPE_NORMAL; break; case MAP_TYPE_SATELLITE: nativeType = GoogleMap.MAP_TYPE_SATELLITE; break; case MAP_TYPE_TERRAIN: nativeType = GoogleMap.MAP_TYPE_TERRAIN; break; } googleMap.setMapType(nativeType); } /** * This method will return the google map if initialized. Will return null otherwise * * @return returns google map if initialized */ public GoogleMap getGoogleMap() { return googleMap; } @Override public void setGeoJsonLayer(final AirMapGeoJsonLayer airMapGeoJsonLayer) throws JSONException { // clear any existing layers clearGeoJsonLayer(); layerOnMap = new GeoJsonLayer(googleMap, new JSONObject(airMapGeoJsonLayer.geoJson)); GeoJsonPolygonStyle style = layerOnMap.getDefaultPolygonStyle(); style.setStrokeColor(airMapGeoJsonLayer.strokeColor); style.setStrokeWidth(airMapGeoJsonLayer.strokeWidth); style.setFillColor(airMapGeoJsonLayer.fillColor); layerOnMap.addLayerToMap(); } @Override public void clearGeoJsonLayer() { if (layerOnMap == null) { return; } layerOnMap.removeLayerFromMap(); layerOnMap = null; } @Override public void getSnapshot(final OnSnapshotReadyListener listener) { getGoogleMap().snapshot(new GoogleMap.SnapshotReadyCallback() { @Override public void onSnapshotReady(Bitmap bitmap) { listener.onSnapshotReady(bitmap); } }); } @Override public void onDestroyView() { clearGeoJsonLayer(); super.onDestroyView(); } }
9,311
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirMapView.java
package com.airbnb.android.airmapview; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.airbnb.android.airmapview.listeners.InfoWindowCreator; import com.airbnb.android.airmapview.listeners.OnCameraChangeListener; import com.airbnb.android.airmapview.listeners.OnCameraMoveListener; import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener; import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback; import com.airbnb.android.airmapview.listeners.OnMapBoundsCallback; import com.airbnb.android.airmapview.listeners.OnMapClickListener; import com.airbnb.android.airmapview.listeners.OnMapInitializedListener; import com.airbnb.android.airmapview.listeners.OnMapLoadedListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerDragListener; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import org.json.JSONException; public class AirMapView extends FrameLayout implements OnCameraChangeListener, OnMapClickListener, OnMapMarkerDragListener, OnMapMarkerClickListener, OnMapLoadedListener, OnInfoWindowClickListener { private static final int INVALID_ZOOM = -1; protected AirMapInterface mapInterface; private OnCameraMoveListener onCameraMoveListener; private OnCameraChangeListener onCameraChangeListener; private boolean mOnCameraMoveTriggered; private OnMapInitializedListener onMapInitializedListener; private OnMapMarkerClickListener onMapMarkerClickListener; private OnMapMarkerDragListener onMapMarkerDragListener; private OnMapClickListener onMapClickListener; private OnInfoWindowClickListener onInfoWindowClickListener; public AirMapView(Context context) { super(context); inflateView(); } public AirMapView(Context context, AttributeSet attrs) { super(context, attrs); inflateView(); } public AirMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); inflateView(); } private void inflateView() { LayoutInflater.from(getContext()).inflate(R.layout.map_view, this); } public void initialize(FragmentManager fragmentManager, AirMapInterface mapInterface) { if (mapInterface == null || fragmentManager == null) { throw new IllegalArgumentException("Either mapInterface or fragmentManager is null"); } this.mapInterface = mapInterface; this.mapInterface.setOnMapLoadedListener(this); fragmentManager.beginTransaction() .replace(getId(), (Fragment) this.mapInterface) .commit(); fragmentManager.executePendingTransactions(); } /** * Used for initialization of the underlying map provider. * * @param fragmentManager required for initialization */ public void initialize(FragmentManager fragmentManager) { AirMapInterface mapInterface = (AirMapInterface) fragmentManager.findFragmentById(R.id.map_frame); if (mapInterface != null) { initialize(fragmentManager, mapInterface); } else { initialize(fragmentManager, new DefaultAirMapViewBuilder(getContext()).builder().build()); } } public void setOnMapInitializedListener(OnMapInitializedListener mapInitializedListener) { onMapInitializedListener = mapInitializedListener; } @Override public boolean dispatchTouchEvent(@NonNull MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_MOVE) { if (onCameraMoveListener != null && !mOnCameraMoveTriggered) { onCameraMoveListener.onCameraMove(); mOnCameraMoveTriggered = true; } } else if (ev.getAction() == MotionEvent.ACTION_UP) { mOnCameraMoveTriggered = false; } return super.dispatchTouchEvent(ev); } public void setOnCameraChangeListener(OnCameraChangeListener onCameraChangeListener) { this.onCameraChangeListener = onCameraChangeListener; } /** * Sets the map {@link com.airbnb.android.airmapview.listeners.OnCameraMoveListener} * * @param onCameraMoveListener The OnCameraMoveListener to be set */ public void setOnCameraMoveListener(OnCameraMoveListener onCameraMoveListener) { this.onCameraMoveListener = onCameraMoveListener; } public final AirMapInterface getMapInterface() { return mapInterface; } public void onDestroyView() { if (isInitialized()) { mapInterface.setMyLocationEnabled(false); } } public int getZoom() { if (isInitialized()) { return mapInterface.getZoom(); } return INVALID_ZOOM; } public LatLng getCenter() { if (isInitialized()) { return mapInterface.getCenter(); } return null; } public boolean setCenter(LatLng latLng) { if (isInitialized()) { mapInterface.setCenter(latLng); return true; } return false; } public boolean animateCenter(LatLng latLng) { if (isInitialized()) { mapInterface.animateCenter(latLng); return true; } return false; } public boolean setZoom(int zoom) { if (isInitialized()) { mapInterface.setZoom(zoom); return true; } return false; } public boolean setCenterZoom(LatLng latLng, int zoom) { if (isInitialized()) { mapInterface.setCenterZoom(latLng, zoom); return true; } return false; } public boolean animateCenterZoom(LatLng latLng, int zoom) { if (isInitialized()) { mapInterface.animateCenterZoom(latLng, zoom); return true; } return false; } public boolean setBounds(LatLngBounds latLngBounds, int boundsPadding) { if (isInitialized()) { mapInterface.setCenter(latLngBounds, boundsPadding); return true; } return false; } public void getScreenBounds(OnMapBoundsCallback callback) { if (isInitialized()) { mapInterface.getMapScreenBounds(callback); } } public void getMapMarkerScreenLocation(LatLng latLng, OnLatLngScreenLocationCallback callback) { if (isInitialized()) { mapInterface.getScreenLocation(latLng, callback); } } public void drawCircle(LatLng latLng, int radius) { if (isInitialized()) { mapInterface.drawCircle(latLng, radius); } } public void drawCircle(LatLng latLng, int radius, int strokeColor) { if (isInitialized()) { mapInterface.drawCircle(latLng, radius, strokeColor); } } public void drawCircle(LatLng latLng, int radius, int strokeColor, int strokeWidth) { if (isInitialized()) { mapInterface.drawCircle(latLng, radius, strokeColor, strokeWidth); } } public void drawCircle(LatLng latLng, int radius, int strokeColor, int strokeWidth, int fillColor) { if (isInitialized()) { mapInterface.drawCircle(latLng, radius, strokeColor, strokeWidth, fillColor); } } public void setPadding(int left, int top, int right, int bottom) { if (isInitialized()) { mapInterface.setPadding(left, top, right, bottom); } } public void setOnMarkerClickListener(OnMapMarkerClickListener listener) { onMapMarkerClickListener = listener; } public void setOnMarkerDragListener(OnMapMarkerDragListener listener) { onMapMarkerDragListener = listener; } public void setOnMapClickListener(OnMapClickListener listener) { onMapClickListener = listener; } public void setInfoWindowAdapter(GoogleMap.InfoWindowAdapter adapter, InfoWindowCreator creator) { if (isInitialized()) { mapInterface.setInfoWindowCreator(adapter, creator); } } public void setOnInfoWindowClickListener(OnInfoWindowClickListener listener) { onInfoWindowClickListener = listener; } public void clearMarkers() { if (isInitialized()) { mapInterface.clearMarkers(); } } public <T> boolean addPolyline(AirMapPolyline<T> polyline) { if (isInitialized()) { mapInterface.addPolyline(polyline); return true; } return false; } public void setMapType(MapType mapType) { mapInterface.setMapType(mapType); } public <T> boolean removePolyline(AirMapPolyline<T> polyline) { if (isInitialized()) { mapInterface.removePolyline(polyline); return true; } return false; } public <T> boolean addPolygon(AirMapPolygon<T> polygon) { if (isInitialized()) { mapInterface.addPolygon(polygon); return true; } return false; } public <T> boolean removePolygon(AirMapPolygon<T> polygon) { if (isInitialized()) { mapInterface.removePolygon(polygon); return true; } return false; } public void setGeoJsonLayer(AirMapGeoJsonLayer layer) throws JSONException { if (!isInitialized()) { return; } mapInterface.setGeoJsonLayer(layer); } public void clearGeoJsonLayer() { if (!isInitialized()) { return; } mapInterface.clearGeoJsonLayer(); } public boolean isInitialized() { return mapInterface != null && mapInterface.isInitialized(); } public boolean addMarker(AirMapMarker<?> marker) { if (isInitialized()) { mapInterface.addMarker(marker); return true; } return false; } public boolean removeMarker(AirMapMarker<?> marker) { if (isInitialized()) { mapInterface.removeMarker(marker); return true; } return false; } public boolean moveMarker(AirMapMarker<?> marker, LatLng to) { if (isInitialized()) { mapInterface.moveMarker(marker, to); return true; } return false; } public void setMyLocationEnabled(boolean trackUserLocation) { mapInterface.setMyLocationEnabled(trackUserLocation); } public void setMyLocationButtonEnabled(boolean enabled) { mapInterface.setMyLocationButtonEnabled(enabled); } @Override public void onCameraChanged(LatLng latLng, int zoom) { if (onCameraChangeListener != null) { onCameraChangeListener.onCameraChanged(latLng, zoom); } } @Override public void onMapClick(LatLng latLng) { if (onMapClickListener != null) { onMapClickListener.onMapClick(latLng); } } @Override public boolean onMapMarkerClick(AirMapMarker<?> airMarker) { if (onMapMarkerClickListener != null) { return onMapMarkerClickListener.onMapMarkerClick(airMarker); } else { return false; } } @Override public void onMapMarkerDragStart(Marker marker) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragStart(marker); } } @Override public void onMapMarkerDrag(Marker marker) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDrag(marker); } } @Override public void onMapMarkerDragEnd(Marker marker) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragEnd(marker); } } @Override public void onMapMarkerDragStart(long id, LatLng latLng) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragStart(id, latLng); } } @Override public void onMapMarkerDrag(long id, LatLng latLng) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDrag(id, latLng); } } @Override public void onMapMarkerDragEnd(long id, LatLng latLng) { if (onMapMarkerDragListener != null) { onMapMarkerDragListener.onMapMarkerDragEnd(id, latLng); } } @Override public void onMapLoaded() { if (isInitialized()) { mapInterface.setOnCameraChangeListener(this); mapInterface.setOnMapClickListener(this); mapInterface.setOnMarkerClickListener(this); mapInterface.setOnMarkerDragListener(this); mapInterface.setOnInfoWindowClickListener(this); if (onMapInitializedListener != null) { // only send map Initialized callback if map initialized successfully and is laid out // initialization can fail if the map leaves the screen before it loads MapLaidOutCheckKt.doWhenMapIsLaidOut(this, () -> onMapInitializedListener.onMapInitialized()); } } } @Override public void onInfoWindowClick(AirMapMarker<?> airMarker) { if (onInfoWindowClickListener != null) { onInfoWindowClickListener.onInfoWindowClick(airMarker); } } }
9,312
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletGoogleMapType.java
package com.airbnb.android.airmapview; public class LeafletGoogleMapType extends LeafletMapType { public LeafletGoogleMapType() { super("Google"); } }
9,313
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirMapPolygon.java
package com.airbnb.android.airmapview; import android.graphics.Color; import androidx.annotation.NonNull; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; public class AirMapPolygon<T> { private static final int STROKE_WIDTH = 1; private static final int STROKE_COLOR = Color.BLUE; private final T object; private final long id; private final PolygonOptions polygonOptions; private Polygon googlePolygon; public AirMapPolygon(T object, long id, PolygonOptions polygonOptions) { this.object = object; this.id = id; this.polygonOptions = polygonOptions; } public T getObject() { return object; } public long getId() { return id; } public PolygonOptions getPolygonOptions() { return polygonOptions; } public Polygon getGooglePolygon() { return googlePolygon; } public void setGooglePolygon(Polygon googlePolygon) { this.googlePolygon = googlePolygon; } public static class Builder<T> { private final PolygonOptions polygonOptions = new PolygonOptions(); private T object; private long id; public Builder() { polygonOptions.strokeWidth(STROKE_WIDTH); polygonOptions.strokeColor(STROKE_COLOR); } public Builder<T> object(T object) { this.object = object; return this; } public Builder<T> id(long id) { this.id = id; return this; } public Builder<T> strokeColor(int color) { polygonOptions.strokeColor(color); return this; } public Builder<T> strokeWidth(float width) { this.polygonOptions.strokeWidth(width); return this; } public Builder<T> fillColor(int color) { this.polygonOptions.fillColor(color); return this; } public Builder<T> geodesic(boolean geodesic) { this.polygonOptions.geodesic(geodesic); return this; } public Builder<T> zIndex(float zIndex) { this.polygonOptions.zIndex(zIndex); return this; } public Builder<T> visible(boolean visible) { this.polygonOptions.visible(visible); return this; } public Builder<T> add(LatLng point) { this.polygonOptions.add(point); return this; } public Builder<T> add(LatLng... points) { this.polygonOptions.add(points); return this; } public Builder<T> addAll(@NonNull Iterable<LatLng> points) { this.polygonOptions.addAll(points); return this; } public Builder<T> addHole(@NonNull Iterable<LatLng> points) { this.polygonOptions.addHole(points); return this; } public AirMapPolygon<T> build() { return new AirMapPolygon<>(object, id, polygonOptions); } } }
9,314
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/WebAirMapViewBuilder.java
package com.airbnb.android.airmapview; /** * AirMapView map that uses the web based Google Maps implementation. */ public class WebAirMapViewBuilder implements AirMapViewBuilder<WebViewMapFragment, AirMapType> { private AirMapType options; @Override public AirMapViewBuilder<WebViewMapFragment, AirMapType> withOptions(AirMapType options) { this.options = options; return this; } /** * Build the map fragment with the requested options * * @return The {@link WebViewMapFragment} map fragment. */ @Override public WebViewMapFragment build() { if (options == null) { options = new GoogleWebMapType(); } if (options instanceof GoogleWebMapType) { return GoogleWebViewMapFragment.newInstance(options); } if (options instanceof GoogleChinaMapType) { return GoogleChinaWebViewMapFragment.newInstance(options); } if (options instanceof LeafletMapType) { return LeafletWebViewMapFragment.newInstance(options); } return null; } }
9,315
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirMapMarker.java
package com.airbnb.android.airmapview; import android.graphics.Bitmap; import androidx.annotation.Nullable; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * Wrapper around {@link MarkerOptions}. Keeps record of data needed to display map markers, as * well as an object T associated with the marker. */ public class AirMapMarker<T> { private final T object; private final long id; private final MarkerOptions markerOptions; private Marker marker; // uses a simple <div> element instead of an image, only available in leaflet map private final @Nullable LeafletDivIcon divIcon; private AirMapMarker(T object, long id, MarkerOptions markerOptions) { this(object, id, markerOptions, null); } private AirMapMarker(T object, long id, @Nullable LeafletDivIcon divIcon) { this(object, id, new MarkerOptions(), divIcon); } private AirMapMarker(T object, long id, MarkerOptions markerOptions, @Nullable LeafletDivIcon divIcon) { this.object = object; this.id = id; this.markerOptions = markerOptions; this.divIcon = divIcon; } public T object() { return object; } public long getId() { return id; } public LatLng getLatLng() { return markerOptions.getPosition(); } void setLatLng(LatLng latLng) { markerOptions.position(latLng); } public String getTitle() { return markerOptions.getTitle(); } public String getSnippet() { return markerOptions.getSnippet(); } public @Nullable LeafletDivIcon getDivIcon() { return divIcon; } public MarkerOptions getMarkerOptions() { return markerOptions; } /** Sets a marker associated to this object */ void setGoogleMarker(Marker marker) { this.marker = marker; } public Builder<T> toBuilder() { Builder<T> builder = new Builder<T>() .id(id) .object(object) .position(markerOptions.getPosition()) .alpha(markerOptions.getAlpha()) .anchor(markerOptions.getAnchorU(), markerOptions.getAnchorV()) .bitmapDescriptor(markerOptions.getIcon()) .infoWindowAnchor(markerOptions.getInfoWindowAnchorU(), markerOptions.getInfoWindowAnchorV()) .snippet(markerOptions.getSnippet()) .title(markerOptions.getTitle()) .draggable(markerOptions.isDraggable()) .visible(markerOptions.isVisible()) .alpha(markerOptions.getAlpha()) .rotation(markerOptions.getRotation()) .flat(markerOptions.isFlat()); if (divIcon != null) { builder.divIconHtml(divIcon.getHtml()) .divIconWidth(divIcon.getWidth()) .divIconHeight(divIcon.getHeight()); } return builder; } public Marker getMarker() { return marker; } public static class Builder<T> { private T object; private long id; private final MarkerOptions markerOptions = new MarkerOptions(); private String divIconHtml; private int divIconHeight; private int divIconWidth; public Builder() { } public Builder<T> object(T object) { this.object = object; return this; } public Builder<T> id(long id) { this.id = id; return this; } public Builder<T> position(LatLng position) { markerOptions.position(position); return this; } public Builder<T> anchor(float u, float v) { markerOptions.anchor(u, v); return this; } public Builder<T> infoWindowAnchor(float u, float v) { markerOptions.infoWindowAnchor(u, v); return this; } public Builder<T> title(String title) { markerOptions.title(title); return this; } public Builder<T> divIconHtml(String divIconHtml) { this.divIconHtml = divIconHtml; return this; } public Builder<T> divIconWidth(int width) { this.divIconWidth = width; return this; } public Builder<T> divIconHeight(int height) { this.divIconHeight = height; return this; } public Builder<T> snippet(String snippet) { markerOptions.snippet(snippet); return this; } public Builder<T> iconId(int iconId) { try { markerOptions.icon(BitmapDescriptorFactory.fromResource(iconId)); } catch (NullPointerException ignored) { // google play services is not available } return this; } public Builder<T> bitmap(Bitmap bitmap) { try { bitmapDescriptor(BitmapDescriptorFactory.fromBitmap(bitmap)); } catch (NullPointerException ignored) { // google play services is not available } return this; } public Builder<T> bitmapDescriptor(BitmapDescriptor bitmap) { markerOptions.icon(bitmap); return this; } public Builder<T> draggable(boolean draggable) { markerOptions.draggable(draggable); return this; } public Builder<T> visible(boolean visible) { markerOptions.visible(visible); return this; } public Builder<T> flat(boolean flat) { markerOptions.flat(flat); return this; } public Builder<T> rotation(float rotation) { markerOptions.rotation(rotation); return this; } public Builder<T> alpha(float alpha) { markerOptions.alpha(alpha); return this; } public Builder<T> zIndex(float zIndex) { markerOptions.zIndex(zIndex); return this; } public AirMapMarker<T> build() { return new AirMapMarker<>(object, id, markerOptions, divIconHtml == null ? null : new LeafletDivIcon(divIconHtml, divIconWidth, divIconHeight)); } } }
9,316
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletDivIcon.java
package com.airbnb.android.airmapview; public class LeafletDivIcon { private final String html; private final int width; private final int height; public LeafletDivIcon(String html, int width, int height) { this.html = html; this.width = width; this.height = height; } public String getHtml() { return html; } public int getWidth() { return width; } public int getHeight() { return height; } }
9,317
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/GoogleChinaWebViewMapFragment.java
package com.airbnb.android.airmapview; public class GoogleChinaWebViewMapFragment extends GoogleWebViewMapFragment { public static GoogleChinaWebViewMapFragment newInstance(AirMapType mapType) { return (GoogleChinaWebViewMapFragment) new GoogleChinaWebViewMapFragment() .setArguments(mapType); } @Override protected boolean isChinaMode() { return true; } }
9,318
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/GoogleWebViewMapFragment.java
package com.airbnb.android.airmapview; import java.util.Locale; public class GoogleWebViewMapFragment extends WebViewMapFragment { public static GoogleWebViewMapFragment newInstance(AirMapType mapType) { return (GoogleWebViewMapFragment) new GoogleWebViewMapFragment().setArguments(mapType); } @Override public void setMapType(MapType type) { String webType = null; switch (type) { case MAP_TYPE_NORMAL: webType = "google.maps.MapTypeId.ROADMAP"; break; case MAP_TYPE_SATELLITE: webType = "google.maps.MapTypeId.SATELLITE"; break; case MAP_TYPE_TERRAIN: webType = "google.maps.MapTypeId.TERRAIN"; break; } webView.loadUrl(String.format(Locale.US, "javascript:setMapTypeId(%1$s);", webType)); } }
9,319
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/DefaultAirMapViewBuilder.java
package com.airbnb.android.airmapview; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; /** * Use this class to request an AirMapView builder. */ public class DefaultAirMapViewBuilder { private static final String TAG = DefaultAirMapViewBuilder.class.getSimpleName(); private final boolean isNativeMapSupported; private final Context context; /** * Default {@link DefaultAirMapViewBuilder} constructor. * * @param context The application context. */ public DefaultAirMapViewBuilder(Context context) { this(context, checkNativeMapSupported(context)); } /** * @param isNativeMapSupported Whether or not Google Play services is available on the * device. If you set this to true and it is not available, * bad things can happen. */ public DefaultAirMapViewBuilder(Context context, boolean isNativeMapSupported) { this.isNativeMapSupported = isNativeMapSupported; this.context = context; } /** * Returns the first/default supported AirMapView implementation in order of preference, as * defined by {@link AirMapViewTypes}. */ public AirMapViewBuilder builder() { if (isNativeMapSupported) { return new NativeAirMapViewBuilder(); } return getWebMapViewBuilder(); } /** * Returns the AirMapView implementation as requested by the mapType argument. Use this method if * you need to request a specific AirMapView implementation that is not necessarily the preferred * type. For example, you can use it to explicit request a web-based map implementation. * * @param mapType Map type for the requested AirMapView implementation. * @return An {@link AirMapViewBuilder} for the requested {@link AirMapViewTypes} mapType. */ public AirMapViewBuilder builder(AirMapViewTypes mapType) { switch (mapType) { case NATIVE: if (isNativeMapSupported) { return new NativeAirMapViewBuilder(); } break; case WEB: return getWebMapViewBuilder(); } throw new UnsupportedOperationException("Requested map type is not supported"); } /** * Decides what the Map Web provider should be used and generates a builder for it. * * @return The AirMapViewBuilder for the selected Map Web provider. */ private AirMapViewBuilder getWebMapViewBuilder() { if (context != null) { try { ApplicationInfo ai = context.getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; String accessToken = bundle.getString("com.mapbox.ACCESS_TOKEN"); String mapId = bundle.getString("com.mapbox.MAP_ID"); if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(mapId)) { return new MapboxWebMapViewBuilder(accessToken, mapId); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Failed to load Mapbox access token and map id", e); } } return new WebAirMapViewBuilder(); } private static boolean checkNativeMapSupported(Context context) { return isGooglePlayServicesAvailable(context); } private static boolean isGooglePlayServicesAvailable(Context context) { return GooglePlayServicesUtil. isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS; } }
9,320
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/AirGoogleMapOptions.java
package com.airbnb.android.airmapview; import android.os.Bundle; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.model.CameraPosition; /** * Wrapper for the {@link GoogleMapOptions} class, which is final. */ public class AirGoogleMapOptions { private final GoogleMapOptions options; public AirGoogleMapOptions(GoogleMapOptions options) { this.options = options; } public AirGoogleMapOptions zOrderOnTop(boolean zOrderOnTop) { options.zOrderOnTop(zOrderOnTop); return this; } public AirGoogleMapOptions useViewLifecycleInFragment(boolean useViewLifecycleInFragment) { options.useViewLifecycleInFragment(useViewLifecycleInFragment); return this; } public AirGoogleMapOptions mapType(int mapType) { options.mapType(mapType); return this; } public AirGoogleMapOptions camera(CameraPosition camera) { options.camera(camera); return this; } public AirGoogleMapOptions zoomControlsEnabled(boolean enabled) { options.zoomControlsEnabled(enabled); return this; } public AirGoogleMapOptions compassEnabled(boolean enabled) { options.compassEnabled(enabled); return this; } public AirGoogleMapOptions scrollGesturesEnabled(boolean enabled) { options.scrollGesturesEnabled(enabled); return this; } public AirGoogleMapOptions zoomGesturesEnabled(boolean enabled) { options.zoomGesturesEnabled(enabled); return this; } public AirGoogleMapOptions tiltGesturesEnabled(boolean enabled) { options.tiltGesturesEnabled(enabled); return this; } public AirGoogleMapOptions rotateGesturesEnabled(boolean enabled) { options.rotateGesturesEnabled(enabled); return this; } public AirGoogleMapOptions liteMode(boolean enabled) { options.liteMode(enabled); return this; } public AirGoogleMapOptions mapToolbarEnabled(boolean enabled) { options.mapToolbarEnabled(enabled); return this; } public Boolean getZOrderOnTop() { return options.getZOrderOnTop(); } public Boolean getUseViewLifecycleInFragment() { return options.getUseViewLifecycleInFragment(); } public int getMapType() { return options.getMapType(); } public CameraPosition getCamera() { return options.getCamera(); } public Boolean getZoomControlsEnabled() { return options.getZoomControlsEnabled(); } public Boolean getCompassEnabled() { return options.getCompassEnabled(); } public Boolean getScrollGesturesEnabled() { return options.getScrollGesturesEnabled(); } public Boolean getZoomGesturesEnabled() { return options.getZoomGesturesEnabled(); } public Boolean getTiltGesturesEnabled() { return options.getTiltGesturesEnabled(); } public Boolean getRotateGesturesEnabled() { return options.getRotateGesturesEnabled(); } public Boolean getLiteMode() { return options.getLiteMode(); } public Boolean getMapToolbarEnabled() { return options.getMapToolbarEnabled(); } public Bundle toBundle() { Bundle args = new Bundle(); // this is internal to SupportMapFragment args.putParcelable("MapOptions", options); return args; } }
9,321
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/LeafletWebViewMapFragment.java
package com.airbnb.android.airmapview; import com.google.android.gms.maps.model.LatLng; import java.util.Locale; public class LeafletWebViewMapFragment extends WebViewMapFragment { public static LeafletWebViewMapFragment newInstance(AirMapType mapType) { return (LeafletWebViewMapFragment) new LeafletWebViewMapFragment().setArguments(mapType); } @Override public void setMapType(MapType type) { String webType = null; switch (type) { case MAP_TYPE_NORMAL: webType = "Normal"; break; case MAP_TYPE_SATELLITE: webType = "Satellite"; break; case MAP_TYPE_TERRAIN: webType = "Terrain"; break; } webView.loadUrl(String.format(Locale.US, "javascript:setMapTypeId('%1$s');", webType)); } @Override public void addMarker(AirMapMarker<?> marker) { if (marker == null || marker.getDivIcon() == null || marker.getDivIcon().getHtml() == null) { super.addMarker(marker); } else { LatLng latLng = marker.getLatLng(); markers.put(marker.getId(), marker); webView.loadUrl( String.format(Locale.US, "javascript:addMarkerWithId(%1$f, %2$f, %3$d, '%4$s', '%5$s', %6$b, '%7$s', %8$d, " + "%9$d);", latLng.latitude, latLng.longitude, marker.getId(), marker.getTitle(), marker.getSnippet(), marker.getMarkerOptions().isDraggable(), marker.getDivIcon().getHtml(), marker.getDivIcon().getWidth(), marker.getDivIcon().getHeight())); } } @Override public void setCenterZoom(LatLng latLng, int zoom) { webView.loadUrl(String.format(Locale.US, "javascript:centerZoomMap(%1$f, %2$f, %3$d);", latLng.latitude, latLng.longitude, zoom)); } @Override public void animateCenter(LatLng latLng) { webView.loadUrl(String.format(Locale.US, "javascript:animateCenterMap(%1$f, %2$f);", latLng.latitude, latLng.longitude)); } @Override public void animateCenterZoom(LatLng latLng, int zoom) { webView.loadUrl(String.format(Locale.US, "javascript:animateCenterZoomMap(%1$f, %2$f, %3$d);", latLng.latitude, latLng.longitude, zoom)); } }
9,322
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/GoogleChinaMapType.java
package com.airbnb.android.airmapview; public class GoogleChinaMapType extends AirMapType { public GoogleChinaMapType() { super("google_map.html", "http://ditu.google.cn/maps/api/js", "www.google.cn"); } }
9,323
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/RuntimePermissionUtils.java
package com.airbnb.android.airmapview; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import androidx.core.app.ActivityCompat; import static androidx.core.content.PermissionChecker.checkSelfPermission; /** * Utility class that handles runtime permissions */ final class RuntimePermissionUtils { private RuntimePermissionUtils() { } private static final byte LOCATION_PERMISSION_REQUEST_CODE = 1; private static final String[] LOCATION_PERMISSIONS = new String[] { "android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION" }; /** * Verifies that any of the given permissions have been granted. * * @return returns true if all permissions have been granted. */ private static boolean verifyPermissions(int... grantResults) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } /** * Returns true if the context has access to any given permissions. */ private static boolean hasSelfPermissions(Context context, String... permissions) { for (String permission : permissions) { if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) { return true; } } return false; } /** * Checks given permissions are needed to show rationale. * * @return returns true if one of the permission is needed to show rationale. */ static boolean shouldShowRequestPermissionRationale(Activity activity, String... permissions) { for (String permission : permissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { return true; } } return false; } /** * Check if any location permissions are granted, and invoke onLocationPermissionsGranted() in the * callback if granted. It will ask users for location permissions and invoke the same callback if * no permission was granted and got granted at runtime. * * @param airMapInterface the callback interface if permission is granted. */ static boolean checkLocationPermissions(Activity targetActivity, AirMapInterface airMapInterface) { if (hasSelfPermissions(targetActivity, LOCATION_PERMISSIONS)) { airMapInterface.onLocationPermissionsGranted(); return true; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { targetActivity.requestPermissions(LOCATION_PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE); } //else don't have location permissions in pre M, don't do anything. return false; } /** * Dispatch actions based off requested permission results.<br /> * Further actions like * 1> Rationale: showing a snack bar to explain why the permissions are needed and * 2> Denied: adding airMapInterface.onLocationPermissionsDenied() * should be added here if needed. */ static void onRequestPermissionsResult(AirMapInterface airMapInterface, int requestCode, int[] grantResults) { switch (requestCode) { case LOCATION_PERMISSION_REQUEST_CODE: if (verifyPermissions(grantResults)) { airMapInterface.onLocationPermissionsGranted(); } break; default: break; } } }
9,324
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapBoundsCallback.java
package com.airbnb.android.airmapview.listeners; import com.google.android.gms.maps.model.LatLngBounds; public interface OnMapBoundsCallback { void onMapBoundsReady(LatLngBounds bounds); }
9,325
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapMarkerClickListener.java
package com.airbnb.android.airmapview.listeners; import com.airbnb.android.airmapview.AirMapMarker; public interface OnMapMarkerClickListener { /* * Called when an airMarker has been clicked or tapped. * Return true if the listener has consumed the event (i.e., the default behavior should not occur); * false otherwise (i.e., the default behavior should occur). * The default behavior is for the camera to move to the marker and an info window to appear. * See: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnMarkerClickListener * */ boolean onMapMarkerClick(AirMapMarker<?> airMarker); }
9,326
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnSnapshotReadyListener.java
package com.airbnb.android.airmapview.listeners; import android.graphics.Bitmap; import androidx.annotation.Nullable; public interface OnSnapshotReadyListener { void onSnapshotReady(@Nullable Bitmap bitmap); }
9,327
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnInfoWindowClickListener.java
package com.airbnb.android.airmapview.listeners; import com.airbnb.android.airmapview.AirMapMarker; public interface OnInfoWindowClickListener { void onInfoWindowClick(AirMapMarker<?> airMarker); }
9,328
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnCameraChangeListener.java
package com.airbnb.android.airmapview.listeners; import com.google.android.gms.maps.model.LatLng; public interface OnCameraChangeListener { void onCameraChanged(LatLng latLng, int zoom); }
9,329
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapClickListener.java
package com.airbnb.android.airmapview.listeners; import com.google.android.gms.maps.model.LatLng; public interface OnMapClickListener { void onMapClick(LatLng latLng); }
9,330
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapMarkerDragListener.java
package com.airbnb.android.airmapview.listeners; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; public interface OnMapMarkerDragListener { void onMapMarkerDragStart(Marker marker); void onMapMarkerDrag(Marker marker); void onMapMarkerDragEnd(Marker marker); void onMapMarkerDragStart(long id, LatLng latLng); void onMapMarkerDrag(long id, LatLng latLng); void onMapMarkerDragEnd(long id, LatLng latLng); }
9,331
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapLoadedListener.java
package com.airbnb.android.airmapview.listeners; public interface OnMapLoadedListener { void onMapLoaded(); }
9,332
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/InfoWindowCreator.java
package com.airbnb.android.airmapview.listeners; import android.view.View; import com.airbnb.android.airmapview.AirMapMarker; public interface InfoWindowCreator { View createInfoWindow(AirMapMarker<?> airMarker); }
9,333
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnLatLngScreenLocationCallback.java
package com.airbnb.android.airmapview.listeners; import android.graphics.Point; public interface OnLatLngScreenLocationCallback { void onLatLngScreenLocationReady(Point point); }
9,334
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnCameraMoveListener.java
package com.airbnb.android.airmapview.listeners; /** * This event is triggered once as soon as the map camera starts moving and then is not triggered * again until the next time the user moves the map camera again. This is handled by AirMapView * instead of the actual GoogleMap implementation since this is not supported by them. */ public interface OnCameraMoveListener { void onCameraMove(); }
9,335
0
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview
Create_ds/AirMapView/library/src/main/java/com/airbnb/android/airmapview/listeners/OnMapInitializedListener.java
package com.airbnb.android.airmapview.listeners; public interface OnMapInitializedListener { void onMapInitialized(); }
9,336
0
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview/sample/Util.java
package com.airbnb.airmapview.sample; import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.Writer; public class Util { private static final String LOGTAG = "Util"; public static String readFromRawResource(Context context, int resourceId) { InputStream resourceReader = context.getResources().openRawResource(resourceId); Writer writer = new StringWriter(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8")); String line = reader.readLine(); while (line != null) { writer.write(line); line = reader.readLine(); } } catch (Exception e) { Log.e(LOGTAG, "Unhandled exception while reading from resource", e); } finally { try { resourceReader.close(); } catch (Exception e) { Log.e(LOGTAG, "Unhandled exception while closing resource", e); } } return writer.toString(); } }
9,337
0
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview/sample/MainActivity.java
package com.airbnb.airmapview.sample; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.airbnb.android.airmapview.AirMapGeoJsonLayer; import com.airbnb.android.airmapview.AirMapInterface; import com.airbnb.android.airmapview.AirMapMarker; import com.airbnb.android.airmapview.AirMapPolygon; import com.airbnb.android.airmapview.AirMapPolyline; import com.airbnb.android.airmapview.AirMapView; import com.airbnb.android.airmapview.AirMapViewTypes; import com.airbnb.android.airmapview.DefaultAirMapViewBuilder; import com.airbnb.android.airmapview.GoogleChinaMapType; import com.airbnb.android.airmapview.LeafletBaiduMapType; import com.airbnb.android.airmapview.LeafletGaodeMapType; import com.airbnb.android.airmapview.LeafletGoogleChinaMapType; import com.airbnb.android.airmapview.LeafletGoogleMapType; import com.airbnb.android.airmapview.LeafletWebViewMapFragment; import com.airbnb.android.airmapview.MapType; import com.airbnb.android.airmapview.WebAirMapViewBuilder; import com.airbnb.android.airmapview.listeners.OnCameraChangeListener; import com.airbnb.android.airmapview.listeners.OnCameraMoveListener; import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener; import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback; import com.airbnb.android.airmapview.listeners.OnMapClickListener; import com.airbnb.android.airmapview.listeners.OnMapInitializedListener; import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener; import com.airbnb.android.airmapview.listeners.OnSnapshotReadyListener; import com.google.android.gms.maps.model.LatLng; import org.json.JSONException; import java.util.Arrays; public class MainActivity extends AppCompatActivity implements OnCameraChangeListener, OnMapInitializedListener, OnMapClickListener, OnCameraMoveListener, OnMapMarkerClickListener, OnInfoWindowClickListener, OnLatLngScreenLocationCallback { private final LogsAdapter adapter = new LogsAdapter(); private static final String TAG = MainActivity.class.getSimpleName(); private AirMapView map; private DefaultAirMapViewBuilder mapViewBuilder; private RecyclerView logsRecyclerView; private View bottomToolsView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mapViewBuilder = new DefaultAirMapViewBuilder(this); map = findViewById(R.id.map); bottomToolsView = findViewById(R.id.bottom_tools); logsRecyclerView = findViewById(R.id.logs); ((LinearLayoutManager) logsRecyclerView.getLayoutManager()).setReverseLayout(true); logsRecyclerView.setAdapter(adapter); Button btnMapTypeNormal = findViewById(R.id.btnMapTypeNormal); Button btnMapTypeSattelite = findViewById(R.id.btnMapTypeSattelite); Button btnMapTypeTerrain = findViewById(R.id.btnMapTypeTerrain); btnMapTypeNormal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(@NonNull View v) { map.setMapType(MapType.MAP_TYPE_NORMAL); } }); btnMapTypeSattelite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(@NonNull View v) { map.setMapType(MapType.MAP_TYPE_SATELLITE); } }); btnMapTypeTerrain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(@NonNull View v) { map.setMapType(MapType.MAP_TYPE_TERRAIN); } }); map.setOnMapClickListener(this); map.setOnCameraChangeListener(this); map.setOnCameraMoveListener(this); map.setOnMarkerClickListener(this); map.setOnMapInitializedListener(this); map.setOnInfoWindowClickListener(this); map.initialize(getSupportFragmentManager()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); AirMapInterface airMapInterface = null; switch (id) { case R.id.action_native_map: try { airMapInterface = mapViewBuilder.builder(AirMapViewTypes.NATIVE).build(); } catch (UnsupportedOperationException e) { Toast.makeText(this, "Sorry, native Google Maps are not supported by this device. " + "Please make sure you have Google Play Services installed.", Toast.LENGTH_SHORT).show(); } break; case R.id.action_mapbox_map: airMapInterface = mapViewBuilder.builder(AirMapViewTypes.WEB).build(); break; case R.id.action_google_web_map: // force Google Web maps since otherwise AirMapViewTypes.WEB returns MapBox by default. airMapInterface = new WebAirMapViewBuilder().build(); break; case R.id.action_google_china_web_map: airMapInterface = new WebAirMapViewBuilder().withOptions(new GoogleChinaMapType()).build(); break; case R.id.action_leaflet_google_web_map: airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGoogleMapType()).build(); break; case R.id.action_leaflet_google_china_web_map: airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGoogleChinaMapType()).build(); break; case R.id.action_baidu_web_map: airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletBaiduMapType()).build(); break; case R.id.action_gaode_web_map: airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGaodeMapType()).build(); break; case R.id.action_clear_logs: adapter.clearLogs(); break; case R.id.add_geojson_layer: // Draws a layer on top of Australia String geoJsonString = Util.readFromRawResource(this, R.raw.google); AirMapGeoJsonLayer layer = new AirMapGeoJsonLayer.Builder(geoJsonString) .strokeColor(getResources().getColor(android.R.color.holo_green_dark)) .strokeWidth(10) .fillColor(getResources().getColor(android.R.color.holo_green_light)) .build(); try { map.getMapInterface().setGeoJsonLayer(layer); } catch (JSONException e) { Log.e(TAG, "Failed to add GeoJson layer", e); } break; case R.id.remove_geojson_layer: map.getMapInterface().clearGeoJsonLayer(); break; case R.id.take_snapshot: map.getMapInterface().getSnapshot(new OnSnapshotReadyListener() { @Override public void onSnapshotReady(@Nullable Bitmap bitmap) { if (bitmap != null) { appendBitmap(bitmap); } else { appendLog("Null bitmap"); } } }); break; case R.id.enable_location: map.setMyLocationEnabled(true); break; case R.id.disable_location: map.setMyLocationEnabled(false); case R.id.add_padding: map.setPadding(0, 0, 0, bottomToolsView.getHeight()); break; case R.id.center_map: { LatLng wfcLatLng = new LatLng(39.918786, 116.459273); map.setCenter(wfcLatLng); break; } case R.id.animateCenter: { LatLng wfcLatLng = new LatLng(39.918786, 116.459273); map.animateCenter(wfcLatLng); break; } case R.id.zoom: map.setZoom(15); break; case R.id.animateCenterZoom: { LatLng wfcLatLng = new LatLng(39.918786, 116.459273); map.animateCenterZoom(wfcLatLng, 15); break; } default: break; } if (airMapInterface != null) { map.initialize(getSupportFragmentManager(), airMapInterface); } return super.onOptionsItemSelected(item); } @Override public void onCameraChanged(LatLng latLng, int zoom) { appendLog("Map onCameraChanged triggered with lat: " + latLng.latitude + ", lng: " + latLng.longitude); } @Override public void onMapInitialized() { appendLog("Map onMapInitialized triggered"); if (map.getMapInterface() instanceof LeafletWebViewMapFragment) { // Baidu map is unavailable in the US, so we show points in China. final LatLng wfcLatLng = new LatLng(39.918786, 116.459273); addMarker("WFC", wfcLatLng, 1); addMarker("Chaoyang Gate", new LatLng(39.923823, 116.433666), 2); String image = "<img width=\"25\" height=\"41\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAMAAAAhFXfZAAAC91BMVEVMaXEzeak2f7I4g7g3g7cua5gzeKg8hJo3grY4g7c3grU0gLI2frE0daAubJc2gbQwd6QzeKk2gLMtd5sxdKIua5g1frA2f7IydaM0e6w2fq41fK01eqo3grgubJgta5cxdKI1f7AydaQydaMxc6EubJgvbJkwcZ4ubZkwcJwubZgubJcydqUydKIxapgubJctbJcubZcubJcvbJYubJcvbZkubJctbJctbZcubJg2f7AubJcrbZcubJcubJcua5g3grY0fq8ubJcubJdEkdEwhsw6i88vhswuhcsuhMtBjMgthMsrg8srgss6is8qgcs8i9A9iMYtg8spgcoogMo7hcMngMonf8olfso4gr8kfck5iM8jfMk4iM8he8k1fro7itAgesk2hs8eecgzfLcofssdeMg0hc4cd8g2hcsxeLQbdsgZdcgxeLImfcszhM0vda4xgckzhM4xg84wf8Yxgs4udKsvfcQucqhUndROmdM1fK0wcZ8vb5w0eqpQm9MzeKhXoNVcpdYydKNWn9VZotVKltJFjsIwcJ1Rms9OlslLmtH///8+kc9epdYzd6dbo9VHkMM2f7FHmNBClM8ydqVcpNY9hro3gLM9hLczealQmcw3fa46f7A8gLMxc6I3eagyc6FIldJMl9JSnNRSntNNl9JPnNJFi75UnM9ZodVKksg8kM45jc09e6ZHltFBk883gbRBh7pDk9EwcaBzn784g7dKkcY2i81Om9M7j85Llc81is09g7Q4grY/j9A0eqxKmdFFltBEjcXf6fFImdBCiLxJl9FGlNFBi78yiMxVndEvbpo6js74+vx+psPP3+o/ks5HkcpGmNCjwdZCkNDM3ehYoNJEls+lxNkxh8xHks0+jdC1zd5Lg6r+/v/H2ufz9/o3jM3t8/edvdM/k89Th61OiLBSjbZklbaTt9BfptdjmL1AicBHj8hGk9FAgK1dkLNTjLRekrdClc/k7fM0icy0y9tgp9c4jc2NtM9Dlc8zicxeXZn3AAAAQ3RSTlMAHDdTb4yPA+LtnEQmC4L2EmHqB7XA0d0sr478x4/Yd5i1zOfyPkf1sLVq4Nh3FvjxopQ2/STNuFzUwFIwxKaejILpIBEV9wAABhVJREFUeF6s1NdyFEcYBeBeoQIhRAkLlRDGrhIgY3BJL8CVeKzuyXFzzjkn5ZxzzuScg3PO8cKzu70JkO0LfxdTU//pM9vTu7Xgf6KqOVTb9X7toRrVEfBf1HTVjZccrT/2by1VV928Yty9ZbVuucdz90frG8DBjl9pVApbOstvmMuvVgaNXSfAAd6pGxpy6yxf5ph43pS/4f3uoaGm2rdu72S9xzOvMymkZFq/ptDrk90mhW7e4zl7HLzhxGWPR20xmSxJ/VqldG5m9XhaVOA1DadsNh3Pu5L2N6QtPO/32JpqQBVVk20oy/Pi2s23WEvyfHbe1thadVQttvm7Llf65gGmXK67XtupyoM7HQhmXdLS8oGWJNeOJ3C5fG5XCEJnkez3/oFdsvgJ4l2ANZwhrJKk/7OSXa+3Vw2WJMlKnGkobouYk6T0TyX30klOUnTD9HJ5qpckL3EW/w4XF3Xd0FGywXUrstrclVsqz5Pd/sXFYyDnPdrLcQODmGOK47IZb4CmibmMn+MYRzFZ5jg33ZL/EJrWcszHmANy3ARBK/IXtciJy8VsitPSdE3uuHxzougojcUdr8/32atnz/ev3f/K5wtpxUTpcaI45zusVDpYtZi+jg0oU9b3x74h7+n9ABvYEZeKaVq0sh0AtLKsFtqNBdeT0MrSzwwlq9+x6xAO4tgOtSzbCjrNQQiNvQUbUEubvzBUeGw26yDCsRHCoLkTHDa7IdOLIThs/gHvChszh2CimE8peRs47cxANI0lYNB5y1DljpOF0IhzBDPOZnDOqYYbeGKECbPzWnXludPphw5c2YBq5zlwXphIbO4VDCZ0gnPfUO1TwZoYwAs2ExPCedAu9DAjfQUjzITQb3jNj0KG2Sgt6BHaQUdYzWz+XmBktOHwanXjaSTcwwziBcuMOtwBmqPrTOxFQR/DRKKPqyur0aiW6cULYsx6tBm0jXpR/AUWR6HRq9WVW6MRhIq5jLyjbaCTDCijyYJNpCajdyobP/eTw0iexBAKkJ3gA5KcQb2zBXsIBckn+xVv8jkZSaEFHE+jFEleAEfayRU0MouNoBmB/L50Ai/HSLIHxcrpCvnhSQAuakKp2C/YbCylJjXRVy/z3+Kv/RrNcCo+WUzlVEhzKffnTQnxeN9fWF88fiNCUdSTsaufaChKWInHeysygfpIqagoakW+vV20J8uyl6TyNKEZWV4oRSPyCkWpgOLSbkCObT8o2r6tlG58HQquf6O0v50tB7JM7F4EORd2dx/K0w/KHsVkLPaoYrwgP/y7krr3SSMA4zj+OBgmjYkxcdIJQyQRKgg2viX9Hddi9UBb29LrKR7CVVEEEXWojUkXNyfTNDE14W9gbHJNuhjDettN3ZvbOvdOqCD3Jp/9l+/wJE+9PkYGjx/fqkys3S2rMozM/o2106rfMUINo6hVqz+eu/hd1c4xTg0TAfy5kV+4UG6+IthHTU9woWmxuKNbTfuCSfovBCxq7EtHqvYL4Sm6F8GVxsSXHMQ07TOi1DKtZxjWaaIyi4CXWjxPccUw8WVbMYY5wxC1mzEyXMJWkllpRloi+Kkoq69sxBTlElF6aAxYUbjXNlhlDZilDnM4U5SlN5biRsRHnbx3mbeWjEh4mEyiuJDl5XcWVmX5GvNkFgLWZM5qwsop4/AWfLhU1cR7k1VVvcYCWRkOI6Xy5gmnphCYIkvzuNYzHzosq2oNk2RtSs8khfUOfHIDgR6ysYBaMpl4uEgk2U/oJTs9AaTSwma7dT69geAE2ZpEjUsn2ieJNHeKfrI3EcAGJ2ZaNgVuC8EBctCLc57P5u5led6IOBkIYkuQMrmmjChs4VkfOerHqSBkPzZlhe06RslZ3zMjk2sscqKwY0RcjKK+LWbzd7KiHhkncs/siFJ+V5eXxD34B8nVuJEpGJNmxN2gH3vSvp7J70tF+D1Ej8qUJD1TkErAND2GZwTFg/LubvmgiBG3SOvdlsqFQrkEzJCL1rstlnVFROixZoDDSuXQFHESwVGlcuQcMb/b42NgjLowh5MTDFE3vNB5qStRIErdCQEh6pLPR92anSUb/wAIhldAaDMpGgAAAABJRU5ErkJggg==\"/>"; addMarker("Dongzhi Gate", new LatLng(39.941823, 116.426319), 3, image, 25, 41); map.animateCenterZoom(wfcLatLng, 11); // Add Polylines LatLng[] latLngs = { new LatLng(39.918786, 116.459273), new LatLng(39.923823, 116.433666), new LatLng(39.919635, 116.448831) }; map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5)); LatLng[] polygonLatLngs = { new LatLng(39.902896, 116.42792), new LatLng(39.902896, 116.43892), new LatLng(39.913896, 116.43892), new LatLng(39.913896, 116.42792) }; map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build()); // Add Circle map.drawCircle(new LatLng(39.919635, 116.448831), 1000); } else { final LatLng airbnbLatLng = new LatLng(37.771883, -122.405224); addMarker("Airbnb HQ", airbnbLatLng, 1); addMarker("Performance Bikes", new LatLng(37.773975, -122.40205), 2); addMarker("REI", new LatLng(37.772127, -122.404411), 3); addMarker("Mapbox", new LatLng(37.77572, -122.41354), 4); map.animateCenterZoom(airbnbLatLng, 10); // Add Polylines LatLng[] latLngs = { new LatLng(37.77977, -122.38937), new LatLng(37.77811, -122.39160), new LatLng(37.77787, -122.38864) }; map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5)); // Add Polygons LatLng[] polygonLatLngs = { new LatLng(37.784, -122.405), new LatLng(37.784, -122.406), new LatLng(37.785, -122.406), new LatLng(37.785, -122.405) }; map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build()); // Add Circle map.drawCircle(new LatLng(37.78443, -122.40805), 1000); // enable my location map.setMyLocationEnabled(false); } } private void addMarker(String title, LatLng latLng, int id) { addMarker(title, latLng, id, null, 0, 0); } private void addMarker(String title, LatLng latLng, int id, String divIconHtml, int iconWidth, int iconHeight) { map.addMarker(new AirMapMarker.Builder() .id(id) .position(latLng) .title(title) .iconId(R.mipmap.icon_location_pin) .divIconHtml(divIconHtml) .divIconWidth(iconWidth) .divIconHeight(iconHeight) .build()); } @Override public void onMapClick(LatLng latLng) { if (latLng != null) { appendLog( "Map onMapClick triggered with lat: " + latLng.latitude + ", lng: " + latLng.longitude); map.getMapInterface().getScreenLocation(latLng, this); } else { appendLog("Map onMapClick triggered with null latLng"); } } @Override public void onCameraMove() { appendLog("Map onCameraMove triggered"); } private void appendLog(String msg) { adapter.addString(msg); logsRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1); } private void appendBitmap(Bitmap bitmap) { adapter.addBitmap(bitmap); logsRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1); } @Override public boolean onMapMarkerClick(AirMapMarker<?> airMarker) { appendLog("Map onMapMarkerClick triggered with id " + airMarker.getId()); return false; } @Override public void onInfoWindowClick(AirMapMarker<?> airMarker) { appendLog("Map onInfoWindowClick triggered with id " + airMarker.getId()); } @Override public void onLatLngScreenLocationReady(Point point) { appendLog("LatLng location on screen (x,y): (" + point.x + "," + point.y + ")"); } }
9,338
0
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview
Create_ds/AirMapView/sample/src/main/java/com/airbnb/airmapview/sample/LogsAdapter.java
package com.airbnb.airmapview.sample; import android.graphics.Bitmap; import androidx.annotation.IntDef; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; public class LogsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @IntDef({VIEW_TYPE_STRING, VIEW_TYPE_BITMAP}) @Retention(RetentionPolicy.SOURCE) private @interface ViewType { } private static final int VIEW_TYPE_STRING = 1; private static final int VIEW_TYPE_BITMAP = 2; private final List<Object> logs = new ArrayList<>(); public void addString(String string) { logs.add(string); notifyItemInserted(logs.size() - 1); } public void addBitmap(Bitmap bitmap) { logs.add(bitmap); notifyItemInserted(logs.size() - 1); } public void clearLogs() { logs.clear(); notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_STRING: return new StringViewHolder(parent); case VIEW_TYPE_BITMAP: return new BitmapViewHolder(parent); default: throw new IllegalArgumentException("Can't make ViewHolder of type " + viewType); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Object log = logs.get(position); switch (holder.getItemViewType()) { case VIEW_TYPE_STRING: ((StringViewHolder) holder).bind((String) log); break; case VIEW_TYPE_BITMAP: ((BitmapViewHolder) holder).bind((Bitmap) log); break; default: throw new IllegalArgumentException("Can't bind view holder of type " + holder.getItemViewType()); } } @ViewType @Override public int getItemViewType(int position) { Object log = logs.get(position); if (log instanceof String) { return VIEW_TYPE_STRING; } else if (log instanceof Bitmap) { return VIEW_TYPE_BITMAP; } else { throw new IllegalArgumentException("Unknown object of type " + log.getClass()); } } @Override public int getItemCount() { return logs.size(); } private static final class StringViewHolder extends RecyclerView.ViewHolder { public StringViewHolder(ViewGroup parent) { super(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_text, parent, false)); } public void bind(String string) { ((TextView) itemView).setText(string); } } private static final class BitmapViewHolder extends RecyclerView.ViewHolder { public BitmapViewHolder(ViewGroup parent) { super(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bitmap, parent, false)); } public void bind(Bitmap bitmap) { ((ImageView) itemView).setImageBitmap(bitmap); } } }
9,339
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/FweApplication.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.annotation.SuppressLint; import android.app.Application; import android.car.Car; import android.car.VehiclePropertyIds; import android.car.hardware.CarPropertyConfig; import android.car.hardware.CarPropertyValue; import android.car.hardware.property.CarPropertyManager; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; public class FweApplication extends Application implements SharedPreferences.OnSharedPreferenceChangeListener, LocationListener { private static final String LOCATION_PROVIDER = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) ? LocationManager.FUSED_PROVIDER : LocationManager.GPS_PROVIDER; private SharedPreferences mPrefs = null; private Elm327 mElm327 = null; private LocationManager mLocationManager = null; private Location mLastLocation = null; private List<Integer> mSupportedPids = null; private final Object mSupportedSignalsLock = new Object(); private CarPropertyManager mCarPropertyManager = null; private boolean mReadVehicleProperties = false; private List<String> mSupportedVehicleProperties = null; @Override public void onLocationChanged(Location loc) { Log.i("FweApplication", "Location change: Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude()); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { Log.i("FweApplication", "Location status changed"); } @Override public void onProviderEnabled(String s) { Log.i("FweApplication", "Location provider enabled: " + s); } @Override public void onProviderDisabled(String s) { Log.i("FweApplication", "Location provider disabled: " + s); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (!mPrefs.getString("vehicle_name", "").equals("") && !mPrefs.getString("mqtt_endpoint_url", "").equals("") && !mPrefs.getString("mqtt_certificate", "").equals("") && !mPrefs.getString("mqtt_private_key", "").equals("") && !mFweThread.isAlive()) { mFweThread.start(); } mDataAcquisitionThread.interrupt(); } @Override public void onCreate() { super.onCreate(); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs.registerOnSharedPreferenceChangeListener(this); onSharedPreferenceChanged(null, null); // Try creating the CarPropertyManager to detect whether we are running on Android Automotive try { mCarPropertyManager = (CarPropertyManager)Car.createCar(this).getCarManager(Car.PROPERTY_SERVICE); } catch (NoClassDefFoundError ignored) { // Not Android Automotive, fall back to ELM327 mode mElm327 = new Elm327(); } mDataAcquisitionThread.start(); } void requestLocationUpdates() { if (mLocationManager == null) { Log.i("FweApplication", "Requesting location access"); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); try { mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, 5000, 10, this); } catch (SecurityException e) { Log.e("FweApplication", "Location access denied"); mLocationManager = null; } } } void serviceLocation() { if (mLocationManager == null) { return; } try { mLastLocation = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER); if (mLastLocation == null) { Log.d("FweApplication", "Location unknown"); return; } Fwe.setLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()); } catch (SecurityException e) { Log.d("FweApplication", "Location access denied"); } } private String getLocationSummary() { if (mLastLocation == null) { return "UNKNOWN"; } return String.format(Locale.getDefault(), "%f, %f", mLastLocation.getLatitude(), mLastLocation.getLongitude()); } private int getUpdateTime() { int updateTime = R.string.default_update_time; try { updateTime = Integer.parseInt(mPrefs.getString("update_time", String.valueOf(R.string.default_update_time))); } catch (Exception ignored) { } if (updateTime == 0) { updateTime = R.string.default_update_time; } updateTime *= 1000; return updateTime; } private static int chrToNibble(char chr) { int res; if (chr >= '0' && chr <= '9') { res = chr - '0'; } else if (chr >= 'A' && chr <= 'F') { res = 10 + chr - 'A'; } else { res = -1; // Invalid hex char } return res; } private static int[] convertResponse(String response) { List<Integer> responseList = new ArrayList<>(); for (int i = 0; (i + 1) < response.length(); i+=2) { int highNibble = chrToNibble(response.charAt(i)); int lowNibble = chrToNibble(response.charAt(i+1)); if (highNibble < 0 || lowNibble < 0) { return null; } responseList.add((highNibble << 4) + lowNibble); // Skip over spaces: if ((i + 2) < response.length() && response.charAt(i+2) == ' ') { i++; } } // Convert list to array: int[] arr = new int[responseList.size()]; for (int i = 0; i < responseList.size(); i++) { arr[i] = responseList.get(i); } return arr; } Thread mDataAcquisitionThread = new Thread(() -> { while (true) { Log.i("FweApplication", "Starting data acquisition"); if (isCar()) { serviceCarProperties(); } else { String bluetoothDevice = mPrefs.getString("bluetooth_device", ""); serviceOBD(bluetoothDevice); } serviceLocation(); // Wait for update time: try { Thread.sleep(getUpdateTime()); } catch (InterruptedException e) { // Carry on } } }); private void serviceOBD(String bluetoothDevice) { mElm327.connect(bluetoothDevice); if (!checkVehicleConnected()) { return; } int[] pidsToRequest = Fwe.getObdPidsToRequest(); if (pidsToRequest.length == 0) { return; } Arrays.sort(pidsToRequest); List<Integer> supportedPids = new ArrayList<>(); for (int pid : pidsToRequest) { if ((mSupportedPids != null) && !mSupportedPids.contains(pid)) { continue; } Log.i("FweApplication", String.format("Requesting PID: 0x%02X", pid)); String request = String.format("01 %02X", pid); String responseString = mElm327.sendObdRequest(request); int[] responseBytes = convertResponse(responseString); if ((responseBytes == null) || (responseBytes.length == 0)) { Log.e("FweApplication", String.format("No response for PID: 0x%02X", pid)); // If vehicle is disconnected: if (mSupportedPids != null) { synchronized (mSupportedSignalsLock) { mSupportedPids = null; } return; } } else { supportedPids.add(pid); Fwe.setObdPidResponse(pid, responseBytes); } } if ((mSupportedPids == null) && (supportedPids.size() > 0)) { StringBuilder sb = new StringBuilder(); for (int b : supportedPids) { sb.append(String.format("%02X ", b)); } Log.i("FweApplication", "Supported PIDs: " + sb.toString()); synchronized (mSupportedSignalsLock) { mSupportedPids = supportedPids; } } } private boolean checkVehicleConnected() { if (mSupportedPids != null) { return true; } Log.i("FweApplication", "Checking if vehicle connected..."); String response = mElm327.sendObdRequest(Elm327.CMD_OBD_SUPPORTED_PIDS_0); int[] responseBytes = convertResponse(response); boolean result = (responseBytes != null) && (responseBytes.length > 0); Log.i("FweApplication", "Vehicle is " + (result ? "CONNECTED" : "DISCONNECTED")); return result; } private int[] getVehiclePropertyIds(int[][] vehiclePropertyInfo) { Set<Integer> propIds = new LinkedHashSet<>(); for (int[] info : vehiclePropertyInfo) { propIds.add(info[0]); } int[] arr = new int[propIds.size()]; int i = 0; for (Integer id : propIds) { arr[i++] = id; } return arr; } private int getVehiclePropertySignalId(int[][] vehiclePropertyInfo, int propId, int areaIndex, int resultIndex) { for (int[] info : vehiclePropertyInfo) { if ((propId == info[0]) && (areaIndex == info[1]) && (resultIndex == info[2])) { return info[3]; } } return -1; } @SuppressLint("DefaultLocale") private void serviceCarProperties() { List<String> supportedProps = new ArrayList<>(); int[][] propInfo = Fwe.getVehiclePropertyInfo(); int[] propIds = getVehiclePropertyIds(propInfo); for (int propId : propIds) { String propName = VehiclePropertyIds.toString(propId); CarPropertyConfig config = mCarPropertyManager.getCarPropertyConfig(propId); if (config == null) { Log.d("serviceCarProperties", "Property unavailable: "+propName); continue; } int[] areaIds = config.getAreaIds(); Class<?> clazz = config.getPropertyType(); for (int areaIndex = 0; areaIndex < areaIds.length; areaIndex++) { int signalId = getVehiclePropertySignalId(propInfo, propId, areaIndex, 0); if (signalId < 0) { Log.d("serviceCarProperties", String.format("More area IDs (%d) than expected (%d) for %s", areaIds.length, areaIndex + 1, propName)); break; } CarPropertyValue propVal; try { propVal = mCarPropertyManager.getProperty(clazz, propId, areaIds[areaIndex]); } catch (IllegalArgumentException ignored) { Log.w("serviceCarProperties", String.format("Could not get %s 0x%X", propName, areaIds[areaIndex])); continue; } catch (SecurityException e) { Log.w("serviceCarProperties", String.format("Access denied for %s 0x%X", propName, areaIds[areaIndex])); continue; } if (areaIndex == 0) { supportedProps.add(propName); } StringBuilder sb = new StringBuilder(); sb.append(String.format("%s 0x%X: ", propName, areaIds[areaIndex])); if (clazz.equals(Boolean.class)) { double val = (boolean) propVal.getValue() ? 1.0 : 0.0; sb.append(val); Fwe.setVehicleProperty(signalId, val); } else if (clazz.equals(Integer.class) || clazz.equals(Float.class)) { double val = ((Number)propVal.getValue()).doubleValue(); sb.append(val); Fwe.setVehicleProperty(signalId, val); } else if (clazz.equals(Integer[].class) || clazz.equals(Long[].class)) { sb.append("["); for (int resultIndex = 0; resultIndex < Array.getLength(propVal.getValue()); resultIndex++) { if (resultIndex > 0) { signalId = getVehiclePropertySignalId(propInfo, propId, areaIndex, resultIndex); if (signalId < 0) { Log.d("serviceCarProperties", String.format("More results (%d) than expected (%d) for %s 0x%X", Array.getLength(propVal.getValue()), resultIndex + 1, propName, areaIds[areaIndex])); break; } } double val = ((Number)Array.get(propVal.getValue(), resultIndex)).doubleValue(); if (resultIndex > 0) { sb.append(", "); } sb.append(val); Fwe.setVehicleProperty(signalId, val); } sb.append("]"); } else { Log.w("serviceCarProperties", "Unsupported type " + clazz.toString() + " for " + propName); continue; } Log.i("serviceCarProperties", sb.toString()); } } if ((mSupportedVehicleProperties == null) && (supportedProps.size() > 0)) { Collections.sort(supportedProps); synchronized (mSupportedSignalsLock) { mSupportedVehicleProperties = supportedProps; } } } Thread mFweThread = new Thread(() -> { Log.i("FweApplication", "Starting FWE"); String vehicleName = mPrefs.getString("vehicle_name", ""); String endpointUrl = mPrefs.getString("mqtt_endpoint_url", ""); String certificate = mPrefs.getString("mqtt_certificate", ""); String privateKey = mPrefs.getString("mqtt_private_key", ""); String mqttTopicPrefix = mPrefs.getString("mqtt_topic_prefix", ""); int res = Fwe.run( getAssets(), vehicleName, endpointUrl, certificate, privateKey, mqttTopicPrefix); if (res != 0) { Log.e("FweApplication", String.format("FWE exited with code %d", res)); } else { Log.i("FweApplication", "FWE finished"); } }); public String getStatusSummary() { StringBuilder sb = new StringBuilder(); synchronized (mSupportedSignalsLock) { if (isCar()) { if (mSupportedVehicleProperties != null) { if (mSupportedVehicleProperties.size() == 0) { sb.append("NONE"); } else { sb.append("Supported vehicle properties: ") .append(String.join(", ", mSupportedVehicleProperties)); } } } else { sb.append("Bluetooth: ") .append(mElm327.getStatus()) .append("\n\n") .append("Supported OBD PIDs: "); if (mSupportedPids == null) { sb.append("VEHICLE DISCONNECTED"); } else if (mSupportedPids.size() == 0) { sb.append("NONE"); } else { for (int pid : mSupportedPids) { sb.append(String.format("%02X ", pid)); } } } } sb.append("\n\n") .append("Location: ") .append(getLocationSummary()) .append("\n\n") .append(Fwe.getStatusSummary()); return sb.toString(); } public boolean isCar() { return mCarPropertyManager != null; } }
9,340
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/BluetoothActivity.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.os.ParcelUuid; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import java.util.Set; public class BluetoothActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bluetooth_device_list); setResult(Activity.RESULT_CANCELED); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } ArrayAdapter<String> deviceListAdapter = new ArrayAdapter<>(this, R.layout.bluetooth_device); ListView deviceListView = findViewById(R.id.device_list); deviceListView.setAdapter(deviceListAdapter); try { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null || !adapter.isEnabled()) { deviceListAdapter.add("Bluetooth disabled"); return; } Set<BluetoothDevice> devices = adapter.getBondedDevices(); if (devices == null) { deviceListAdapter.add("Error getting devices"); return; } for (BluetoothDevice device : devices) { ParcelUuid[] uuids = device.getUuids(); if (uuids == null) { continue; } for (ParcelUuid uuid : uuids) { if (uuid.getUuid().equals(Elm327.SERIAL_PORT_UUID)) { deviceListAdapter.add(device.getName() + "\t" + device.getAddress()); break; } } } if (deviceListAdapter.getCount() == 0) { deviceListAdapter.add("No supported devices"); return; } } catch (SecurityException e) { deviceListAdapter.add("Bluetooth access denied"); return; } deviceListView.setOnItemClickListener((parent, view, position, id) -> { Intent intent = new Intent(); intent.putExtra("bluetooth_device", ((TextView)view).getText().toString()); setResult(Activity.RESULT_OK, intent); finish(); }); } @Override public boolean onSupportNavigateUp() { finish(); return true; } }
9,341
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/ConfigureVehicleActivity.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; public class ConfigureVehicleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_configure_vehicle); setResult(Activity.RESULT_CANCELED); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } EditText linkEditText = findViewById(R.id.provisioning_link); linkEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { Intent intent = new Intent(); intent.putExtra("provisioning_link", linkEditText.getText().toString()); setResult(Activity.RESULT_OK, intent); finish(); } }); } @Override public boolean onSupportNavigateUp() { finish(); return true; } }
9,342
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/AboutActivity.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import java.io.InputStream; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); setResult(Activity.RESULT_CANCELED); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } TextView githubTextView = findViewById(R.id.github); githubTextView.setMovementMethod(LinkMovementMethod.getInstance()); githubTextView.setLinkTextColor(Color.BLUE); try { InputStream stream = getAssets().open("THIRD-PARTY-LICENSES"); int size = stream.available(); byte[] buffer = new byte[size]; stream.read(buffer); stream.close(); String licenses = new String(buffer); EditText editText = findViewById(R.id.licenses); editText.setText(licenses); } catch (IOException ignored) { } } @Override public boolean onSupportNavigateUp() { finish(); return true; } }
9,343
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/MainActivity.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.car.Car; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.JsonReader; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import pub.devrel.easypermissions.AfterPermissionGranted; import pub.devrel.easypermissions.EasyPermissions; public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private static final int REQUEST_PERMISSIONS = 100; private static final int REQUEST_BLUETOOTH = 200; private static final int REQUEST_CONFIGURE_VEHICLE = 300; private static final int REQUEST_ABOUT = 400; SharedPreferences mPrefs = null; @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @AfterPermissionGranted(REQUEST_PERMISSIONS) // This causes this function to be called again after the user has approved access private void requestPermissions() { List<String> perms = new ArrayList<>(); perms.add(Manifest.permission.ACCESS_FINE_LOCATION); String rationale = "Location"; if (((FweApplication)getApplication()).isCar()) { perms.add(Car.PERMISSION_ENERGY); perms.add(Car.PERMISSION_SPEED); rationale += " and car information"; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { perms.add(Manifest.permission.BLUETOOTH_CONNECT); rationale += " and Bluetooth"; } String[] permsArray = perms.toArray(new String[0]); if (!EasyPermissions.hasPermissions(this, permsArray)) { Log.i("requestPermissions", "Requesting permissions"); EasyPermissions.requestPermissions(this, rationale+" access required", REQUEST_PERMISSIONS, permsArray); } else { Log.i("requestPermissions", "Permissions granted, starting data acquisition"); ((FweApplication)getApplication()).requestLocationUpdates(); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (!((FweApplication)getApplication()).isCar()) { findPreference("bluetooth_device").setSummary(mPrefs.getString("bluetooth_device", "No device selected")); } findPreference("vehicle_name").setSummary(mPrefs.getString("vehicle_name", "Not yet configured")); findPreference("update_time").setSummary(mPrefs.getString("update_time", String.valueOf(R.string.default_update_time))); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_BLUETOOTH: if (resultCode == Activity.RESULT_OK) { String deviceParam = data.getExtras().getString("bluetooth_device"); SharedPreferences.Editor edit = mPrefs.edit(); edit.putString("bluetooth_device", deviceParam); edit.apply(); } break; case REQUEST_CONFIGURE_VEHICLE: if (resultCode == Activity.RESULT_OK) { String link = data.getExtras().getString("provisioning_link"); downloadCredentials(link); } break; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); setContentView(R.layout.activity_main); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); TextView versionTextView = (TextView)findViewById(R.id.version); versionTextView.setText(Fwe.getVersion()); mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); mPrefs.registerOnSharedPreferenceChangeListener(this); requestPermissions(); onSharedPreferenceChanged(null, null); Preference bluetoothDevicePreference = (Preference)findPreference("bluetooth_device"); if (((FweApplication)getApplication()).isCar()) { PreferenceScreen preferenceScreen = getPreferenceScreen(); preferenceScreen.removePreference(bluetoothDevicePreference); } else { bluetoothDevicePreference.setOnPreferenceClickListener(preference -> { startActivityForResult(new Intent(MainActivity.this, BluetoothActivity.class), REQUEST_BLUETOOTH); return false; }); Preference vehicleNamePreference = (Preference)findPreference("vehicle_name"); vehicleNamePreference.setOnPreferenceClickListener(preference -> { startActivityForResult(new Intent(MainActivity.this, ConfigureVehicleActivity.class), REQUEST_CONFIGURE_VEHICLE); return false; }); } mStatusUpdateThread.start(); // Handle deep link: Uri appLinkData = getIntent().getData(); if (appLinkData != null) { downloadCredentials(appLinkData.toString()); } // Handle ADB provided credentials: String credentials = getIntent().getStringExtra("credentials"); if (credentials != null) { InputStream inputStream = new ByteArrayInputStream(credentials.getBytes(StandardCharsets.UTF_8)); try { configureCredentials(inputStream); } catch (IOException ignored) { runOnUiThread(() -> { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Error"); alertDialog.setMessage("Invalid credentials"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", (dialog, which) -> dialog.dismiss()); alertDialog.show(); }); } } } @Override public void onDestroy() { if (mStatusUpdateThread != null) { mStatusUpdateThread.interrupt(); } if (mPrefs != null) { mPrefs.unregisterOnSharedPreferenceChangeListener(this); } super.onDestroy(); } public void onAboutClick(View v) { startActivityForResult(new Intent(MainActivity.this, AboutActivity.class), REQUEST_ABOUT); } private void downloadCredentials(String provisioningLink) { Thread t = new Thread(() -> { Log.i("DownloadCredentials", "Provisioning link: " + provisioningLink); final String urlParam = "url="; // First try getting the S3 link normally from the provisioning link: Uri uri = Uri.parse(provisioningLink); String fragment = uri.getFragment(); if (fragment != null) { int urlStart = fragment.indexOf(urlParam); if (urlStart >= 0) { String s3Link = fragment.substring(urlStart + urlParam.length()); if (downloadCredentialsFromS3(s3Link)) { return; } } } // Some QR code scanning apps url decode the provisioning link, so try that next: int urlStart = provisioningLink.indexOf(urlParam); if (urlStart >= 0) { String s3Link = provisioningLink.substring(urlStart + urlParam.length()); if (downloadCredentialsFromS3(s3Link)) { return; } } // Neither worked, show an error: runOnUiThread(() -> { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Error"); alertDialog.setMessage("Invalid provisioning link"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", (dialog, which) -> dialog.dismiss()); alertDialog.show(); }); }); t.start(); } private boolean configureCredentials(InputStream inputStream) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); String vehicleName = null; String endpointUrl = null; String certificate = null; String privateKey = null; String mqttTopicPrefix = ""; reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "vehicle_name": vehicleName = reader.nextString(); break; case "endpoint_url": endpointUrl = reader.nextString(); break; case "certificate": certificate = reader.nextString(); break; case "private_key": privateKey = reader.nextString(); break; case "mqtt_topic_prefix": mqttTopicPrefix = reader.nextString(); break; default: reader.skipValue(); break; } } reader.endObject(); if (vehicleName != null && endpointUrl != null && certificate != null && privateKey != null) { Log.i("configureCredentials", "Configured credentials for vehicle name "+vehicleName); SharedPreferences.Editor edit = mPrefs.edit(); edit.putString("vehicle_name", vehicleName); edit.putString("mqtt_endpoint_url", endpointUrl); edit.putString("mqtt_certificate", certificate); edit.putString("mqtt_private_key", privateKey); edit.putString("mqtt_topic_prefix", mqttTopicPrefix); edit.apply(); return true; } return false; } private boolean downloadCredentialsFromS3(String s3Link) { boolean res = false; try { Log.i("DownloadCredentials", "Trying to download from " + s3Link); URL url = new URL(s3Link); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { res = configureCredentials(urlConnection.getInputStream()); } finally { urlConnection.disconnect(); } } catch (IOException e) { e.printStackTrace(); } return res; } Thread mStatusUpdateThread = new Thread(() -> { Log.i("MainActivity", "Status update thread started"); try { while (true) { Thread.sleep(1000); String status = ((FweApplication)getApplication()).getStatusSummary(); runOnUiThread(() -> findPreference("debug_status").setSummary(status)); } } catch (InterruptedException ignored) { } Log.i("MainActivity", "Status update thread finished"); }); }
9,344
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/Fwe.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.content.res.AssetManager; public class Fwe { /** * Run FWE. This will block until the `stop` method is called. * @param assetManager Android asset manager object, used to access the files in `assets/` * @param vehicleName Name of the vehicle * @param endpointUrl AWS IoT Core endpoint URL * @param certificate AWS IoT Core certificate * @param privateKey AWS IoT Core private key * @param mqttTopicPrefix MQTT topic prefix, which should be "$aws/iotfleetwise/" * @return Zero on success, non-zero on error */ public native static int run( AssetManager assetManager, String vehicleName, String endpointUrl, String certificate, String privateKey, String mqttTopicPrefix); /** * Stop FWE */ public native static void stop(); /** * Get the OBD PIDs that should be requested according to the campaign. * @return Array of OBD PID identifiers to request */ public native static int[] getObdPidsToRequest(); /** * Set the OBD response to a PID request for a given PID. * @param pid PID * @param response Array of response bytes received from vehicle */ public native static void setObdPidResponse(int pid, int[] response); /** * Ingest raw CAN message * @param interfaceId Interface identifier, as defined in the static config JSON file * @param timestamp Timestamp of the message in milliseconds since the epoch, or zero to use the system time * @param messageId CAN message ID in Linux SocketCAN format * @param data CAN message data */ public native static void ingestCanMessage(String interfaceId, long timestamp, int messageId, byte[] data); /** * Set the GPS location * @param latitude Latitude * @param longitude Longitude */ public native static void setLocation(double latitude, double longitude); /** * Returns an array of Android Automotive vehicle property info * @return vehicle property info, with each member containing an array with 4 values: * - Vehicle property ID * - Area index * - Result index * - Signal ID */ public native static int[][] getVehiclePropertyInfo(); /** * Set an Android Automotive vehicle property * @param signalId Signal ID * @param value Vehicle property value */ public native static void setVehicleProperty(int signalId, double value); /** * Get a status summary * @return Status summary */ public native static String getStatusSummary(); /** * Get the version * @return Version */ public native static String getVersion(); static { System.loadLibrary("aws-iot-fleetwise-edge"); } }
9,345
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/Elm327.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; public class Elm327 { public static final UUID SERIAL_PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final int TIMEOUT_RESET_MS = 2000; private static final int TIMEOUT_SETUP_MS = 500; private static final int TIMEOUT_OBD_MS = 500; private static final int TIMEOUT_POLL_MS = 50; private static final String CMD_RESET = "AT Z"; private static final String CMD_SET_PROTOCOL_AUTO = "AT SP 0"; public static final String CMD_OBD_SUPPORTED_PIDS_0 = "01 00"; private BluetoothSocket mSocket = null; private String mLastAddress = ""; private String mStatus = ""; void connect(String deviceParam) { if (!deviceParam.contains("\t")) { mStatus = "No device selected"; return; } String[] deviceInfo = deviceParam.split("\t"); String deviceAddress = deviceInfo[1]; try { if (mSocket != null && mSocket.isConnected()) { if (mLastAddress.equals(deviceAddress)) { return; } Log.i("ELM327.connect", "Closing connection to " + mLastAddress); mSocket.close(); } Log.i("ELM327.connect", "Connecting to " + deviceAddress); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); mSocket = device.createRfcommSocketToServiceRecord(SERIAL_PORT_UUID); mSocket.connect(); mLastAddress = deviceAddress; Log.i("ELM327.connect", "Resetting device"); List<String> res = sendCommand(CMD_RESET, TIMEOUT_RESET_MS); if (res == null) { throw new RuntimeException("Error resetting ELM327"); } String version = res.get(0); Log.i("ELM327.connect", "Set automatic protocol"); res = sendCommand(CMD_SET_PROTOCOL_AUTO, TIMEOUT_SETUP_MS); if (res == null) { throw new RuntimeException("Error setting ELM327 protocol"); } mStatus = "Connected to "+version; } catch (SecurityException e) { mSocket = null; mStatus = "Access denied"; } catch (Exception e) { mSocket = null; mStatus = "Connection error: "+e.getMessage(); } } public String sendObdRequest(String request) { if (mSocket == null) { return ""; } List<String> res = sendCommand(request, TIMEOUT_OBD_MS); if (res == null || res.size() == 0) { return ""; } return res.get(0); } private List<String> sendCommand(String request, int timeout) { try { // Flush the input: receiveResponse(0, null); // Send the command: Log.i("ELM327.tx", request); OutputStream outputStream = mSocket.getOutputStream(); outputStream.write((request + "\r").getBytes()); outputStream.flush(); // Receive the response: return receiveResponse(timeout, request); } catch (Exception e) { mSocket = null; mStatus = "Request error: "+e.getMessage(); return null; } } private List<String> receiveResponse(int timeout, String request) throws IOException { InputStream inputStream = mSocket.getInputStream(); List<String> result = new ArrayList<>(); StringBuilder lineBuilder = new StringBuilder(); int timeoutLeft = timeout; while (true) { if (inputStream.available() == 0) { if (timeoutLeft <= 0) { if (timeout > 0) { Log.e("ELM327.rx", "timeout"); } return null; } try { Thread.sleep(TIMEOUT_POLL_MS); timeoutLeft -= TIMEOUT_POLL_MS; } catch (InterruptedException e) { // Carry on } continue; } char chr = (char)inputStream.read(); switch (chr) { case '>': return result; case '\n': case '\r': String line = lineBuilder.toString(); lineBuilder.setLength(0); if (line.equals("?")) { Log.e("ELM327.rx", line); return null; } else if (line.equals("SEARCHING...")) { Log.d("ELM327.rx", line); } else if (line.equals("") || line.equals(request)) { // Ignore blank lines or the echoed command } else { Log.i("ELM327.rx", line); result.add(line); } break; default: lineBuilder.append(chr); break; } } } public String getStatus() { return mStatus; } }
9,346
0
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws
Create_ds/aws-iot-fleetwise-edge/tools/android-app/app/src/main/java/com/aws/iotfleetwise/StatusEditTextPreference.java
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.aws.iotfleetwise; import android.content.Context; import android.preference.EditTextPreference; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class StatusEditTextPreference extends EditTextPreference { public StatusEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public StatusEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public StatusEditTextPreference(Context context, AttributeSet attrs) { super(context, attrs); } public StatusEditTextPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view); TextView summary = (TextView)view.findViewById(android.R.id.summary); summary.setMaxLines(20); } }
9,347
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/test/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/test/java/com/netflix/turbine/discovery/eureka/EurekaInstanceDiscoveryTest.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import com.google.common.collect.Sets; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.interests.Interest; import com.netflix.eureka2.interests.Interests; import com.netflix.eureka2.registry.DataCenterInfo; import com.netflix.eureka2.registry.InstanceInfo; import com.netflix.eureka2.registry.NetworkAddress; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; public class EurekaInstanceDiscoveryTest { private InstanceInfo upInstanceInfo1; private InstanceInfo downInstanceInfo1; private InstanceInfo upInstanceInfo2; private EurekaClient testEurekaClient; private EurekaInstanceDiscovery eurekaInstanceDiscovery; @Before public void setUp() { NetworkAddress defaultAddress = NetworkAddress.NetworkAddressBuilder.aNetworkAddress() .withLabel("public") .withHostName("hostname") .withProtocolType(NetworkAddress.ProtocolType.IPv4) .build(); DataCenterInfo defaultDataCenterInfo = new BasicDataCenterInfo.Builder() .withName("default") .withAddresses(defaultAddress) .build(); this.upInstanceInfo1 = new InstanceInfo.Builder() .withId("id-1") .withApp("API") .withStatus(InstanceInfo.Status.UP) .withDataCenterInfo(defaultDataCenterInfo) .withPorts(Sets.newHashSet(new ServicePort(8080, false))) .build(); this.downInstanceInfo1 = new InstanceInfo.Builder() .withId("id-1") .withApp("API") .withStatus(InstanceInfo.Status.DOWN) .withDataCenterInfo(defaultDataCenterInfo) .withPorts(Sets.newHashSet(new ServicePort(8080, false))) .build(); this.upInstanceInfo2 = new InstanceInfo.Builder() .withId("id-2") .withApp("API") .withStatus(InstanceInfo.Status.UP) .withDataCenterInfo(defaultDataCenterInfo) .withPorts(Sets.newHashSet(new ServicePort(8080, false))) .build(); testEurekaClient = new TestEurekaClient(); eurekaInstanceDiscovery = new EurekaInstanceDiscovery(testEurekaClient); } @After public void tearDown() { testEurekaClient.close(); } @Test public void testUpdateToSameInstance() { EurekaInstance a = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Add, upInstanceInfo1)); EurekaInstance b = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Add, downInstanceInfo1)); Assert.assertEquals(EurekaInstance.Status.UP, a.getStatus()); Assert.assertEquals(EurekaInstance.Status.DOWN, b.getStatus()); TestSubscriber<EurekaInstance> ts = new TestSubscriber<>(); testEurekaClient.register(upInstanceInfo1); testEurekaClient.update(downInstanceInfo1); eurekaInstanceDiscovery.getInstanceEvents("API").subscribe(ts); ts.assertReceivedOnNext(Arrays.asList(a, b)); } @Test public void testInstanceRegisterUnregister() { EurekaInstance a = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Add, upInstanceInfo1)); EurekaInstance b = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Delete, upInstanceInfo1)); Assert.assertEquals(EurekaInstance.Status.UP, a.getStatus()); Assert.assertEquals(EurekaInstance.Status.DOWN, b.getStatus()); TestSubscriber<EurekaInstance> ts = new TestSubscriber<>(); testEurekaClient.register(upInstanceInfo1); testEurekaClient.unregister(upInstanceInfo1); eurekaInstanceDiscovery.getInstanceEvents("API").subscribe(ts); ts.assertReceivedOnNext(Arrays.asList(a, b)); } @Test public void testMultipleInstances() { EurekaInstance a = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Add, upInstanceInfo1)); EurekaInstance b = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Delete, upInstanceInfo1)); EurekaInstance c = EurekaInstance.from(new ChangeNotification<>(ChangeNotification.Kind.Add, upInstanceInfo2)); Assert.assertEquals(EurekaInstance.Status.UP, a.getStatus()); Assert.assertEquals(EurekaInstance.Status.DOWN, b.getStatus()); Assert.assertEquals(EurekaInstance.Status.UP, c.getStatus()); TestSubscriber<EurekaInstance> ts = new TestSubscriber<>(); testEurekaClient.register(upInstanceInfo1); testEurekaClient.unregister(upInstanceInfo1); testEurekaClient.register(upInstanceInfo2); eurekaInstanceDiscovery.getInstanceEvents("API").subscribe(ts); ts.assertReceivedOnNext(Arrays.asList(a, b, c)); } private static class TestEurekaClient extends EurekaClient { private Queue<ChangeNotification<InstanceInfo>> messages; TestEurekaClient() { this.messages = new ConcurrentLinkedQueue<>(); } @Override public Observable<Void> register(InstanceInfo instanceInfo) { messages.add(new ChangeNotification<>(ChangeNotification.Kind.Add, instanceInfo)); return Observable.empty(); } @Override public Observable<Void> update(InstanceInfo instanceInfo) { messages.add(new ChangeNotification<>(ChangeNotification.Kind.Modify, instanceInfo)); return Observable.empty(); } @Override public Observable<Void> unregister(InstanceInfo instanceInfo) { messages.add(new ChangeNotification<>(ChangeNotification.Kind.Delete, instanceInfo)); return Observable.empty(); } @Override public Observable<ChangeNotification<InstanceInfo>> forInterest(Interest<InstanceInfo> interest) { return Observable.from(messages); } @Override public Observable<ChangeNotification<InstanceInfo>> forApplication(String s) { return forInterest(Interests.forApplications(s)); } @Override public Observable<ChangeNotification<InstanceInfo>> forVips(String... strings) { throw new RuntimeException("Not Implemented"); } @Override public void close() { messages.clear(); } } }
9,348
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery/eureka/StartEurekaTurbine.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import com.netflix.eureka2.client.Eureka; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.client.resolver.ServerResolvers; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.turbine.Turbine; public class StartEurekaTurbine { private static final Logger logger = LoggerFactory.getLogger(StartEurekaTurbine.class); public static void main(String[] args) { OptionParser optionParser = new OptionParser(); optionParser.accepts("port").withRequiredArg(); optionParser.accepts("app").withRequiredArg(); optionParser.accepts("urlTemplate").withRequiredArg(); optionParser.accepts("eurekaPort").withRequiredArg(); optionParser.accepts("eurekaHostname").withRequiredArg(); OptionSet options = optionParser.parse(args); int port = -1; if (!options.has("port")) { System.err.println("Argument -port required for SSE HTTP server to start on. Eg. -port 8888"); System.exit(-1); } else { try { port = Integer.parseInt(String.valueOf(options.valueOf("port"))); } catch (NumberFormatException e) { System.err.println("Value of port must be an integer but was: " + options.valueOf("port")); } } String app = null; if (!options.has("app")) { System.err.println("Argument -app required for Eureka instance discovery. Eg. -app api"); System.exit(-1); } else { app = String.valueOf(options.valueOf("app")); } String template = null; if (!options.has("urlTemplate")) { System.err.println("Argument -urlTemplate required. Eg. http://" + EurekaStreamDiscovery.HOSTNAME + "/metrics.stream"); System.exit(-1); } else { template = String.valueOf(options.valueOf("urlTemplate")); if (!template.contains(EurekaStreamDiscovery.HOSTNAME)) { System.err.println("Argument -urlTemplate must contain " + EurekaStreamDiscovery.HOSTNAME + " marker. Eg. http://" + EurekaStreamDiscovery.HOSTNAME + "/metrics.stream"); System.exit(-1); } } // // Eureka2 Configs // int eurekaPort = -1; if (!options.has("eurekaPort")) { System.err.println("Argument --eurekaPort required: port of eurekaServer"); System.exit(-1); } else { try { eurekaPort = Integer.parseInt(String.valueOf(options.valueOf("eurekaPort"))); } catch (NumberFormatException e) { System.err.println("Value of eurekaPort must be an integer but was: " + options.valueOf("eurekaPort")); } } String eurekaHostname = null; if (!options.has("eurekaHostname")) { System.err.println("Argument --eurekaHostname required: hostname of eurekaServer"); System.exit(-1); } else { eurekaHostname = String.valueOf(options.valueOf("eurekaHostname")); } logger.info("Turbine => Eureka App: " + app); logger.info("Turbine => Eureka URL Template: " + template); try { EurekaClient eurekaClient = Eureka.newClient(ServerResolvers.just(eurekaHostname, eurekaPort), null); Turbine.startServerSentEventServer(port, EurekaStreamDiscovery.create(app, template, eurekaClient)); } catch (Throwable e) { e.printStackTrace(); } } }
9,349
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery/eureka/EurekaInstanceDiscovery.java
/* * Copyright 2013 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import com.netflix.eureka2.client.Eureka; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.client.resolver.ServerResolvers; import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.registry.InstanceInfo; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; /** * Class that encapsulates an {@link InstanceDicovery} implementation that uses Eureka (see https://github.com/Netflix/eureka) * The plugin requires a list of applications configured. It then queries the set of instances for each application. * Instance information retrieved from Eureka must be translated to something that Turbine can understand i.e the * {@link EurekaInstance} class. * * All the logic to perform this translation can be overridden here, so that you can provide your own implementation if needed. */ public class EurekaInstanceDiscovery { private static final Logger logger = LoggerFactory.getLogger(EurekaInstanceDiscovery.class); private final EurekaClient eurekaClient; public static void main(String[] args) { OptionParser optionParser = new OptionParser(); optionParser.accepts("eurekaPort").withRequiredArg(); optionParser.accepts("eurekaHostname").withRequiredArg(); optionParser.accepts("app").withRequiredArg(); OptionSet options = optionParser.parse(args); int eurekaPort = -1; if (!options.has("eurekaPort")) { System.err.println("Argument --eurekaPort required: port of eurekaServer"); System.exit(-1); } else { try { eurekaPort = Integer.parseInt(String.valueOf(options.valueOf("eurekaPort"))); } catch (NumberFormatException e) { System.err.println("Value of eurekaPort must be an integer but was: " + options.valueOf("eurekaPort")); } } String eurekaHostname = null; if (!options.has("eurekaHostname")) { System.err.println("Argument --eurekaHostname required: hostname of eurekaServer"); System.exit(-1); } else { eurekaHostname = String.valueOf(options.valueOf("eurekaHostname")); } String app = null; if (!options.has("app")) { System.err.println("Argument --app required for Eureka instance discovery. Eg. -app api"); System.exit(-1); } else { app = String.valueOf(options.valueOf("app")); } EurekaClient eurekaClient = Eureka.newClient(ServerResolvers.just(eurekaHostname, eurekaPort), null); new EurekaInstanceDiscovery(eurekaClient) .getInstanceEvents(app).toBlocking().forEach(i -> System.out.println(i)); } public EurekaInstanceDiscovery(EurekaClient eurekaClient) { this.eurekaClient = eurekaClient; } public Observable<EurekaInstance> getInstanceEvents(String appName) { return eurekaClient.forApplication(appName) .map(new Func1<ChangeNotification<InstanceInfo>, EurekaInstance>() { @Override public EurekaInstance call(ChangeNotification<InstanceInfo> notification) { try { return EurekaInstance.from(notification); } catch (Exception e) { logger.warn("Error parsing notification from eurekaClient {}", notification); } return null; } }).filter(new Func1<EurekaInstance, Boolean>() { @Override public Boolean call(EurekaInstance eurekaInstance) { return eurekaInstance != null; } }); } }
9,350
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery/eureka/EurekaInstance.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.registry.InstanceInfo; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.NetworkAddress.ProtocolType; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.stream.Collectors; public class EurekaInstance { public static enum Status { UP, DOWN } private final String cluster; private final Status status; private final String hostname; private final int port; private final Map<String, Object> attributes; private EurekaInstance(String cluster, Status status, String hostname, int port) { this.cluster = cluster; this.status = status; this.hostname = hostname; this.port = port; this.attributes = new HashMap<>(); } public static EurekaInstance from(ChangeNotification<InstanceInfo> notification) { InstanceInfo instanceInfo = notification.getData(); String cluster = instanceInfo.getApp(); String ipAddress = instanceInfo.getDataCenterInfo() .getAddresses().stream() .filter(na -> na.getProtocolType() == ProtocolType.IPv4) .collect(Collectors.toList()).get(0).getIpAddress(); HashSet<ServicePort> servicePorts = instanceInfo.getPorts(); int port = instanceInfo.getPorts().iterator().next().getPort(); Status status = ChangeNotification.Kind.Delete == notification.getKind() ? Status.DOWN // count deleted as DOWN : (InstanceInfo.Status.UP == instanceInfo.getStatus() ? Status.UP : Status.DOWN); return new EurekaInstance(cluster, status, ipAddress, port); } public Status getStatus() { return status; } public String getCluster() { return cluster; } public String getHost() { return hostname; } public boolean isUp() { return Status.UP == status; } public int getPort() { return port; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof EurekaInstance)) return false; EurekaInstance that = (EurekaInstance) o; if (port != that.port) return false; if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null) return false; if (cluster != null ? !cluster.equals(that.cluster) : that.cluster != null) return false; if (hostname != null ? !hostname.equals(that.hostname) : that.hostname != null) return false; if (status != that.status) return false; return true; } @Override public int hashCode() { int result = cluster != null ? cluster.hashCode() : 0; result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (hostname != null ? hostname.hashCode() : 0); result = 31 * result + port; result = 31 * result + (attributes != null ? attributes.hashCode() : 0); return result; } @Override public String toString() { return "EurekaInstance{" + "cluster='" + cluster + '\'' + ", status=" + status + ", hostname='" + hostname + '\'' + ", port=" + port + ", attributes=" + attributes + '}'; } }
9,351
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka2/src/main/java/com/netflix/turbine/discovery/eureka/EurekaStreamDiscovery.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import java.net.URI; import com.netflix.eureka2.client.EurekaClient; import com.netflix.turbine.discovery.StreamAction; import com.netflix.turbine.discovery.StreamDiscovery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; public class EurekaStreamDiscovery implements StreamDiscovery { private static final Logger logger = LoggerFactory.getLogger(EurekaStreamDiscovery.class); public static EurekaStreamDiscovery create(String appName, String uriTemplate, EurekaClient eurekaClient) { return new EurekaStreamDiscovery(appName, uriTemplate, eurekaClient); } public final static String HOSTNAME = "{HOSTNAME}"; private final String uriTemplate; private final String appName; private final EurekaClient eurekaClient; private EurekaStreamDiscovery(String appName, String uriTemplate, EurekaClient eurekaClient) { this.appName = appName; this.uriTemplate = uriTemplate; this.eurekaClient = eurekaClient; } @Override public Observable<StreamAction> getInstanceList() { return new EurekaInstanceDiscovery(eurekaClient) .getInstanceEvents(appName) .map(ei -> { URI uri; String uriString = uriTemplate.replace(HOSTNAME, ei.getHost() + ":" + ei.getPort()); try { uri = new URI(uriString); } catch (Exception e) { throw new RuntimeException("Invalid URI: " + uriString, e); } if (ei.getStatus() == EurekaInstance.Status.UP) { logger.info("StreamAction ADD"); return StreamAction.create(StreamAction.ActionType.ADD, uri); } else { logger.info("StreamAction REMOVE"); return StreamAction.create(StreamAction.ActionType.REMOVE, uri); } }); } }
9,352
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/test/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/test/java/com/netflix/turbine/discovery/eureka/EurekaInstanceDiscoveryTest.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.turbine.discovery.eureka.EurekaInstance; import com.netflix.turbine.discovery.eureka.EurekaInstanceDiscovery; import com.netflix.turbine.discovery.eureka.EurekaInstance.Status; public class EurekaInstanceDiscoveryTest { @Test public void testDeltaRemoveDuplicateAddSecond() { EurekaInstance a = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname1").setStatus(InstanceStatus.UP).build()); Observable<List<EurekaInstance>> first = Observable.just(a).toList(); EurekaInstance b = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname1").setStatus(InstanceStatus.DOWN).build()); Observable<List<EurekaInstance>> second = Observable.just(a, b).toList(); TestSubscriber<EurekaInstance> ts = new TestSubscriber<EurekaInstance>(); Observable .just(first, second) .flatMap(o -> o) .startWith(new ArrayList<EurekaInstance>()) .buffer(2, 1) .filter(l -> l.size() == 2) .flatMap(EurekaInstanceDiscovery::delta) .subscribe(ts); ts.assertReceivedOnNext(Arrays.asList(a, b)); } @Test public void testDrop() { EurekaInstance a = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname1").setStatus(InstanceStatus.UP).build()); Observable<List<EurekaInstance>> first = Observable.just(a).toList(); EurekaInstance b = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname1").setStatus(InstanceStatus.DOWN).build()); Observable<List<EurekaInstance>> second = Observable.just(b).toList(); TestSubscriber<EurekaInstance> ts = new TestSubscriber<EurekaInstance>(); Observable .just(first, second) .flatMap(o -> o) .startWith(new ArrayList<EurekaInstance>()) .buffer(2, 1) .filter(l -> l.size() == 2) .flatMap(EurekaInstanceDiscovery::delta) .subscribe(ts); ts.assertReceivedOnNext(Arrays.asList(a, b)); } @Test public void testAddRemoveAddRemove() { // start with 4 EurekaInstance a1 = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname1").setStatus(InstanceStatus.UP).build()); EurekaInstance a2 = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname2").setStatus(InstanceStatus.UP).build()); EurekaInstance a3 = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname3").setStatus(InstanceStatus.UP).build()); EurekaInstance a4 = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname4").setStatus(InstanceStatus.UP).build()); Observable<List<EurekaInstance>> first = Observable.just(a1, a2, a3, a4).toList(); // mark one of them as DOWN EurekaInstance b4 = EurekaInstance.create(InstanceInfo.Builder.newBuilder() .setAppName("api").setHostName("hostname4").setStatus(InstanceStatus.DOWN).build()); Observable<List<EurekaInstance>> second = Observable.just(a1, a2, a3, b4).toList(); // then completely drop 2 of them Observable<List<EurekaInstance>> third = Observable.just(a1, a2).toList(); TestSubscriber<EurekaInstance> ts = new TestSubscriber<EurekaInstance>(); Observable .just(first, second, third) .flatMap(o -> o) .startWith(new ArrayList<EurekaInstance>()) .buffer(2, 1) .filter(l -> l.size() == 2) .flatMap(EurekaInstanceDiscovery::delta) .subscribe(ts); // expected ... // UP a1, UP a2, UP a3, UP a4 // DOWN b4 // DOWN a3 ts.assertReceivedOnNext(Arrays.asList(a1, a2, a3, a4, b4, EurekaInstance.create(Status.DOWN, a3.getInstanceInfo()), b4)); } }
9,353
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery/eureka/StartEurekaTurbine.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.turbine.Turbine; public class StartEurekaTurbine { private static final Logger logger = LoggerFactory.getLogger(StartEurekaTurbine.class); public static void main(String[] args) { OptionParser optionParser = new OptionParser(); optionParser.accepts("port").withRequiredArg(); optionParser.accepts("app").withRequiredArg(); optionParser.accepts("urlTemplate").withRequiredArg(); OptionSet options = optionParser.parse(args); int port = -1; if (!options.has("port")) { System.err.println("Argument -port required for SSE HTTP server to start on. Eg. -port 8888"); System.exit(-1); } else { try { port = Integer.parseInt(String.valueOf(options.valueOf("port"))); } catch (NumberFormatException e) { System.err.println("Value of port must be an integer but was: " + options.valueOf("port")); } } String app = null; if (!options.has("app")) { System.err.println("Argument -app required for Eureka instance discovery. Eg. -app api"); System.exit(-1); } else { app = String.valueOf(options.valueOf("app")); } String template = null; if (!options.has("urlTemplate")) { System.err.println("Argument -urlTemplate required. Eg. http://" + EurekaStreamDiscovery.HOSTNAME + "/metrics.stream"); System.exit(-1); } else { template = String.valueOf(options.valueOf("urlTemplate")); if (!template.contains(EurekaStreamDiscovery.HOSTNAME)) { System.err.println("Argument -urlTemplate must contain " + EurekaStreamDiscovery.HOSTNAME + " marker. Eg. http://" + EurekaStreamDiscovery.HOSTNAME + "/metrics.stream"); System.exit(-1); } } logger.info("Turbine => Eureka App: " + app); logger.info("Turbine => Eureka URL Template: " + template); try { Turbine.startServerSentEventServer(port, EurekaStreamDiscovery.create(app, template)); } catch (Throwable e) { e.printStackTrace(); } } }
9,354
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery/eureka/EurekaInstanceDiscovery.java
/* * Copyright 2013 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.shared.Application; import com.netflix.turbine.discovery.eureka.EurekaInstance.Status; /** * Class that encapsulates an {@link InstanceDicovery} implementation that uses Eureka (see https://github.com/Netflix/eureka) * The plugin requires a list of applications configured. It then queries the set of instances for each application. * Instance information retrieved from Eureka must be translated to something that Turbine can understand i.e the {@link Instance} class. * * All the logic to perform this translation can be overriden here, so that you can provide your own implementation if needed. */ public class EurekaInstanceDiscovery { private static final Logger logger = LoggerFactory.getLogger(EurekaInstanceDiscovery.class); public static void main(String[] args) { new EurekaInstanceDiscovery().getInstanceEvents("api").toBlocking().forEach(i -> System.out.println(i)); } public EurekaInstanceDiscovery() { // initialize eureka client. make sure eureka properties are properly configured in config.properties DiscoveryManager.getInstance().initComponent(new MyDataCenterInstanceConfig(), new DefaultEurekaClientConfig()); } public Observable<EurekaInstance> getInstanceEvents(String appName) { return Observable. create((Subscriber<? super EurekaInstance> subscriber) -> { try { logger.info("Fetching instance list for app: " + appName); Application app = DiscoveryManager.getInstance().getDiscoveryClient().getApplication(appName); if (app == null) { subscriber.onError(new RuntimeException("App not found: " + appName)); return; } List<InstanceInfo> instancesForApp = app.getInstances(); if (instancesForApp != null) { logger.info("Received instance list for app: " + appName + " = " + instancesForApp.size()); for (InstanceInfo instance : instancesForApp) { if (InstanceInfo.InstanceStatus.UP == instance.getStatus()) { // we only emit UP instances, the delta process marks DOWN subscriber.onNext(EurekaInstance.create(instance)); } } subscriber.onCompleted(); } else { subscriber.onError(new RuntimeException("Failed to retrieve instances for appName: " + appName)); } } catch (Throwable e) { subscriber.onError(e); } }) .subscribeOn(Schedulers.io()) .toList() .repeatWhen(a -> a.flatMap(n -> Observable.timer(30, TimeUnit.SECONDS))) // repeat after 30 second delay .startWith(new ArrayList<EurekaInstance>()) .buffer(2, 1) .filter(l -> l.size() == 2) .flatMap(EurekaInstanceDiscovery::delta); } static Observable<EurekaInstance> delta(List<List<EurekaInstance>> listOfLists) { if (listOfLists.size() == 1) { return Observable.from(listOfLists.get(0)); } else { // diff the two List<EurekaInstance> newList = listOfLists.get(1); List<EurekaInstance> oldList = new ArrayList<>(listOfLists.get(0)); Set<EurekaInstance> delta = new LinkedHashSet<>(); delta.addAll(newList); // remove all that match in old delta.removeAll(oldList); // filter oldList to those that aren't in the newList oldList.removeAll(newList); // for all left in the oldList we'll create DROP events for (EurekaInstance old : oldList) { delta.add(EurekaInstance.create(Status.DOWN, old.getInstanceInfo())); } return Observable.from(delta); } } }
9,355
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery/eureka/EurekaInstance.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; public class EurekaInstance { public static enum Status { UP, DOWN } private final Status status; private final InstanceInfo instance; private EurekaInstance(Status status, InstanceInfo instance) { this.status = status; this.instance = instance; } public static EurekaInstance create(InstanceInfo instance) { Status status; if (InstanceStatus.UP == instance.getStatus()) { status = Status.UP; } else { status = Status.DOWN; } return new EurekaInstance(status, instance); } public static EurekaInstance create(Status status, InstanceInfo instance) { return new EurekaInstance(status, instance); } public Status getStatus() { return status; } public InstanceInfo getInstanceInfo() { return instance; } public String getAppName() { return instance.getAppName(); } public String getHostName() { return instance.getHostName(); } public String getIPAddr() { return instance.getIPAddr(); } public String getVIPAddress() { return instance.getVIPAddress(); } public String getASGName() { return instance.getASGName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getAppName() == null) ? 0 : getAppName().hashCode()); result = prime * result + ((getASGName() == null) ? 0 : getASGName().hashCode()); result = prime * result + ((getHostName() == null) ? 0 : getHostName().hashCode()); result = prime * result + ((getIPAddr() == null) ? 0 : getIPAddr().hashCode()); result = prime * result + ((getVIPAddress() == null) ? 0 : getVIPAddress().hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EurekaInstance other = (EurekaInstance) obj; if (getAppName() == null) { if (other.getAppName() != null) return false; } else if (!getAppName().equals(other.getAppName())) return false; if (getASGName() == null) { if (other.getASGName() != null) return false; } else if (!getASGName().equals(other.getASGName())) return false; if (getHostName() == null) { if (other.getHostName() != null) return false; } else if (!getHostName().equals(other.getHostName())) return false; if (getIPAddr() == null) { if (other.getIPAddr() != null) return false; } else if (!getIPAddr().equals(other.getIPAddr())) return false; if (getVIPAddress() == null) { if (other.getVIPAddress() != null) return false; } else if (!getVIPAddress().equals(other.getVIPAddress())) return false; if (status != other.status) return false; return true; } @Override public String toString() { return "EurekaInstance [status=" + status + ", vip=" + instance.getVIPAddress() + ", hostname=" + instance.getHostName() + ", asg=" + instance.getASGName() + "]"; } }
9,356
0
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery
Create_ds/Turbine/turbine-ext/turbine-discovery-eureka1/src/main/java/com/netflix/turbine/discovery/eureka/EurekaStreamDiscovery.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery.eureka; import java.net.URI; import com.netflix.turbine.discovery.StreamAction; import com.netflix.turbine.discovery.StreamDiscovery; import rx.Observable; public class EurekaStreamDiscovery implements StreamDiscovery { public static EurekaStreamDiscovery create(String appName, String uriTemplate) { return new EurekaStreamDiscovery(appName, uriTemplate); } public final static String HOSTNAME = "{HOSTNAME}"; private final String uriTemplate; private final String appName; private EurekaStreamDiscovery(String appName, String uriTemplate) { this.appName = appName; this.uriTemplate = uriTemplate; } @Override public Observable<StreamAction> getInstanceList() { return new EurekaInstanceDiscovery() .getInstanceEvents(appName) .map(ei -> { URI uri; try { uri = new URI(uriTemplate.replace(HOSTNAME, ei.getHostName())); } catch (Exception e) { throw new RuntimeException("Invalid URI", e); } if (ei.getStatus() == EurekaInstance.Status.UP) { return StreamAction.create(StreamAction.ActionType.ADD, uri); } else { return StreamAction.create(StreamAction.ActionType.REMOVE, uri); } }); } }
9,357
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/HystrixStreamSource.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import com.netflix.turbine.aggregator.InstanceKey; import com.netflix.turbine.internal.JsonUtility; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.observables.GroupedObservable; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; public class HystrixStreamSource { public static final String STREAM_ALL = "hystrix"; public static final String STREAM_SUBSCRIBER = "hystrix-subscriber"; public static final String STREAM_CINEMATCH = "hystrix-cinematch"; public static final String STREAM_SUBSCRIBER_CINEMATCH_1 = "hystrix-subscriber_cinematch_1"; public static final String STREAM_SUBSCRIBER_CINEMATCH_2 = "hystrix-subscriber_cinematch_2"; public static void main(String[] args) { getHystrixStreamFromFile(STREAM_ALL, 12345, 1).take(5).toBlocking().forEach(new Action1<Map<String, Object>>() { @Override public void call(Map<String, Object> s) { System.out.println("s: " + s.keySet()); } }); } // a hack to simulate a stream public static GroupedObservable<InstanceKey, Map<String, Object>> getHystrixStreamFromFile(final String stream, final int instanceID, int latencyBetweenEvents) { return GroupedObservable.from(InstanceKey.create(instanceID), Observable.create(new OnSubscribe<Map<String, Object>>() { @Override public void call(Subscriber<? super Map<String, Object>> sub) { try { while (!sub.isUnsubscribed()) { String packagePath = HystrixStreamSource.class.getPackage().getName().replace('.', '/'); InputStream file = HystrixStreamSource.class.getResourceAsStream("/" + packagePath + "/" + stream + ".stream"); BufferedReader in = new BufferedReader(new InputStreamReader(file)); String line = null; while ((line = in.readLine()) != null && !sub.isUnsubscribed()) { if (!line.trim().equals("")) { if (line.startsWith("data: ")) { String json = line.substring(6); try { Map<String, Object> jsonMap = JsonUtility.jsonToMap(json); jsonMap.put("instanceId", String.valueOf(instanceID)); sub.onNext(jsonMap); Thread.sleep(latencyBetweenEvents); } catch (Exception e) { e.printStackTrace(); } } } } } } catch (Exception e) { sub.onError(e); } } }).subscribeOn(Schedulers.newThread())); } public static GroupedObservable<InstanceKey, Map<String, Object>> getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(final String stream, final int instanceID, final TestScheduler scheduler, int maxTime) { TestSubject<Map<String, Object>> scheduledOrigin = TestSubject.create(scheduler); try { String packagePath = HystrixStreamSource.class.getPackage().getName().replace('.', '/'); InputStream file = HystrixStreamSource.class.getResourceAsStream("/" + packagePath + "/" + stream + ".stream"); BufferedReader in = new BufferedReader(new InputStreamReader(file)); String line = null; int time = 0; while ((line = in.readLine()) != null && time < maxTime) { if (!line.trim().equals("")) { if (line.startsWith("data: ")) { time = time + 10; // increment by 10 milliseconds String json = line.substring(6); try { Map<String, Object> jsonMap = JsonUtility.jsonToMap(json); // System.err.println(instanceID + " => scheduling at time: " + time + " => " + jsonMap); scheduledOrigin.onNext(jsonMap, time); } catch (Exception e) { System.err.println("bad data"); } } } } scheduledOrigin.onCompleted(maxTime); } catch (Exception e) { throw new RuntimeException(e); } return GroupedObservable.from(InstanceKey.create(instanceID), scheduledOrigin.subscribeOn(scheduler)); } }
9,358
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/HttpServerDemo.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine; import com.netflix.turbine.internal.JsonUtility; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; public class HttpServerDemo { public static void main(String args[]) { RxNetty.createHttpServer(8080, (request, response) -> { return Demo.getStream().flatMap(data -> { response.getHeaders().set("Content-Type", "text/event-stream"); return response.writeAndFlush(new ServerSentEvent("1", "data", JsonUtility.mapToJson(data))); }); }, PipelineConfigurators.sseServerConfigurator()).startAndWait(); } }
9,359
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/Demo.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine; import java.util.Map; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.observables.GroupedObservable; import com.netflix.turbine.aggregator.InstanceKey; import com.netflix.turbine.aggregator.StreamAggregator; import com.netflix.turbine.internal.JsonUtility; public class Demo { public static void main(String[] args) { getStream().toBlocking().forEach(map -> { System.out.println("data => " + JsonUtility.mapToJson(map)); }); } public static Observable<Map<String, Object>> getStream() { GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamA = HystrixStreamSource.getHystrixStreamFromFile(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 12345, 500); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamB = HystrixStreamSource.getHystrixStreamFromFile(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 23456, 500); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamC = HystrixStreamSource.getHystrixStreamFromFile(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 34567, 500); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamD = HystrixStreamSource.getHystrixStreamFromFile(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 45678, 500); Observable<GroupedObservable<InstanceKey, Map<String, Object>>> fullStream = Observable.just(hystrixStreamA, hystrixStreamB, hystrixStreamC, hystrixStreamD); return StreamAggregator.aggregateGroupedStreams(fullStream).flatMap(commandGroup -> { return commandGroup .throttleFirst(1000, TimeUnit.MILLISECONDS); }); } }
9,360
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/aggregator/AggregateStringTest.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class AggregateStringTest { @Test public void testSingleValue() { AggregateString v = AggregateString.create("false", InstanceKey.create(1)); assertEquals("{\"false\":1}", v.toJson()); v = v.update("false", "false", InstanceKey.create(1)); assertEquals("{\"false\":1}", v.toJson()); v = v.update("false", "true", InstanceKey.create(1)); assertEquals("{\"true\":1}", v.toJson()); } @Test public void testMultipleValuesOnSingleInstance() { AggregateString v = AggregateString.create(); InstanceKey instance = InstanceKey.create(1); v = v.update(null, "false", instance); assertEquals("{\"false\":1}", v.toJson()); v = v.update("false", "false", instance); assertEquals("{\"false\":1}", v.toJson()); v = v.update("false", "true", instance); assertEquals("{\"true\":1}", v.toJson()); } @Test public void testMultipleValuesOnMultipleInstances() { AggregateString v = AggregateString.create(); v = v.update(null, "false", InstanceKey.create(1)); v = v.update(null, "true", InstanceKey.create(2)); assertEquals("{\"false\":1,\"true\":1}", v.toJson()); v = v.update("false", "false", InstanceKey.create(1)); // old value set so we'll decrement ... but same so no different assertEquals("{\"false\":1,\"true\":1}", v.toJson()); assertEquals(2, v.instances().size()); v = v.update(null, "false", InstanceKey.create(3)); assertEquals("{\"false\":2,\"true\":1}", v.toJson()); assertEquals(3, v.instances().size()); v = v.update("false", "true", InstanceKey.create(1)); assertEquals("{\"false\":1,\"true\":2}", v.toJson()); v = v.update("false", "true", InstanceKey.create(3)); assertEquals("{\"true\":3}", v.toJson()); // remove an instance v = v.update("true", null, InstanceKey.create(1)); assertEquals("{\"true\":2}", v.toJson()); assertEquals(2, v.instances().size()); } }
9,361
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/aggregator/NumberListTest.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import static org.junit.Assert.assertEquals; import java.util.LinkedHashMap; import org.junit.Test; import com.netflix.turbine.aggregator.NumberList; public class NumberListTest { private static final LinkedHashMap<String, Object> values = new LinkedHashMap<String, Object>(); private static final LinkedHashMap<String, Object> values2 = new LinkedHashMap<String, Object>(); static { values.put("0", 10); values.put("25", 50); values.put("50", 100); values.put("75", 250); values.put("99", 500); values2.put("0", 15); values2.put("25", 55); values2.put("50", 105); values2.put("75", 255); values2.put("99", 505); } @Test public void testCreate() { NumberList nl = NumberList.create(values); System.out.println(nl); assertEquals(Long.valueOf(10), nl.get("0")); assertEquals(Long.valueOf(50), nl.get("25")); assertEquals(Long.valueOf(100), nl.get("50")); assertEquals(Long.valueOf(250), nl.get("75")); assertEquals(Long.valueOf(500), nl.get("99")); } @Test public void testDelta() { NumberList nl = NumberList.delta(values2, values); System.out.println(nl); assertEquals(Long.valueOf(5), nl.get("0")); assertEquals(Long.valueOf(5), nl.get("25")); assertEquals(Long.valueOf(5), nl.get("50")); assertEquals(Long.valueOf(5), nl.get("75")); assertEquals(Long.valueOf(5), nl.get("99")); } @Test public void testDeltaWithNumberList() { NumberList nl = NumberList.delta(NumberList.create(values2), NumberList.create(values)); System.out.println(nl); assertEquals(Long.valueOf(5), nl.get("0")); assertEquals(Long.valueOf(5), nl.get("25")); assertEquals(Long.valueOf(5), nl.get("50")); assertEquals(Long.valueOf(5), nl.get("75")); assertEquals(Long.valueOf(5), nl.get("99")); } @Test public void testSum() { NumberList nl = NumberList.create(values).sum(NumberList.create(values2)); System.out.println(nl); assertEquals(Long.valueOf(25), nl.get("0")); assertEquals(Long.valueOf(105), nl.get("25")); assertEquals(Long.valueOf(205), nl.get("50")); assertEquals(Long.valueOf(505), nl.get("75")); assertEquals(Long.valueOf(1005), nl.get("99")); } }
9,362
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/aggregator/StreamAggregatorTest.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.junit.Test; import rx.Observable; import rx.observables.GroupedObservable; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import com.netflix.turbine.HystrixStreamSource; public class StreamAggregatorTest { /** * Submit 3 events containing `rollingCountSuccess` of => 327, 370, 358 * * We should receive a GroupedObservable of key "CinematchGetPredictions" with deltas => 327, 43, -12, -358 (onComplete) */ @Test public void testNumberValue_OneInstanceOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return data.get("rollingCountSuccess"); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 5); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); ts.assertNoErrors(); assertEquals(0, ts.getOnErrorEvents().size()); // we expect a single instance assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess ts.assertReceivedOnNext(Arrays.asList(327L, 370L, 358L, 0L)); } /** * Group 1: 327, 370, 358 => deltas: 327, 43, -12, -358 (onComplete) * Group 2: 617, 614, 585 => deltas: 617, -3, -29, -585 (onComplete) * * */ @Test public void testNumberValue_OneInstanceTwoGroups() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return data.get("rollingCountSuccess"); }); }).subscribe(ts); stream.onNext(getSubscriberAndCinematchCommandInstanceStream(12345, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 2 commands assertEquals(2, numGroups.get()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) ts.assertReceivedOnNext(Arrays.asList(327L, 617L, 370L, 614L, 358L, 585L, 0L, 0L)); // two 0s because both groups complete and remove themselves } /** * Two instances emitting: 327, 370, 358 => deltas: 327, 43, -12, -358 (onComplete) * * 327, 327, 370, 370, 358, 358 * * 0 + 327 = 327 * 327 + 327 = 654 * 654 + 43 = 697 * 697 + 43 = 740 * 740 - 12 = 728 * 728 - 358 = 370 * 370 - 12 = 358 * 358 - 358 = 0 * */ @Test public void testNumberValue_TwoInstancesOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return data.get("rollingCountSuccess"); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) ts.assertReceivedOnNext(Arrays.asList(327L, 654L, 697L, 740L, 728L, 370L, 358L, 0L)); } /** * * Each instance emits => * * Group 1: 327, 370, 358 => deltas: 327, 43, -12, -358 (onComplete) * Group 2: 617, 614, 585 => deltas: 617, -3, -29, -585 (onComplete) * * Group1 => * * 327, 327, 370, 370, 358, 358 * * 0 + 327 = 327 * 327 + 327 = 654 * 654 + 43 = 697 * 697 + 43 = 740 * 740 - 12 = 728 * 728 - 358 = 370 * 370 - 12 = 358 * 358 - 358 = 0 * * Group 2 => * * 617, 617, 614, 614, 585, 585 * * 0 + 617 = 617 * 617 + 617 = 1234 * 1234 - 3 = 1231 * 1231 - 3 = 1228 * 1228 - 29 = 1199 * 1199 - 585 = 614 * 614 - 29 = 585 * 585 - 585 = 0 * * Interleaved because 2 groups: * * 327, 654, 617, 1234, 697, 740, 1231, 1228, 728, 716, 1199, 1170 * */ @Test public void testNumberValue_TwoInstancesTwoGroups() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return data.get("rollingCountSuccess"); }); }).subscribe(ts); stream.onNext(getSubscriberAndCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getSubscriberAndCinematchCommandInstanceStream(23456, scheduler), 5); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 2 commands assertEquals(2, numGroups.get()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) ts.assertReceivedOnNext(Arrays.asList(327L, 654L, 617L, 1234L, 697L, 740L, 1231L, 1228L, 728L, 716L, 1199L, 614L, 358L, 585L, 0L, 0L)); } @Test public void testStringValue_OneInstanceOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return ((AggregateString) data.get("isCircuitBreakerOpen")).toJson(); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 5); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect a single instance assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess ts.assertReceivedOnNext(Arrays.asList("{\"false\":1}", "{\"false\":1}", "{\"true\":1}", "{}")); } @Test public void testStringValue_TwoInstancesOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return ((AggregateString) data.get("isCircuitBreakerOpen")).toJson(); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) ts.assertReceivedOnNext(Arrays.asList("{\"false\":1}", "{\"false\":2}", "{\"false\":2}", "{\"false\":2}", "{\"false\":1,\"true\":1}", "{\"false\":1}", "{\"true\":1}", "{}")); } /* * Test that an instance dropping correctly removes the data */ @Test public void testInstanceRemovalStringValue() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<AggregateString> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).<AggregateString> flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return ((AggregateString) data.get("isCircuitBreakerOpen")); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler, 31), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler, 100), 0); stream.onCompleted(100); scheduler.advanceTimeTo(30, TimeUnit.MILLISECONDS); // assert we have two groups aggregated List<AggregateString> onNextAt30 = ts.getOnNextEvents(); List<String> jsonAt30 = ts.getOnNextEvents().stream().map(as -> as.toJson()).collect(Collectors.toList()); System.out.println("OnNext at 30ms -> " + jsonAt30); // we should have 2 instance now System.out.println("Instances at 30: " + onNextAt30.get(onNextAt30.size() - 1).instances()); assertEquals(2, onNextAt30.get(onNextAt30.size() - 1).instances().size()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) assertEquals(jsonAt30, Arrays.asList("{\"false\":1}", "{\"false\":2}", "{\"false\":2}", "{\"false\":2}", "{\"false\":1,\"true\":1}", "{\"true\":2}")); // advance past the first stream so it onCompletes and removes itself scheduler.advanceTimeTo(31, TimeUnit.MILLISECONDS); // we should now see only 1 value List<AggregateString> onNextAt31 = ts.getOnNextEvents(); List<String> jsonAt31 = ts.getOnNextEvents().stream().map(as -> as.toJson()).collect(Collectors.toList()); System.out.println("OnNext at 31ms -> " + jsonAt31); // we should only have 1 instance now System.out.println("Instances at 31: " + onNextAt31.get(onNextAt31.size() - 1).instances()); assertEquals(1, onNextAt31.get(onNextAt31.size() - 1).instances().size()); assertEquals(jsonAt31, Arrays.asList("{\"false\":1}", "{\"false\":2}", "{\"false\":2}", "{\"false\":2}", "{\"false\":1,\"true\":1}", "{\"true\":2}", "{\"true\":1}")); // complete scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); } @Test public void testFields() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { numGroups.incrementAndGet(); return commandGroup.map(data -> { validateNumber(data, "reportingHosts"); validateString(data, "type"); validateString(data, "name"); validateAggregateString(data, "group"); validateNull(data, "currentTime"); validateAggregateString(data, "isCircuitBreakerOpen"); validateNumber(data, "errorPercentage"); validateNumber(data, "errorCount"); validateNumber(data, "requestCount"); validateNumber(data, "rollingCountCollapsedRequests"); validateNumber(data, "rollingCountExceptionsThrown"); validateNumber(data, "rollingCountFailure"); validateNumber(data, "rollingCountFallbackFailure"); validateNumber(data, "rollingCountFallbackRejection"); validateNumber(data, "rollingCountFallbackSuccess"); validateNumber(data, "rollingCountResponsesFromCache"); validateNumber(data, "rollingCountSemaphoreRejected"); validateNumber(data, "rollingCountShortCircuited"); validateNumber(data, "rollingCountSuccess"); validateNumber(data, "rollingCountThreadPoolRejected"); validateNumber(data, "rollingCountTimeout"); validateNumber(data, "currentConcurrentExecutionCount"); validateNumber(data, "latencyExecute_mean"); validateNumberList(data, "latencyExecute"); validateNumber(data, "latencyTotal_mean"); validateNumberList(data, "latencyTotal"); validateAggregateString(data, "propertyValue_circuitBreakerRequestVolumeThreshold"); validateAggregateString(data, "propertyValue_circuitBreakerSleepWindowInMilliseconds"); validateAggregateString(data, "propertyValue_circuitBreakerErrorThresholdPercentage"); validateAggregateString(data, "propertyValue_circuitBreakerForceOpen"); validateAggregateString(data, "propertyValue_executionIsolationStrategy"); validateAggregateString(data, "propertyValue_executionIsolationThreadTimeoutInMilliseconds"); validateAggregateString(data, "propertyValue_executionIsolationThreadInterruptOnTimeout"); validateAggregateString(data, "propertyValue_executionIsolationSemaphoreMaxConcurrentRequests"); validateAggregateString(data, "propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests"); validateAggregateString(data, "propertyValue_requestCacheEnabled"); validateAggregateString(data, "propertyValue_requestLogEnabled"); validateAggregateString(data, "propertyValue_metricsRollingStatisticalWindowInMilliseconds"); return data.get("name"); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess (2 instances of same data grouped together) ts.assertReceivedOnNext(Arrays.asList("CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions", "CinematchGetPredictions")); } @Test public void testFieldReportingHosts() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { numGroups.incrementAndGet(); return commandGroup.map(data -> { return data.get("reportingHosts"); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); ts.assertReceivedOnNext(Arrays.asList(1L, 2L, 2L, 2L, 2L, 1L, 1L, 0L)); } @Test public void testField_propertyValue_circuitBreakerForceOpen() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { numGroups.incrementAndGet(); return commandGroup.map(data -> { return String.valueOf(data.get("propertyValue_circuitBreakerForceOpen")); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 0); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect 1 command assertEquals(1, numGroups.get()); ts.assertReceivedOnNext(Arrays.asList("AggregateString => {\"false\":1}", "AggregateString => {\"false\":2}", "AggregateString => {\"false\":2}", "AggregateString => {\"false\":2}", "AggregateString => {\"false\":2}", "AggregateString => {\"false\":1}", "AggregateString => {\"false\":1}", "AggregateString => {}")); } @Test public void testFieldOnStream() { TestScheduler scheduler = new TestScheduler(); TestSubscriber<Object> ts = new TestSubscriber<>(); // 20 events per instance, 10 per group // 80 events total GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamA = HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 12345, scheduler, 200); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamB = HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 23456, scheduler, 200); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamC = HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 67890, scheduler, 200); GroupedObservable<InstanceKey, Map<String, Object>> hystrixStreamD = HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, 63543, scheduler, 200); Observable<GroupedObservable<InstanceKey, Map<String, Object>>> fullStream = Observable.just(hystrixStreamA, hystrixStreamB, hystrixStreamC, hystrixStreamD); StreamAggregator.aggregateGroupedStreams(fullStream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); return commandGroup; }).doOnNext(data -> { System.out.println("data => " + data.get("propertyValue_circuitBreakerForceOpen") + " " + data.get("name")); }).skip(8).doOnNext(v -> { // assert the count is always 4 (4 instances) on AggregateString values AggregateString as = (AggregateString) (v.get("propertyValue_circuitBreakerForceOpen")); if (!"AggregateString => {\"false\":4}".equals(as.toString())) { // after the initial 1, 2, 3, 4 counting on each instance we should receive 4 always thereafter // and we skip the first 8 to get past those throw new IllegalStateException("Expect the count to always be 4 but was " + as.toString()); } }).subscribe(ts); // only got to 199 so we don't trigger completion scheduler.advanceTimeBy(199, TimeUnit.MILLISECONDS); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); } private void validateNumberList(Map<String, Object> data, String key) { Object o = data.get(key); if (o == null) { throw new IllegalStateException("Expected value: " + key); } if (!(o instanceof NumberList)) { throw new IllegalStateException("Expected value of '" + key + "' to be a NumberList but was: " + o.getClass().getSimpleName()); } } private void validateNull(Map<String, Object> data, String key) { Object o = data.get(key); if (o != null) { throw new IllegalStateException("Did not expect value for key: " + key); } } private void validateAggregateString(Map<String, Object> data, String key) { Object o = data.get(key); if (o == null) { throw new IllegalStateException("Expected value: " + key); } if (!(o instanceof AggregateString)) { throw new IllegalStateException("Expected value of '" + key + "' to be a AggregateString but was: " + o.getClass().getSimpleName()); } } private void validateString(Map<String, Object> data, String key) { Object o = data.get(key); if (o == null) { throw new IllegalStateException("Expected value: " + key); } if (!(o instanceof String)) { throw new IllegalStateException("Expected value of '" + key + "' to be a String but was: " + o.getClass().getSimpleName()); } } private void validateNumber(Map<String, Object> data, String key) { Object o = data.get(key); if (o == null) { throw new IllegalStateException("Expected value: " + key); } if (!(o instanceof Number)) { throw new IllegalStateException("Expected value of '" + key + "' to be a Number but was: " + o.getClass().getSimpleName()); } } /** * This looks for the latency values which look like this: * * {"0":0,"25":0,"50":4,"75":11,"90":14,"95":17,"99":31,"99.5":43,"100":71} * {"0":0,"25":0,"50":3,"75":12,"90":17,"95":24,"99":48,"99.5":363,"100":390} * {"0":0,"25":0,"50":3,"75":12,"90":17,"95":24,"99":48,"99.5":363,"100":390} * * The inner values need to be summed. */ @Test public void testArrayMapValue_OneInstanceOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return ((NumberList) data.get("latencyTotal")).toJson(); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 5); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect a single instance assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess ts.assertReceivedOnNext(Arrays.asList("{\"0\":0,\"25\":0,\"50\":4,\"75\":11,\"90\":14,\"95\":17,\"99\":31,\"99.5\":43,\"100\":71}", "{\"0\":0,\"25\":0,\"50\":3,\"75\":12,\"90\":17,\"95\":24,\"99\":48,\"99.5\":363,\"100\":390}", "{\"0\":0,\"25\":0,\"50\":3,\"75\":12,\"90\":17,\"95\":24,\"99\":48,\"99.5\":363,\"100\":390}", "{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0}")); } /** * This looks for the latency values which look like this: * * {"0":0,"25":0,"50":4,"75":11,"90":14,"95":17,"99":31,"99.5":43,"100":71} * {"0":0,"25":0,"50":3,"75":12,"90":17,"95":24,"99":48,"99.5":363,"100":390} * {"0":0,"25":0,"50":3,"75":12,"90":17,"95":24,"99":48,"99.5":363,"100":390} * * The inner values need to be summed. */ @Test public void testArrayMapValue_TwoInstanceOneGroup() { TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateGroupedStreams(stream).flatMap(commandGroup -> { System.out.println("======> Got group for command: " + commandGroup.getKey()); numGroups.incrementAndGet(); return commandGroup.map(data -> { return ((NumberList) data.get("latencyTotal")).toJson(); }); }).subscribe(ts); stream.onNext(getCinematchCommandInstanceStream(12345, scheduler), 0); stream.onNext(getCinematchCommandInstanceStream(23456, scheduler), 5); stream.onCompleted(100); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); ts.awaitTerminalEvent(); System.out.println("---------> OnErrorEvents: " + ts.getOnErrorEvents()); if (ts.getOnErrorEvents().size() > 0) { ts.getOnErrorEvents().get(0).printStackTrace(); } System.out.println("---------> OnNextEvents: " + ts.getOnNextEvents()); assertEquals(0, ts.getOnErrorEvents().size()); // we expect a single instance assertEquals(1, numGroups.get()); // the expected deltas for rollingCountSuccess ts.assertReceivedOnNext(Arrays.asList( "{\"0\":0,\"25\":0,\"50\":4,\"75\":11,\"90\":14,\"95\":17,\"99\":31,\"99.5\":43,\"100\":71}", "{\"0\":0,\"25\":0,\"50\":8,\"75\":22,\"90\":28,\"95\":34,\"99\":62,\"99.5\":86,\"100\":142}", // 71 + 71 combination "{\"0\":0,\"25\":0,\"50\":7,\"75\":23,\"90\":31,\"95\":41,\"99\":79,\"99.5\":406,\"100\":461}", // 71 + 390 combination "{\"0\":0,\"25\":0,\"50\":6,\"75\":24,\"90\":34,\"95\":48,\"99\":96,\"99.5\":726,\"100\":780}", // 390 + 390 combination "{\"0\":0,\"25\":0,\"50\":6,\"75\":24,\"90\":34,\"95\":48,\"99\":96,\"99.5\":726,\"100\":780}", // 390 + 390 combination "{\"0\":0,\"25\":0,\"50\":3,\"75\":12,\"90\":17,\"95\":24,\"99\":48,\"99.5\":363,\"100\":390}", // 780 - 390 "{\"0\":0,\"25\":0,\"50\":3,\"75\":12,\"90\":17,\"95\":24,\"99\":48,\"99.5\":363,\"100\":390}", // 780 - 390 "{\"0\":0,\"25\":0,\"50\":0,\"75\":0,\"90\":0,\"95\":0,\"99\":0,\"99.5\":0,\"100\":0}")); } private GroupedObservable<InstanceKey, Map<String, Object>> getCinematchCommandInstanceStream(int instanceId, TestScheduler scheduler) { return getCinematchCommandInstanceStream(instanceId, scheduler, 30); // 30ms max time before onComplete } // `rollingCountSuccess` of => 327, 370, 358 private GroupedObservable<InstanceKey, Map<String, Object>> getCinematchCommandInstanceStream(int instanceId, TestScheduler scheduler, int time) { return HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_CINEMATCH, instanceId, scheduler, time); } // `rollingCountSuccess` of => 617, 614, 585 private GroupedObservable<InstanceKey, Map<String, Object>> getSubscriberCommandInstanceStream(int instanceId, TestScheduler scheduler) { return HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER, instanceId, scheduler, 30); } // `rollingCountSuccess` of => 327, 617, 370, 614, 358, 585 private GroupedObservable<InstanceKey, Map<String, Object>> getSubscriberAndCinematchCommandInstanceStream(int instanceId, TestScheduler scheduler) { return HystrixStreamSource.getHystrixStreamFromFileEachLineScheduledEvery10Milliseconds(HystrixStreamSource.STREAM_SUBSCRIBER_CINEMATCH_1, instanceId, scheduler, 60); } private Map<String, Object> newMapInitializedWithInstanceKey() { Map<String, Object> m = new LinkedHashMap<>(); m.put("InstanceKey", InstanceKey.create(98765)); return m; } @Test public void testDeltaNumberNew() { Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); mCurrent.put("a", 1); mCurrent.put("b", 2); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mCurrent); assertEquals(1l, d.get("a")); assertEquals(2l, d.get("b")); Map<String, Object> s = StreamAggregator.sumOfDelta(newMapInitializedWithInstanceKey(), d); assertEquals(1l, s.get("a")); assertEquals(2l, s.get("b")); } @Test public void testDeltaNumber1() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", 1); mPrevious.put("b", 2); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); mCurrent.put("a", 3); mCurrent.put("b", 1); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); assertEquals(2l, d.get("a")); assertEquals(-1l, d.get("b")); Map<String, Object> s = StreamAggregator.sumOfDelta(mPrevious, d); assertEquals(3l, s.get("a")); assertEquals(1l, s.get("b")); } @Test public void testDeltaNumber2() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", 4); mPrevious.put("b", 3); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); mCurrent.put("a", 2); mCurrent.put("b", 2); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); assertEquals(-2l, d.get("a")); assertEquals(-1l, d.get("b")); Map<String, Object> s = StreamAggregator.sumOfDelta(mPrevious, d); assertEquals(2l, s.get("a")); assertEquals(2l, s.get("b")); } @Test public void testDeltaNumberRemove() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", 4); mPrevious.put("b", 3); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, Collections.emptyMap()); assertEquals(-4l, d.get("a")); assertEquals(-3l, d.get("b")); Map<String, Object> s = StreamAggregator.sumOfDelta(mPrevious, d); assertEquals(0l, s.get("a")); assertEquals(0l, s.get("b")); } @Test public void testDeltaNumberRemoveWithEmptyMapHavingInstanceKey() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", 4); mPrevious.put("b", 3); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); assertEquals(-4l, d.get("a")); assertEquals(-3l, d.get("b")); Map<String, Object> s = StreamAggregator.sumOfDelta(mPrevious, d); assertEquals(0l, s.get("a")); assertEquals(0l, s.get("b")); } @Test public void testDeltaBooleanNew() { Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); mCurrent.put("a", Boolean.TRUE); mCurrent.put("b", Boolean.FALSE); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mCurrent); String[] as = (String[]) d.get("a"); String[] bs = (String[]) d.get("b"); assertArrayEquals(new String[] { "true" }, as); assertArrayEquals(new String[] { "false" }, bs); Map<String, Object> s = StreamAggregator.sumOfDelta(new LinkedHashMap<>(), d); assertEquals("AggregateString => {\"true\":1}", s.get("a").toString()); assertEquals("AggregateString => {\"false\":1}", s.get("b").toString()); } @Test public void testDeltaBoolean1() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", Boolean.TRUE); mPrevious.put("b", Boolean.FALSE); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); mCurrent.put("a", Boolean.TRUE); mCurrent.put("b", Boolean.TRUE); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); String[] as = (String[]) d.get("a"); String[] bs = (String[]) d.get("b"); assertArrayEquals(new String[] { "true", "true" }, as); assertArrayEquals(new String[] { "false", "true" }, bs); Map<String, Object> state = newMapInitializedWithInstanceKey(); state.put("a", AggregateString.create("true", InstanceKey.create(98765))); state.put("b", AggregateString.create("false", InstanceKey.create(98765))); Map<String, Object> s = StreamAggregator.sumOfDelta(state, d); assertEquals("AggregateString => {\"true\":1}", s.get("a").toString()); // same instanceId so count == 1 assertEquals("AggregateString => {\"true\":1}", s.get("b").toString()); } @Test public void testDeltaBooleanRemove() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); mPrevious.put("a", Boolean.TRUE); mPrevious.put("b", Boolean.FALSE); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); String[] as = (String[]) d.get("a"); String[] bs = (String[]) d.get("b"); assertArrayEquals(new String[] { "true", null }, as); assertArrayEquals(new String[] { "false", null }, bs); Map<String, Object> state = newMapInitializedWithInstanceKey(); state.put("a", AggregateString.create("true", InstanceKey.create(98765))); state.put("b", AggregateString.create("false", InstanceKey.create(98765))); Map<String, Object> s = StreamAggregator.sumOfDelta(state, d); assertEquals("AggregateString => {}", s.get("a").toString()); // same instanceId so count == 1 assertEquals("AggregateString => {}", s.get("b").toString()); } @Test public void testDeltaNumberListNew() { Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); Map<String, Object> v = new HashMap<>(); v.put("100", 99); mCurrent.put("a", v); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mCurrent); assertEquals(99l, ((NumberList)d.get("a")).get("100").longValue()); Map<String, Object> s = StreamAggregator.sumOfDelta(newMapInitializedWithInstanceKey(), d); assertEquals(99l, ((NumberList)s.get("a")).get("100").longValue()); } @Test public void testDeltaNumberList1() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); Map<String, Object> v = new HashMap<>(); v.put("100", 99); mPrevious.put("a", v); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); Map<String, Object> v2 = new HashMap<>(); v2.put("100", 97); mCurrent.put("a", v2); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); assertEquals(-2l, ((NumberList)d.get("a")).get("100").longValue()); Map<String, Object> initial = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mPrevious); Map<String, Object> s = StreamAggregator.sumOfDelta(initial, d); assertEquals(97l, ((NumberList)s.get("a")).get("100").longValue()); } @Test public void testDeltaNumberList2() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); Map<String, Number> v = new HashMap<>(); v.put("100", 90); mPrevious.put("a", v); Map<String, Object> mCurrent = newMapInitializedWithInstanceKey(); Map<String, Number> v2 = new HashMap<>(); v2.put("100", 99); mCurrent.put("a", v2); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, mCurrent); assertEquals(9l, ((NumberList)d.get("a")).get("100").longValue()); Map<String, Object> initial = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mPrevious); Map<String, Object> s = StreamAggregator.sumOfDelta(initial, d); assertEquals(99l, ((NumberList)s.get("a")).get("100").longValue()); } @Test public void testDeltaNumberListRemove() { Map<String, Object> mPrevious = newMapInitializedWithInstanceKey(); Map<String, Number> v = new HashMap<>(); v.put("100", 99); mPrevious.put("a", v); Map<String, Object> d = StreamAggregator.previousAndCurrentToDelta(mPrevious, Collections.emptyMap()); System.out.println("d: " + d); assertEquals(-99l, ((NumberList)d.get("a")).get("100").longValue()); Map<String, Object> initial = StreamAggregator.previousAndCurrentToDelta(Collections.emptyMap(), mPrevious); Map<String, Object> s = StreamAggregator.sumOfDelta(initial, d); assertEquals(0l, ((NumberList)s.get("a")).get("100").longValue()); } }
9,363
0
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/test/java/com/netflix/turbine/internal/RequestCreatorTest.java
package com.netflix.turbine.internal; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import org.junit.Test; import java.net.URI; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class RequestCreatorTest { private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; @Test public void doesntAddAuthorizationHeaderWhenNoUserInfoIsDefinedInUri() throws Exception { // Given URI uri = new URI("http://myapp.com"); // When HttpClientRequest<ByteBuf> request = RequestCreator.createRequest(uri); // Then assertFalse(request.getHeaders().contains(AUTHORIZATION_HEADER_NAME)); } @Test public void addsAuthorizationHeaderWhenUserInfoIsDefinedInUri() throws Exception { // Given URI uri = new URI("http://username:password@myapp.com"); // When HttpClientRequest<ByteBuf> request = RequestCreator.createRequest(uri); // Then assertEquals(basicAuthOf("username", "password"), request.getHeaders().getHeader(AUTHORIZATION_HEADER_NAME)); } @Test public void removesUserInfoFromUriWhenUserInfoIsDefinedInUri() throws Exception { // Given URI uri = new URI("http://username:password@myapp.com"); // When HttpClientRequest<ByteBuf> request = RequestCreator.createRequest(uri); // Then assertFalse(request.getUri().contains("username:password@")); } private String basicAuthOf(String username, String password) { return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8)); } }
9,364
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/Turbine.java
/** * Copyright 2014 Netflix, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine; import com.netflix.turbine.aggregator.InstanceKey; import com.netflix.turbine.aggregator.StreamAggregator; import com.netflix.turbine.aggregator.TypeAndNameKey; import com.netflix.turbine.discovery.StreamAction; import com.netflix.turbine.discovery.StreamAction.ActionType; import com.netflix.turbine.discovery.StreamDiscovery; import com.netflix.turbine.internal.JsonUtility; import io.netty.buffer.ByteBuf; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.observables.GroupedObservable; import java.net.URI; import java.util.Map; import java.util.concurrent.TimeUnit; import static com.netflix.turbine.internal.RequestCreator.createRequest; public class Turbine { private static final Logger logger = LoggerFactory.getLogger(Turbine.class); public static void startServerSentEventServer(int port, Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> streams) { logger.info("Turbine => Starting server on " + port); // multicast so multiple concurrent subscribers get the same stream Observable<Map<String, Object>> publishedStreams = streams .doOnUnsubscribe(() -> logger.info("Turbine => Unsubscribing aggregation.")) .doOnSubscribe(() -> logger.info("Turbine => Starting aggregation")) .flatMap(o -> o).publish().refCount(); RxNetty.createHttpServer(port, (request, response) -> { logger.info("Turbine => SSE Request Received"); response.getHeaders().setHeader("Content-Type", "text/event-stream"); return publishedStreams .doOnUnsubscribe(() -> logger.info("Turbine => Unsubscribing RxNetty server connection")) .flatMap(data -> { return response.writeAndFlush(new ServerSentEvent(null, null, JsonUtility.mapToJson(data))); }); }, PipelineConfigurators.<ByteBuf>sseServerConfigurator()).startAndWait(); } public static void startServerSentEventServer(int port, StreamDiscovery discovery) { startServerSentEventServer(port, aggregateHttpSSE(discovery)); } public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateHttpSSE(URI... uris) { return aggregateHttpSSE(() -> { return Observable.from(uris).map(uri -> StreamAction.create(ActionType.ADD, uri)).concatWith(Observable.never()); // never() as we don't want to end }); } /** * Aggregate multiple HTTP Server-Sent Event streams into one stream with the values summed. * <p> * The returned data must be JSON data that contains the following keys: * <p> * instanceId => Unique instance representing each stream to be merged, such as the instanceId of the server the stream is from. * type => The type of data such as HystrixCommand or HystrixThreadPool if aggregating Hystrix metrics. * name => Name of a group of metrics to be aggregated, such as a HystrixCommand name if aggregating Hystrix metrics. * * @param uri * @return */ public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateHttpSSE(StreamDiscovery discovery) { Observable<StreamAction> streamActions = discovery.getInstanceList().publish().refCount(); Observable<StreamAction> streamAdds = streamActions.filter(a -> a.getType() == ActionType.ADD); Observable<StreamAction> streamRemoves = streamActions.filter(a -> a.getType() == ActionType.REMOVE); Observable<GroupedObservable<InstanceKey, Map<String, Object>>> streamPerInstance = streamAdds.map(streamAction -> { URI uri = streamAction.getUri(); Observable<Map<String, Object>> io = Observable.defer(() -> { Observable<Map<String, Object>> flatMap = RxNetty.createHttpClient(uri.getHost(), uri.getPort(), PipelineConfigurators.<ByteBuf>sseClientConfigurator()) .submit(createRequest(uri)) .flatMap(response -> { if (response.getStatus().code() != 200) { return Observable.error(new RuntimeException("Failed to connect: " + response.getStatus())); } return response.getContent() .doOnSubscribe(() -> logger.info("Turbine => Aggregate Stream from URI: " + uri.toASCIIString())) .doOnUnsubscribe(() -> logger.info("Turbine => Unsubscribing Stream: " + uri)) .takeUntil(streamRemoves.filter(a -> a.getUri().equals(streamAction.getUri()))) // unsubscribe when we receive a remove event .map(sse -> JsonUtility.jsonToMap(sse.getEventData())); }); // eclipse is having issues with type inference so breaking up return flatMap.retryWhen(attempts -> { return attempts.flatMap(e -> { return Observable.timer(1, TimeUnit.SECONDS) .doOnEach(n -> logger.info("Turbine => Retrying connection to: " + uri)); }); }); }); return GroupedObservable.from(InstanceKey.create(uri.toASCIIString()), io); }); return StreamAggregator.aggregateGroupedStreams(streamPerInstance); } /** * Aggregate multiple HTTP URIs * * @param uri * @return */ // public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateHttp(java.net.URI... uri) { // // } }
9,365
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/StartTurbine.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine; import java.net.URI; import java.net.URISyntaxException; import joptsimple.OptionParser; import joptsimple.OptionSet; public class StartTurbine { public static void main(String[] args) { OptionParser optionParser = new OptionParser(); optionParser.accepts("port").withRequiredArg(); optionParser.accepts("streams").withRequiredArg(); OptionSet options = optionParser.parse(args); int port = -1; if (!options.has("port")) { System.err.println("Argument -port required for SSE HTTP server to start on."); System.exit(-1); } else { try { port = Integer.parseInt(String.valueOf(options.valueOf("port"))); } catch (NumberFormatException e) { System.err.println("Value of port must be an integer but was: " + options.valueOf("port")); } } URI[] streams = null; if (!options.hasArgument("streams")) { System.err.println("Argument -streams required with URIs to connect to. Eg. -streams \"http://host1/metrics.stream http://host2/metrics.stream\""); System.exit(-1); } else { String streamsArg = String.valueOf(options.valueOf("streams")); String[] ss = streamsArg.split(" "); streams = new URI[ss.length]; for (int i = 0; i < ss.length; i++) { try { streams[i] = new URI(ss[i]); } catch (URISyntaxException e) { System.err.println("ERROR: Could not parse stream into URI: " + ss[i]); System.exit(-1); } } } if (streams == null || streams.length == 0) { System.err.println("There must be at least 1 valid stream URI."); System.exit(-1); } try { Turbine.startServerSentEventServer(port, Turbine.aggregateHttpSSE(streams)); } catch (Throwable e) { e.printStackTrace(); } } }
9,366
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/TypeAndNameKey.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import java.util.concurrent.ConcurrentHashMap; public final class TypeAndNameKey implements GroupKey { private final String key; private final String type; private final String name; private static ConcurrentHashMap<String, TypeAndNameKey> internedKeys = new ConcurrentHashMap<>(); public static TypeAndNameKey from(String type, String name) { // I wish there was a way to do compound keys without creating new strings return internedKeys.computeIfAbsent(type + "_" + name, k -> new TypeAndNameKey(k, type, name)); } private TypeAndNameKey(String key, String type, String name) { this.key = key; this.type = type; this.name = name; } public String getKey() { return key; } public String getType() { return type; } public String getName() { return name; } @Override public String toString() { return "TypeAndName=>" + key; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeAndNameKey other = (TypeAndNameKey) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } }
9,367
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/GroupKey.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; public interface GroupKey { public String getKey(); }
9,368
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/AggregateString.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.netflix.turbine.internal.AggregateStringSerializer; import com.netflix.turbine.internal.JsonUtility; /** * Represents the different sets of string values that have been received for a given key * and the respective value counts. * * For example, if 2 "false" and 1 "true" were set on this the output would be: {"false":2,"true":1} * * This class is optimized for the fact that almost all the time the value is expected to be the same and only rarely have more than 1 value. */ @JsonSerialize(using = AggregateStringSerializer.class) public class AggregateString { private final Map<String, Integer> values; private final Set<InstanceKey> instances; private AggregateString(Map<String, Integer> values, Set<InstanceKey> instances) { this.values = values; this.instances = instances; } private static AggregateString EMPTY = new AggregateString(Collections.emptyMap(), Collections.emptySet()); public static AggregateString create() { return EMPTY; } public static AggregateString create(String value, InstanceKey instanceKey) { if (instanceKey == null) { throw new NullPointerException("AggregateString can not have null InstanceKey. Value -> " + value); } return new AggregateString(Collections.singletonMap(value, 1), Collections.singleton(instanceKey)); } /** * Update a value for an instance. * <p> * To completely remove a value and its instance, pass in null for newValue * * @param oldValue * @param newValue * @param instanceKey * @return */ public AggregateString update(String oldValue, String newValue, InstanceKey instanceKey) { if (instanceKey == null) { throw new NullPointerException("AggregateString can not have null InstanceKey. Value -> " + newValue); } boolean containsInstance = instances.contains(instanceKey); boolean valuesEqual = valuesEqual(oldValue, newValue); if (containsInstance && valuesEqual) { // no change return this; } else { Set<InstanceKey> _instances; if (containsInstance && newValue != null) { _instances = instances; // pass thru } else if (containsInstance && newValue == null) { _instances = new HashSet<InstanceKey>(instances); // clone _instances.remove(instanceKey); } else { _instances = new HashSet<InstanceKey>(instances); // clone _instances.add(instanceKey); } Map<String, Integer> _values; if (valuesEqual) { _values = values; // pass thru } else { _values = new TreeMap<String, Integer>(values); // clone if (oldValue != null) { _values.computeIfPresent(oldValue, (key, old) -> { if (old == 1) { return null; // remove } else { return old - 1; } }); } if (newValue != null) { _values.merge(newValue, 1, (e, v) -> { if (e == null) { return v; } else { return e + v; } }); } } return new AggregateString(_values, _instances); } } private boolean valuesEqual(String newValue, String oldValue) { if (newValue == oldValue) return true; if (newValue == null) { if (oldValue != null) return false; } else if (!newValue.equals(oldValue)) { return false; } return true; } public Map<String, Integer> values() { return Collections.unmodifiableMap(values); } public Set<InstanceKey> instances() { return Collections.unmodifiableSet(instances); } public String toJson() { return JsonUtility.mapToJson(values); } @Override public String toString() { return getClass().getSimpleName() + " => " + toJson(); } }
9,369
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/NumberList.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.netflix.turbine.internal.JsonUtility; import com.netflix.turbine.internal.NumberListSerializer; @JsonSerialize(using = NumberListSerializer.class) public class NumberList { public static NumberList create(Map<String, Object> numbers) { LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(numbers.size()); for (Entry<String, Object> k : numbers.entrySet()) { Object v = k.getValue(); if (v instanceof Number) { values.put(k.getKey(), ((Number) v).longValue()); } else { values.put(k.getKey(), Long.valueOf(String.valueOf(v))); } } return new NumberList(values); } // unchecked but we know we can go from Map<String, Long> to Map<String, Object> @SuppressWarnings("unchecked") public static NumberList delta(Map<String, Object> currentMap, NumberList previousMap) { return delta(currentMap, (Map)previousMap.numbers); } // unchecked but we know we can go from Map<String, Long> to Map<String, Object> @SuppressWarnings("unchecked") public static NumberList delta(NumberList currentMap, NumberList previousMap) { return delta((Map)currentMap.numbers, (Map)previousMap.numbers); } /** * This assumes both maps contain the same keys. If they don't then keys will be lost. * * @param currentMap * @param previousMap * @return */ public static NumberList delta(Map<String, Object> currentMap, Map<String, Object> previousMap) { LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(currentMap.size()); if(currentMap.size() != previousMap.size()) { throw new IllegalArgumentException("Maps must have the same keys"); } for (Entry<String, Object> k : currentMap.entrySet()) { Object v = k.getValue(); Number current = getNumber(v); Object p = previousMap.get(k.getKey()); Number previous = null; if (p == null) { previous = 0; } else { previous = getNumber(p); } long d = (current.longValue() - previous.longValue()); values.put(k.getKey(), d); } return new NumberList(values); } /** * Return a NubmerList with the inverse of the given values. */ public static NumberList deltaInverse(Map<String, Object> map) { LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(map.size()); for (Entry<String, Object> k : map.entrySet()) { Object v = k.getValue(); Number current = getNumber(v); long d = -current.longValue(); values.put(k.getKey(), d); } return new NumberList(values); } public NumberList sum(NumberList delta) { LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(numbers.size()); for (Entry<String, Long> k : numbers.entrySet()) { Long p = k.getValue(); Long d = delta.get(k.getKey()); Long previous = null; if (p == null) { previous = 0L; } else { previous = p; } // if we're missing the value in the delta we negate it if (d == null) { d = -previous; } long sum = d + previous; values.put(k.getKey(), sum); } return new NumberList(values); } private static Number getNumber(Object v) { Number n = null; if (v instanceof Number) { n = ((Number) v).longValue(); } else { n = Long.valueOf(String.valueOf(v)); } return n; } public static NumberList empty() { return create(Collections.emptyMap()); } private final Map<String, Long> numbers; private NumberList(Map<String, Long> numbers) { this.numbers = numbers; } public Map<String, Long> getMap() { return numbers; } public Long get(String key) { return numbers.get(key); } public Set<Entry<String, Long>> getEntries() { return numbers.entrySet(); } @Override public String toString() { return getClass().getSimpleName() + " => " + numbers.entrySet(); } public String toJson() { return JsonUtility.mapToJson(numbers); } }
9,370
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/StreamAggregator.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import rx.Observable; import rx.observables.GroupedObservable; public class StreamAggregator { public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateGroupedStreams(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) { return aggregateUsingFlattenedGroupBy(stream); } private StreamAggregator() { } /** * Flatten the stream and then do nested groupBy. This matches the mental model and is simple but * serializes the stream to a single thread which is bad for performance. * * TODO: Add a version like this but with a ParallelObservable * * @param stream * @return */ @SuppressWarnings("unused") private static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateUsingFlattenedGroupBy(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) { Observable<Map<String, Object>> allData = stream.flatMap(instanceStream -> { return instanceStream .map((Map<String, Object> event) -> { event.put("InstanceKey", instanceStream.getKey()); event.put("TypeAndName", TypeAndNameKey.from(String.valueOf(event.get("type")), String.valueOf(event.get("name")))); return event; }) .compose(is -> { return tombstone(is, instanceStream.getKey()); }); }); Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> byCommand = allData .groupBy((Map<String, Object> event) -> { return (TypeAndNameKey) event.get("TypeAndName"); }); return byCommand .map(commandGroup -> { Observable<Map<String, Object>> sumOfDeltasForAllInstancesForCommand = commandGroup .groupBy((Map<String, Object> json) -> { return json.get("InstanceKey"); }).flatMap(instanceGroup -> { // calculate and output deltas for each instance stream per command return instanceGroup .takeUntil(d -> d.containsKey("tombstone")) .startWith(Collections.<String, Object> emptyMap()) .map(data -> { if (data.containsKey("tombstone")) { return Collections.<String, Object> emptyMap(); } else { return data; } }) .buffer(2, 1) .filter(list -> list.size() == 2) .map(StreamAggregator::previousAndCurrentToDelta) .filter(data -> data != null && !data.isEmpty()); }) // we now have all instance deltas merged into a single stream per command // and sum them into a single stream of aggregate values .scan(new HashMap<String, Object>(), StreamAggregator::sumOfDelta) .skip(1); // we artificially wrap in a GroupedObservable that communicates the CommandKey this stream represents return GroupedObservable.from(commandGroup.getKey(), sumOfDeltasForAllInstancesForCommand); }); } /** * Append tombstone events to each instanceStream when they terminate so that the last values from the stream * will be removed from all aggregates down stream. * * @param instanceStream * @param instanceKey */ private static Observable<Map<String, Object>> tombstone(Observable<Map<String, Object>> instanceStream, InstanceKey instanceKey) { return instanceStream.publish(is -> { Observable<Map<String, Object>> tombstone = is // collect all unique "TypeAndName" keys .collect(() -> new HashSet<TypeAndNameKey>(), (listOfTypeAndName, event) -> { listOfTypeAndName.add((TypeAndNameKey) event.get("TypeAndName")); }) // when instanceStream completes, emit a "tombstone" for each "TypeAndName" in the HashSet collected above .flatMap(listOfTypeAndName -> { return Observable.from(listOfTypeAndName) .map(typeAndName -> { Map<String, Object> tombstoneForTypeAndName = new LinkedHashMap<>(); tombstoneForTypeAndName.put("tombstone", "true"); tombstoneForTypeAndName.put("InstanceKey", instanceKey); tombstoneForTypeAndName.put("TypeAndName", typeAndName); tombstoneForTypeAndName.put("name", typeAndName.getName()); tombstoneForTypeAndName.put("type", typeAndName.getType()); return tombstoneForTypeAndName; }); }); // concat the tombstone events to the end of the original stream return is.mergeWith(tombstone); }); } /** * This expects to receive a list of 2 items. If it is a different size it will throw an exception. * * @param data * @return */ /* package for unit tests */static final Map<String, Object> previousAndCurrentToDelta(List<Map<String, Object>> data) { if (data.size() == 2) { Map<String, Object> previous = data.get(0); Map<String, Object> current = data.get(1); return previousAndCurrentToDelta(previous, current); } else { throw new IllegalArgumentException("Must be list of 2 items"); } } @SuppressWarnings("unchecked") /* package for unit tests */static final Map<String, Object> previousAndCurrentToDelta(Map<String, Object> previous, Map<String, Object> current) { if (previous.isEmpty()) { // the first time through it is empty so we'll emit the current to start Map<String, Object> seed = new LinkedHashMap<String, Object>(); initMapWithIdentifiers(current, seed); for (String key : current.keySet()) { if (isIdentifierKey(key)) { continue; } Object currentValue = current.get(key); if (currentValue instanceof Number && !key.startsWith("propertyValue_")) { // convert all numbers to Long so they are consistent seed.put(key, ((Number) currentValue).longValue()); } else if (currentValue instanceof Map) { // NOTE: we are expecting maps to only contain key/value pairs with values as numbers seed.put(key, NumberList.create((Map<String, Object>) currentValue)); } else { seed.put(key, new String[] { String.valueOf(currentValue) }); } } return seed; } else if (current.isEmpty() || containsOnlyIdentifiers(current)) { // we are terminating so the delta we emit needs to remove everything Map<String, Object> delta = new LinkedHashMap<String, Object>(); initMapWithIdentifiers(previous, delta); for (String key : previous.keySet()) { if (isIdentifierKey(key)) { continue; } Object previousValue = previous.get(key); if (previousValue instanceof Number && !key.startsWith("propertyValue_")) { Number previousValueAsNumber = (Number) previousValue; long d = -previousValueAsNumber.longValue(); delta.put(key, d); } else if (previousValue instanceof Map) { delta.put(key, NumberList.deltaInverse((Map<String, Object>) previousValue)); } else { delta.put(key, new String[] { String.valueOf(previousValue), null }); } } return delta; } else { // we have previous and current so calculate delta Map<String, Object> delta = new LinkedHashMap<String, Object>(); initMapWithIdentifiers(current, delta); for (String key : current.keySet()) { if (isIdentifierKey(key)) { continue; } Object previousValue = previous.get(key); Object currentValue = current.get(key); if (currentValue instanceof Number && !key.startsWith("propertyValue_")) { if (previousValue == null) { previousValue = 0; } Number previousValueAsNumber = (Number) previousValue; if (currentValue != null) { Number currentValueAsNumber = (Number) currentValue; long d = (currentValueAsNumber.longValue() - previousValueAsNumber.longValue()); delta.put(key, d); } } else if (currentValue instanceof Map) { if (previousValue == null) { delta.put(key, NumberList.create((Map<String, Object>) currentValue)); } else { delta.put(key, NumberList.delta((Map<String, Object>) currentValue, (Map<String, Object>) previousValue)); } } else { delta.put(key, new String[] { String.valueOf(previousValue), String.valueOf(currentValue) }); } } return delta; } } private static boolean isIdentifierKey(String key) { return key.equals("InstanceKey") || key.equals("TypeAndName") || key.equals("instanceId") || key.equals("currentTime") || key.equals("name") || key.equals("type"); } private static boolean containsOnlyIdentifiers(Map<String, Object> m) { for (String k : m.keySet()) { if (!isIdentifierKey(k)) { return false; } } return true; } private static void initMapWithIdentifiers(Map<String, Object> source, Map<String, Object> toInit) { toInit.put("InstanceKey", source.get("InstanceKey")); // we don't aggregate this, just pass it through toInit.put("TypeAndName", source.get("TypeAndName")); // we don't aggregate this, just pass it through toInit.put("instanceId", source.get("instanceId")); // we don't aggregate this, just pass it through toInit.put("name", source.get("name")); // we don't aggregate this, just pass it through toInit.put("type", source.get("type")); // we don't aggregate this, just pass it through } /* package for unit tests */static Map<String, Object> sumOfDelta(Map<String, Object> state, Map<String, Object> delta) { InstanceKey instanceId = (InstanceKey) delta.get("InstanceKey"); if (instanceId == null) { throw new RuntimeException("InstanceKey can not be null"); } for (String key : delta.keySet()) { Object existing = state.get(key); Object current = delta.get(key); if (current instanceof Number) { if (existing == null) { existing = 0; } Number v = (Number) existing; Number d = (Number) delta.get(key); state.put(key, v.longValue() + d.longValue()); } else if (current instanceof NumberList) { if (existing == null) { state.put(key, current); } else { state.put(key, ((NumberList) existing).sum((NumberList) current)); } } else { Object o = delta.get(key); if (o instanceof String[]) { String[] vs = (String[]) o; if (vs.length == 1) { Object previousAggregateString = state.get(key); if (previousAggregateString instanceof AggregateString) { state.put(key, ((AggregateString) previousAggregateString).update(null, vs[0], instanceId)); } else { state.put(key, AggregateString.create(vs[0], instanceId)); } } else { // it should always be AggregateString here since that's all we add above AggregateString pas = (AggregateString) state.get(key); state.put(key, pas.update(vs[0], vs[1], instanceId)); } } else { state.put(key, String.valueOf(o)); } } } return state; } }
9,371
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/aggregator/InstanceKey.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.aggregator; public final class InstanceKey implements GroupKey { final String key; public static InstanceKey create(Number id) { return new InstanceKey(id.toString()); } public static InstanceKey create(String id) { return new InstanceKey(id); } private InstanceKey(String key) { if (key == null) { throw new NullPointerException("InstanceKey can not have null key"); } this.key = key; } public String getKey() { return key; } @Override public String toString() { return "InstanceKey=>" + key; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InstanceKey other = (InstanceKey) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } }
9,372
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/discovery/StreamAction.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery; import java.net.URI; public class StreamAction { public static enum ActionType { ADD, REMOVE } private final ActionType type; private final URI uri; private StreamAction(ActionType type, URI uri) { this.type = type; this.uri = uri; } public static StreamAction create(ActionType type, URI uri) { return new StreamAction(type, uri); } public ActionType getType() { return type; } public URI getUri() { return uri; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((uri == null) ? 0 : uri.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StreamAction other = (StreamAction) obj; if (type != other.type) return false; if (uri == null) { if (other.uri != null) return false; } else if (!uri.equals(other.uri)) return false; return true; } @Override public String toString() { return "StreamAction [type=" + type + ", uri=" + uri + "]"; } }
9,373
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/discovery/StreamDiscovery.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.discovery; import rx.Observable; /** * Interface used by Turbine to get Instances it will connect to. */ public interface StreamDiscovery { /** * Observable of ADD/REMOVE events for Stream URIs * * @return Observable<Instance> */ public Observable<StreamAction> getInstanceList(); }
9,374
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/internal/AggregateStringSerializer.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.internal; import java.io.IOException; import java.util.Map; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import com.netflix.turbine.aggregator.AggregateString; public class AggregateStringSerializer extends JsonSerializer<AggregateString> { @Override public void serialize(AggregateString as, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { Map<String, Integer> values = as.values(); if (values.size() == 1) { String k = values.entrySet().iterator().next().getKey(); if ("false".equals(k)) { jgen.writeBoolean(false); } else if ("true".equals(k)) { jgen.writeBoolean(true); } else { jgen.writeString(k); } } else { jgen.writeObject(values); } } }
9,375
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/internal/NumberListSerializer.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.internal; import java.io.IOException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import com.netflix.turbine.aggregator.NumberList; /** * Need to serialize like this => "latencyExecute":{"0":0,"25":0,"50":2,"75":12,"90":16,"95":22,"99":47,"99.5":363,"100":390} * */ public class NumberListSerializer extends JsonSerializer<NumberList> { @Override public void serialize(NumberList nl, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeObject(nl.getMap()); } }
9,376
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/internal/RequestCreator.java
/** * Copyright 2014 Netflix, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.internal; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.net.URISyntaxException; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; public class RequestCreator { private static final Logger logger = LoggerFactory.getLogger(RequestCreator.class); /** * Creates a {@link HttpClientRequest} for the supplied URI. * If user info is defined in the URI it'll be applied as basic authentication. * * @param uri The URI * @return The generated {@link HttpClientRequest} with basic auth (if applicable) */ public static HttpClientRequest<ByteBuf> createRequest(URI uri) { String uriToUse = stripUserInfoFromUriIfDefined(uri).toASCIIString(); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(uriToUse); if (uri.getUserInfo() != null) { logger.debug("Adding basic authentication header for URI {}", uriToUse); String basicAuth = "Basic " + Base64.getEncoder().encodeToString(uri.getUserInfo().getBytes(UTF_8)); request.withHeader("Authorization", basicAuth); } return request; } private static URI stripUserInfoFromUriIfDefined(URI uri) { final URI uriToUse; if (uri.getUserInfo() != null) { try { uriToUse = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else { uriToUse = uri; } return uriToUse; } }
9,377
0
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine
Create_ds/Turbine/turbine-core/src/main/java/com/netflix/turbine/internal/JsonUtility.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.turbine.internal; import java.io.IOException; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectReader; import org.codehaus.jackson.map.ObjectWriter; public class JsonUtility { private static final JsonUtility INSTANCE = new JsonUtility(); private JsonUtility() { } public static Map<String, Object> jsonToMap(String jsonString) { return INSTANCE._jsonToMap(jsonString); } public static String mapToJson(Map<String, ? extends Object> map) { return INSTANCE._mapToJson(map); } private final ObjectMapper objectMapper = new ObjectMapper(); private final ObjectReader objectReader = objectMapper.reader(Map.class); private Map<String, Object> _jsonToMap(String jsonString) { try { return objectReader.readValue(jsonString); } catch (IOException e) { throw new RuntimeException("Unable to parse JSON", e); } } private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); private String _mapToJson(Map<String, ? extends Object> map) { try { return objectWriter.writeValueAsString(map); } catch (IOException e) { throw new RuntimeException("Unable to write JSON", e); } } }
9,378
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/AWSDatabaseHolderRefreshJob.java
package com.airbnb.billow; import com.codahale.metrics.Counter; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.SchedulerException; public class AWSDatabaseHolderRefreshJob implements Job { public static final String DB_KEY = "db"; public static final String FAILURE_COUNTER_KEY = "failure_counter"; public static final String START_COUNTER_KEY = "start_counter"; public static final String SUCCESS_COUNTER_KEY = "success_counter"; public static final String NAME = "dbRefresh"; @Override public void execute(JobExecutionContext context) throws JobExecutionException { try { increment(START_COUNTER_KEY, context); ((AWSDatabaseHolder) context.getScheduler().getContext().get(DB_KEY)).rebuild(); increment(SUCCESS_COUNTER_KEY, context); } catch (SchedulerException e) { increment(FAILURE_COUNTER_KEY, context); throw new JobExecutionException(e); } } private void increment(String counterName, JobExecutionContext context) { try { ((Counter) context.getScheduler().getContext().get(counterName)).inc(); } catch (SchedulerException e) { // do nothing, don't throw an error for metrics } } }
9,379
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/ElasticacheCluster.java
package com.airbnb.billow; import com.amazonaws.services.elasticache.model.Endpoint; import com.amazonaws.services.elasticache.model.NodeGroupMember; import lombok.Getter; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.elasticache.model.CacheCluster; import com.amazonaws.services.elasticache.model.Tag; import com.fasterxml.jackson.annotation.JsonFilter; /** * Created by tong_wei on 3/15/16. */ @JsonFilter(ElasticacheCluster.CACHE_CLUSTER_FILTER) public class ElasticacheCluster { public static final String CACHE_CLUSTER_FILTER = "CacheClusterFilter"; @Getter private final String cacheClusterId; @Getter String configurationEndpoint; private final String clientDownloadLandingPage; @Getter private final String cacheNodeType; @Getter private final String engine; @Getter private final String engineVersion; @Getter private final String cacheClusterStatus; @Getter private final Integer numCacheNodes; @Getter private final String preferredAvailabilityZone; @Getter private final Date cacheClusterCreateTime; @Getter private final String preferredMaintenanceWindow; @Getter private final String pendingModifiedValues; @Getter private final String notificationConfiguration; @Getter private final String cacheSecurityGroups; @Getter private final String cacheParameterGroup; @Getter private final String cacheSubnetGroupName; @Getter private final String cacheNodes; @Getter private final Boolean autoMinorVersionUpgrade; @Getter private final String securityGroups; @Getter private final String replicationGroupId; @Getter private final Integer snapshotRetentionLimit; @Getter private final String snapshotWindow; @Getter private final Endpoint endpoint; @Getter private final String currentRole; @Getter private final Map<String, String> tags; public ElasticacheCluster(CacheCluster cacheCluster, NodeGroupMember nodeGroupMember, List<Tag> tagList) { this.cacheClusterId = cacheCluster.getCacheClusterId(); this.clientDownloadLandingPage = cacheCluster.getClientDownloadLandingPage(); this.cacheNodeType = cacheCluster.getCacheNodeType(); this.engine = cacheCluster.getEngine(); this.engineVersion = cacheCluster.getEngineVersion(); this.cacheClusterStatus = cacheCluster.getCacheClusterStatus(); this.numCacheNodes = cacheCluster.getNumCacheNodes(); this.preferredAvailabilityZone = cacheCluster.getPreferredAvailabilityZone(); this.cacheClusterCreateTime = cacheCluster.getCacheClusterCreateTime(); this.preferredMaintenanceWindow = cacheCluster.getPreferredMaintenanceWindow(); this.pendingModifiedValues = cacheCluster.getPendingModifiedValues().toString(); if (cacheCluster.getNotificationConfiguration() != null) { this.notificationConfiguration = cacheCluster.getNotificationConfiguration().toString(); } else { this.notificationConfiguration = "empty"; } this.cacheSecurityGroups = cacheCluster.getSecurityGroups().toString(); this.cacheParameterGroup = cacheCluster.getCacheParameterGroup().toString(); this.cacheSubnetGroupName = cacheCluster.getCacheSubnetGroupName(); this.cacheNodes = cacheCluster.getCacheNodes().toString(); this.autoMinorVersionUpgrade = cacheCluster.getAutoMinorVersionUpgrade(); this.securityGroups = cacheCluster.getSecurityGroups().toString(); this.replicationGroupId = cacheCluster.getReplicationGroupId(); this.snapshotRetentionLimit = cacheCluster.getSnapshotRetentionLimit(); this.snapshotWindow = cacheCluster.getSnapshotWindow(); if (nodeGroupMember != null) { this.endpoint = nodeGroupMember.getReadEndpoint(); this.currentRole = nodeGroupMember.getCurrentRole(); } else { this.endpoint = cacheCluster.getConfigurationEndpoint(); this.currentRole = null; } this.tags = new HashMap<>(tagList.size()); for(Tag tag : tagList) { this.tags.put(tag.getKey(), tag.getValue()); } } }
9,380
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/Handler.java
package com.airbnb.billow; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata; import com.amazonaws.services.rds.model.DBInstance; import com.amazonaws.services.rds.model.DBInstanceStatusInfo; import com.amazonaws.services.rds.model.PendingModifiedValues; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.net.HttpHeaders; import ognl.Ognl; import ognl.OgnlException; import org.apache.http.entity.ContentType; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; @Slf4j public class Handler extends AbstractHandler { public static final SimpleFilterProvider NOOP_INSTANCE_FILTER = new SimpleFilterProvider() .addFilter(EC2Instance.INSTANCE_FILTER, SimpleBeanPropertyFilter.serializeAllExcept()); public static final SimpleFilterProvider NOOP_TABLE_FILTER = new SimpleFilterProvider() .addFilter(DynamoTable.TABLE_FILTER, SimpleBeanPropertyFilter.serializeAllExcept()); public static final SimpleFilterProvider NOOP_QUEUE_FILTER = new SimpleFilterProvider() .addFilter(SQSQueue.QUEUE_FILTER, SimpleBeanPropertyFilter.serializeAllExcept()); public static final SimpleFilterProvider NOOP_CACHE_CLUSTER_FILTER = new SimpleFilterProvider() .addFilter(ElasticacheCluster.CACHE_CLUSTER_FILTER, SimpleBeanPropertyFilter.serializeAllExcept()); private final ObjectMapper mapper; private final MetricRegistry registry; private final AWSDatabaseHolder dbHolder; private final long maxDBAgeInMs; public static abstract class DBInstanceMixin extends DBInstance { @JsonIgnore @Override public abstract Boolean isMultiAZ(); @JsonIgnore @Override public abstract Boolean isAutoMinorVersionUpgrade(); @JsonIgnore @Override public abstract Boolean isPubliclyAccessible(); } public static abstract class PendingModifiedValuesMixin extends PendingModifiedValues { @JsonIgnore @Override public abstract Boolean isMultiAZ(); } public static abstract class DBInstanceStatusInfoMixin extends DBInstanceStatusInfo { @JsonIgnore @Override public abstract Boolean isNormal(); } public Handler(MetricRegistry registry, AWSDatabaseHolder dbHolder, long maxDBAgeInMs) { this.mapper = new ObjectMapper(); this.mapper.addMixInAnnotations(DBInstance.class, DBInstanceMixin.class); this.mapper.addMixInAnnotations(PendingModifiedValues.class, PendingModifiedValuesMixin.class); this.mapper.addMixInAnnotations(DBInstanceStatusInfo.class, DBInstanceStatusInfoMixin.class); this.mapper.registerModule(new JodaModule()); this.mapper.registerModule(new GuavaModule()); this.registry = registry; this.dbHolder = dbHolder; this.maxDBAgeInMs = maxDBAgeInMs; } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { try { final Map<String, String[]> paramMap = request.getParameterMap(); final AWSDatabase current = dbHolder.getCurrent(); final long age = current.getAgeInMs(); final float ageInSeconds = (float) age / 1000.0f; response.setHeader("Age", String.format("%.3f", ageInSeconds)); response.setHeader("Cache-Control", String.format("public, max-age=%d", dbHolder.getCacheTimeInMs() / 1000)); switch (target) { case "/ec2": handleComplexEC2(response, paramMap, current); break; case "/rds": handleComplexRDS(response, paramMap, current); break; case "/ec2/all": handleSimpleRequest(response, current.getEc2Instances()); break; case "/rds/all": handleSimpleRequest(response, current.getRdsInstances()); break; case "/ec2/sg": handleSimpleRequest(response, current.getEc2SGs()); break; case "/elasticsearch": handleSimpleRequest(response, current.getElasticsearchClusters()); break; case "/iam": // backwards compatibility with documented feature final ArrayList<AccessKeyMetadata> justKeys = Lists.<AccessKeyMetadata>newArrayList(); for (IAMUserWithKeys userWithKeys : current.getIamUsers()) justKeys.addAll(userWithKeys.getKeys()); handleSimpleRequest(response, justKeys); break; case "/iam/users": handleSimpleRequest(response, current.getIamUsers()); break; case "/dynamo": handleComplexDynamo(response, paramMap, current); break; case "/sqs": handleComplexSQS(response, paramMap, current); break; case "/elasticache/cluster": handleComplexElasticacheCluster(response, paramMap, current); break; default: response.setStatus(HttpServletResponse.SC_NOT_FOUND); break; } } finally { baseRequest.setHandled(true); } } private void handleSimpleRequest(HttpServletResponse response, Object o) { try { response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); mapper.writer(NOOP_INSTANCE_FILTER).writeValue(response.getOutputStream(), o); } catch (Throwable e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("Error handling request", e); } } private void handleComplexElasticacheCluster(HttpServletResponse response, Map<String, String[]> params, AWSDatabase db) { final String query = getQuery(params); final String sort = getSort(params); final int limit = getLimit(params); final Set<String> fields = getFields(params); response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); try { try { final Collection<ElasticacheCluster> queriedQueues = listCacheClustersFromQueryExpression(query, db); final Collection<ElasticacheCluster> sortedQueues = sortWithExpression(queriedQueues, sort); final Iterable<ElasticacheCluster> servedQueues = Iterables.limit(sortedQueues, limit); if (!(servedQueues.iterator().hasNext())) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { final ServletOutputStream outputStream = response.getOutputStream(); final SimpleFilterProvider filterProvider; if (fields != null) { log.debug("filtered output ({})", fields); filterProvider = new SimpleFilterProvider() .addFilter(ElasticacheCluster.CACHE_CLUSTER_FILTER, SimpleBeanPropertyFilter.filterOutAllExcept(fields)); } else { log.debug("unfiltered output"); filterProvider = NOOP_CACHE_CLUSTER_FILTER; } mapper.writer(filterProvider).writeValue(outputStream, Lists.newArrayList(servedQueues)); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.print(e.toString()); outputStream.close(); } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("I/O error handling ElasticacheCluster request", e); } } private void handleComplexSQS(HttpServletResponse response, Map<String, String[]> params, AWSDatabase db) { final String query = getQuery(params); final String sort = getSort(params); final int limit = getLimit(params); final Set<String> fields = getFields(params); response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); try { try { final Collection<SQSQueue> queriedQueues = listQueuesFromQueryExpression(query, db); final Collection<SQSQueue> sortedQueues = sortWithExpression(queriedQueues, sort); final Iterable<SQSQueue> servedQueues = Iterables.limit(sortedQueues, limit); if (!(servedQueues.iterator().hasNext())) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { final ServletOutputStream outputStream = response.getOutputStream(); final SimpleFilterProvider filterProvider; if (fields != null) { log.debug("filtered output ({})", fields); filterProvider = new SimpleFilterProvider() .addFilter(SQSQueue.QUEUE_FILTER, SimpleBeanPropertyFilter.filterOutAllExcept(fields)); } else { log.debug("unfiltered output"); filterProvider = NOOP_QUEUE_FILTER; } mapper.writer(filterProvider).writeValue(outputStream, Lists.newArrayList(servedQueues)); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.print(e.toString()); outputStream.close(); } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("I/O error handling SQS request", e); } } private void handleComplexDynamo(HttpServletResponse response, Map<String, String[]> params, AWSDatabase db) { final String query = getQuery(params); final String sort = getSort(params); final int limit = getLimit(params); final Set<String> fields = getFields(params); response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); try { try { final Collection<DynamoTable> queriedTables = listTablesFromQueryExpression(query, db); final Collection<DynamoTable> sortedTables = sortWithExpression(queriedTables, sort); final Iterable<DynamoTable> servedTables = Iterables.limit(sortedTables, limit); if (!(servedTables.iterator().hasNext())) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { final ServletOutputStream outputStream = response.getOutputStream(); final SimpleFilterProvider filterProvider; if (fields != null) { log.debug("filtered output ({})", fields); filterProvider = new SimpleFilterProvider() .addFilter(DynamoTable.TABLE_FILTER, SimpleBeanPropertyFilter.filterOutAllExcept(fields)); } else { log.debug("unfiltered output"); filterProvider = NOOP_TABLE_FILTER; } mapper.writer(filterProvider).writeValue(outputStream, Lists.newArrayList(servedTables)); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.print(e.toString()); outputStream.close(); } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("I/O error handling DynamoDB request", e); } } private void handleComplexEC2(HttpServletResponse response, Map<String, String[]> params, AWSDatabase db) { final String query = getQuery(params); final String sort = getSort(params); final int limit = getLimit(params); final Set<String> fields = getFields(params); response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); try { try { final Collection<EC2Instance> queriedInstances = listInstancesFromQueryExpression(query, db); final Collection<EC2Instance> sortedInstances = sortWithExpression(queriedInstances, sort); final Iterable<EC2Instance> servedInstances = Iterables.limit(sortedInstances, limit); if (!(servedInstances.iterator().hasNext())) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { final ServletOutputStream outputStream = response.getOutputStream(); final SimpleFilterProvider filterProvider; if (fields != null) { log.debug("filtered output ({})", fields); filterProvider = new SimpleFilterProvider() .addFilter(EC2Instance.INSTANCE_FILTER, SimpleBeanPropertyFilter.filterOutAllExcept(fields)); } else { log.debug("unfiltered output"); filterProvider = NOOP_INSTANCE_FILTER; } mapper.writer(filterProvider).writeValue(outputStream, Lists.newArrayList(servedInstances)); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.print(e.toString()); outputStream.close(); } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("I/O error handling EC2 request", e); } } private void handleComplexRDS(HttpServletResponse response, Map<String, String[]> params, AWSDatabase db) { final String query = getQuery(params); final String sort = getSort(params); final int limit = getLimit(params); final Set<String> fields = getFields(params); response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); try { try { final Collection<RDSInstance> queriedInstances = listDatabaseInstancesFromQueryExpression(query, db); final Collection<RDSInstance> sortedInstances = sortWithExpression(queriedInstances, sort); final Iterable<RDSInstance> servedInstances = Iterables.limit(sortedInstances, limit); if (!(servedInstances.iterator().hasNext())) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { final ServletOutputStream outputStream = response.getOutputStream(); final SimpleFilterProvider filterProvider; if (fields != null) { log.debug("filtered output ({})", fields); filterProvider = new SimpleFilterProvider() .addFilter(RDSInstance.INSTANCE_FILTER, SimpleBeanPropertyFilter.filterOutAllExcept(fields)); } else { log.debug("unfiltered output"); filterProvider = NOOP_INSTANCE_FILTER; } mapper.writer(filterProvider).writeValue(outputStream, Lists.newArrayList(servedInstances)); } } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); final ServletOutputStream outputStream = response.getOutputStream(); outputStream.print(e.toString()); outputStream.close(); } } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("I/O error handling RDS request", e); } } Collection<DynamoTable> listTablesFromQueryExpression(final String expression, final AWSDatabase db) throws OgnlException { final Collection<DynamoTable> allTables = db.getDynamoTables().values(); if (expression == null) return allTables; final Object compiled = Ognl.parseExpression(expression); final List<DynamoTable> tables = new ArrayList<>(); for (DynamoTable table : allTables) { final Object value = Ognl.getValue(compiled, table); if (value instanceof Boolean && (Boolean) value) tables.add(table); } return tables; } Collection<SQSQueue> listQueuesFromQueryExpression(final String expression, final AWSDatabase db) throws OgnlException { final Collection<SQSQueue> allQueues = db.getSqsQueues().values(); if (expression == null) return allQueues; final Object compiled = Ognl.parseExpression(expression); final List<SQSQueue> queues = new ArrayList<>(); for (SQSQueue queue : allQueues) { final Object value = Ognl.getValue(compiled, queue); if (value instanceof Boolean && (Boolean) value) queues.add(queue); } return queues; } Collection<ElasticacheCluster> listCacheClustersFromQueryExpression(final String expression, final AWSDatabase db) throws OgnlException { final Collection<ElasticacheCluster> allClusters = db.getElasticacheClusters().values(); if (expression == null) return allClusters; final Object compiled = Ognl.parseExpression(expression); final List<ElasticacheCluster> clusters = new ArrayList<>(); for (ElasticacheCluster cluster : allClusters) { final Object value = Ognl.getValue(compiled, cluster); if (value instanceof Boolean && (Boolean) value) clusters.add(cluster); } return clusters; } <T> Collection<T> sortWithExpression(final Collection<T> set, final String expression) throws OgnlException { if (expression == null) return set; final Object compiled = Ognl.parseExpression(expression); final ArrayList<T> result = new ArrayList<>(set); Collections.sort(result, new Comparator<T>() { public int compare(T o1, T o2) { try { final Object v1 = Ognl.getValue(compiled, o1); final Object v2 = Ognl.getValue(compiled, o2); if (v1 instanceof Comparable) { return ((Comparable) v1).compareTo(v2); } } catch (OgnlException e) { return 0; } return 0; } }); return result; } Collection<EC2Instance> listInstancesFromQueryExpression(final String expression, final AWSDatabase db) throws OgnlException { final Collection<EC2Instance> allInstances = db.getEc2Instances().values(); if (expression == null) return allInstances; final Object compiled = Ognl.parseExpression(expression); final List<EC2Instance> instances = new ArrayList<>(); for (EC2Instance instance : allInstances) { final Object value = Ognl.getValue(compiled, instance); if (value instanceof Boolean && (Boolean) value) instances.add(instance); } return instances; } Collection<RDSInstance> listDatabaseInstancesFromQueryExpression(final String expression, final AWSDatabase db) throws OgnlException { final Collection<RDSInstance> allInstances = db.getRdsInstances().values(); if (expression == null) return allInstances; final Object compiled = Ognl.parseExpression(expression); final List<RDSInstance> instances = new ArrayList<>(); for (RDSInstance instance : allInstances) { final Object value = Ognl.getValue(compiled, instance); if (value instanceof Boolean && (Boolean) value) instances.add(instance); } return instances; } private String getQuery(Map<String, String[]> params) { final String[] qs = params.get("q"); if (qs != null) return qs[0]; final String[] queries = params.get("query"); if (queries != null) return queries[0]; return null; } private String getSort(Map<String, String[]> params) { final String[] ss = params.get("s"); if (ss != null) return ss[0]; final String[] sorts = params.get("sort"); if (sorts != null) return sorts[0]; return null; } private int getLimit(Map<String, String[]> params) { final String[] ls = params.get("l"); if (ls != null) return Integer.parseInt(ls[0]); final String[] limits = params.get("limit"); if (limits != null) return Integer.parseInt(limits[0]); return Integer.MAX_VALUE; } private Set<String> getFields(Map<String, String[]> params) { final String[] fs = params.get("f"); if (fs != null) return Sets.newHashSet(Splitter.on(',').split(fs[0])); final String[] fields = params.get("fields"); if (fields != null) return Sets.newHashSet(Splitter.on(',').split(fields[0])); return null; } }
9,381
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/IAMUserWithKeys.java
package com.airbnb.billow; import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata; import com.amazonaws.services.identitymanagement.model.User; import com.google.common.collect.ImmutableList; import lombok.Data; @Data public class IAMUserWithKeys { private final User user; private final ImmutableList<AccessKeyMetadata> keys; }
9,382
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/RDSInstance.java
package com.airbnb.billow; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.rds.model.DBCluster; import com.amazonaws.services.rds.model.DBClusterMember; import com.amazonaws.services.rds.model.DBInstance; import com.amazonaws.services.rds.model.DBInstanceStatusInfo; import com.amazonaws.services.rds.model.DBParameterGroupStatus; import com.amazonaws.services.rds.model.DBSecurityGroupMembership; import com.amazonaws.services.rds.model.DBSubnetGroup; import com.amazonaws.services.rds.model.Endpoint; import com.amazonaws.services.rds.model.OptionGroupMembership; import com.amazonaws.services.rds.model.PendingModifiedValues; import com.amazonaws.services.rds.model.Tag; import com.amazonaws.services.rds.model.VpcSecurityGroupMembership; import com.fasterxml.jackson.annotation.JsonFilter; @Slf4j @JsonFilter(RDSInstance.INSTANCE_FILTER) public class RDSInstance { public static final String INSTANCE_FILTER = "InstanceFilter"; @Getter private final Integer allocatedStorage; @Getter private final Boolean autoMinorVersionUpgrade; @Getter private final String availabilityZone; @Getter private final Integer backupRetentionPeriod; @Getter private final String characterSetName; @Getter private final String dBInstanceClass; @Getter private final String dBInstanceIdentifier; @Getter private final String dBInstanceStatus; @Getter private final String dBClusterIdentifier; @Getter private final String dBName; @Getter private final List<DBParameterGroupStatus> dBParameterGroups; @Getter private final List<DBSecurityGroupMembership> dBSecurityGroups; @Getter private final DBSubnetGroup dBSubnetGroup; @Getter private final Endpoint endpoint; @Getter private final String engine; @Getter private final String engineVersion; @Getter private final Date instanceCreateTime; @Getter private final Integer iops; @Getter private final Date latestRestorableTime; @Getter private final String licenseModel; @Getter private final String masterUsername; @Getter private final Boolean multiAZ; @Getter private final List<OptionGroupMembership> optionGroupMemberships; @Getter private final PendingModifiedValues pendingModifiedValues; @Getter private final String preferredBackupWindow; @Getter private final String preferredMaintenanceWindow; @Getter private final Boolean publiclyAccessible; @Getter private final List<String> readReplicaDBInstanceIdentifiers; @Getter private final String readReplicaSourceDBInstanceIdentifier; @Getter private final String secondaryAvailabilityZone; @Getter private final List<DBInstanceStatusInfo> statusInfos; @Getter private final List<VpcSecurityGroupMembership> vpcSecurityGroups; @Getter private final boolean isMaster; @Getter private final Map<String, String> tags; @Getter private final String privateIP; @Getter private final String hostname; @Getter private final List<String> snapshots; @Getter private final String caCertificateIdentifier; public RDSInstance(DBInstance instance, DBCluster cluster, List<Tag> tagList, List<String> snapshots) { this.allocatedStorage = instance.getAllocatedStorage(); this.autoMinorVersionUpgrade = instance.getAutoMinorVersionUpgrade(); this.availabilityZone = instance.getAvailabilityZone(); this.backupRetentionPeriod = instance.getBackupRetentionPeriod(); this.characterSetName = instance.getCharacterSetName(); this.dBInstanceClass = instance.getDBInstanceClass(); this.dBInstanceIdentifier = instance.getDBInstanceIdentifier(); this.dBInstanceStatus = instance.getDBInstanceStatus(); this.dBClusterIdentifier = instance.getDBClusterIdentifier(); this.dBName = instance.getDBName(); this.dBParameterGroups = instance.getDBParameterGroups(); this.dBSecurityGroups = instance.getDBSecurityGroups(); this.dBSubnetGroup = instance.getDBSubnetGroup(); this.endpoint = instance.getEndpoint(); if(this.endpoint != null) { this.hostname = endpoint.getAddress(); this.privateIP = getPrivateIp(hostname); } else { this.hostname = null; this.privateIP = null; } this.engine = instance.getEngine(); this.engineVersion = instance.getEngineVersion(); this.instanceCreateTime = instance.getInstanceCreateTime(); this.iops = instance.getIops(); this.latestRestorableTime = instance.getLatestRestorableTime(); this.licenseModel = instance.getLicenseModel(); this.masterUsername = instance.getMasterUsername(); this.multiAZ = instance.getMultiAZ(); this.optionGroupMemberships = instance.getOptionGroupMemberships(); this.pendingModifiedValues = instance.getPendingModifiedValues(); this.preferredBackupWindow = instance.getPreferredBackupWindow(); this.preferredMaintenanceWindow = instance.getPreferredMaintenanceWindow(); this.publiclyAccessible = instance.getPubliclyAccessible(); this.readReplicaDBInstanceIdentifiers = instance.getReadReplicaDBInstanceIdentifiers(); this.readReplicaSourceDBInstanceIdentifier = instance.getReadReplicaSourceDBInstanceIdentifier(); this.secondaryAvailabilityZone = instance.getSecondaryAvailabilityZone(); this.statusInfos = instance.getStatusInfos(); this.vpcSecurityGroups = instance.getVpcSecurityGroups(); this.isMaster = checkIfMaster(instance, cluster); this.tags = new HashMap<>(tagList.size()); for(Tag tag : tagList) { this.tags.put(tag.getKey(), tag.getValue()); } this.snapshots = new ArrayList<>(snapshots); this.caCertificateIdentifier = instance.getCACertificateIdentifier(); } public static boolean checkIfMaster(DBInstance instance, DBCluster cluster) { if (instance.getDBClusterIdentifier() == null || cluster == null) { // It's NOT a member of a DB cluster return instance.getReadReplicaSourceDBInstanceIdentifier() == null; } else { // It's a member of a DB cluster for (DBClusterMember member : cluster.getDBClusterMembers()) { if (member.getDBInstanceIdentifier().equals(instance.getDBInstanceIdentifier()) && member.isClusterWriter()) { return true; } } return false; } } private String getPrivateIp(String hostname) { try { InetAddress address = InetAddress.getByName(hostname); return address.getHostAddress().toString(); } catch (UnknownHostException e) { log.error("{}", e); } return null; } }
9,383
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/AWSDatabaseHolder.java
package com.airbnb.billow; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.retry.RetryPolicy; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.Region; import com.amazonaws.services.elasticache.AmazonElastiCacheClient; import com.amazonaws.services.elasticsearch.AWSElasticsearchClient; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.rds.AmazonRDSClient; import com.amazonaws.services.sqs.AmazonSQSClient; import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.Maps; import com.typesafe.config.Config; @Slf4j public class AWSDatabaseHolder { private final Map<String, AmazonEC2Client> ec2Clients; private final Map<String, AmazonRDSClient> rdsClients; private final Map<String, AmazonDynamoDBClient> dynamoDBClients; private final Map<String, AmazonSQSClient> sqsClients; private final Map<String, AmazonElastiCacheClient> elasticacheClients; private final Map<String, AWSElasticsearchClient> elasticsearchClients; private final AmazonIdentityManagement iamClient; @Getter private AWSDatabase current; private final long maxAgeInMs; private final String awsAccountNumber; private final String awsARNPartition; public AWSDatabaseHolder(Config config) { maxAgeInMs = config.getDuration("maxAge", TimeUnit.MILLISECONDS); final DefaultAWSCredentialsProviderChain awsCredentialsProviderChain = new DefaultAWSCredentialsProviderChain(); final ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setRetryPolicy(new RetryPolicy(null, null, config.getInt("maxErrorRetry"), true)); clientConfig.setSocketTimeout(config.getInt("socketTimeout") * 1000); final AmazonEC2 bootstrapEC2Client = AmazonEC2ClientBuilder.standard().withCredentials(awsCredentialsProviderChain).build(); ec2Clients = Maps.newHashMap(); rdsClients = Maps.newHashMap(); sqsClients = Maps.newHashMap(); dynamoDBClients = Maps.newHashMap(); elasticacheClients = Maps.newHashMap(); elasticsearchClients = Maps.newHashMap(); final List<Region> ec2Regions = bootstrapEC2Client.describeRegions().getRegions(); for (Region region : ec2Regions) { final String regionName = region.getRegionName(); final String endpoint = region.getEndpoint(); log.debug("Adding ec2 region {}", region); if (config.getBoolean("ec2Enabled")) { final AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentialsProviderChain, clientConfig); ec2Client.setEndpoint(endpoint); ec2Clients.put(regionName, ec2Client); } if (config.getBoolean("rdsEnabled")) { final AmazonRDSClient rdsClient = new AmazonRDSClient(awsCredentialsProviderChain, clientConfig); rdsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "rds.")); rdsClients.put(regionName, rdsClient); } if (config.getBoolean("dynamodbEnabled")) { final AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(awsCredentialsProviderChain, clientConfig); dynamoDBClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "dynamodb.")); dynamoDBClients.put(regionName, dynamoDBClient); } if (config.getBoolean("sqsEnabled")) { final AmazonSQSClient sqsClient = new AmazonSQSClient(awsCredentialsProviderChain, clientConfig); sqsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "sqs.")); sqsClients.put(regionName, sqsClient); } if (config.getBoolean("elasticacheEnabled")) { final AmazonElastiCacheClient elastiCacheClient = new AmazonElastiCacheClient (awsCredentialsProviderChain, clientConfig); elastiCacheClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "elasticache.")); elasticacheClients.put(regionName, elastiCacheClient); } if (config.getBoolean("elasticsearchEnabled")) { final AWSElasticsearchClient elasticsearchClient = new AWSElasticsearchClient (awsCredentialsProviderChain, clientConfig); elasticsearchClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "es.")); elasticsearchClients.put(regionName, elasticsearchClient); } } this.iamClient = AmazonIdentityManagementClientBuilder.standard() .withCredentials(awsCredentialsProviderChain) .withClientConfiguration(clientConfig) .build(); if (config.hasPath("accountNumber")) { this.awsAccountNumber = config.getString("accountNumber"); } else { this.awsAccountNumber = null; } if (config.hasPath("arnPartition")) { this.awsARNPartition = config.getString("arnPartition"); } else { this.awsARNPartition = "aws"; } rebuild(); } public void rebuild() { current = new AWSDatabase( ec2Clients, rdsClients, dynamoDBClients, sqsClients, elasticacheClients, elasticsearchClients, iamClient, awsAccountNumber, awsARNPartition); } public HealthCheck.Result healthy() { final long ageInMs = current.getAgeInMs(); if (ageInMs < maxAgeInMs) return HealthCheck.Result.healthy(); else return HealthCheck.Result.unhealthy("DB too old: " + ageInMs + " ms"); } public long getCacheTimeInMs() { return maxAgeInMs - current.getAgeInMs(); } }
9,384
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/EC2Instance.java
package com.airbnb.billow; import lombok.Getter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.ec2.model.GroupIdentifier; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.StateReason; import com.amazonaws.services.ec2.model.Tag; import com.fasterxml.jackson.annotation.JsonFilter; import org.joda.time.DateTime; import org.joda.time.Interval; @JsonFilter(EC2Instance.INSTANCE_FILTER) public class EC2Instance { public static final String INSTANCE_FILTER = "InstanceFilter"; @Getter private final String id; @Getter private final String type; @Getter private final String lifecycle; @Getter private final String hypervisor; @Getter private final String az; @Getter private final String group; @Getter private final String tenancy; @Getter private final String platform; @Getter private final String kernel; @Getter private final String key; @Getter private final String image; @Getter private final String privateIP; @Getter private final String publicIP; @Getter private final String publicHostname; @Getter private final String privateHostname; @Getter private final String architecture; @Getter private final String state; @Getter private final String ramdisk; @Getter private final String subnet; @Getter private final String rootDeviceName; @Getter private final String rootDeviceType; @Getter private final String stateTransitionReason; @Getter private final String spotInstanceRequest; @Getter private final String virtualizationType; @Getter private final Boolean sourceDestCheck; @Getter private final String stateReason; @Getter private final String vpc; @Getter private final Map<String, String> tags; @Getter private final DateTime launchTime; @Getter private final List<SecurityGroup> securityGroups; @Getter private final String iamInstanceProfile; public EC2Instance(Instance instance) { this.id = instance.getInstanceId(); this.type = instance.getInstanceType(); this.lifecycle = instance.getInstanceLifecycle(); this.hypervisor = instance.getHypervisor(); this.az = instance.getPlacement().getAvailabilityZone(); this.group = instance.getPlacement().getGroupName(); this.tenancy = instance.getPlacement().getTenancy(); this.vpc = instance.getVpcId(); this.platform = instance.getPlatform(); this.kernel = instance.getKernelId(); this.key = instance.getKeyName(); this.image = instance.getImageId(); this.privateIP = instance.getPrivateIpAddress(); this.publicIP = instance.getPublicIpAddress(); this.publicHostname = instance.getPublicDnsName(); this.privateHostname = instance.getPrivateDnsName(); this.architecture = instance.getArchitecture(); this.state = instance.getState().getName(); this.ramdisk = instance.getRamdiskId(); this.subnet = instance.getSubnetId(); this.rootDeviceName = instance.getRootDeviceName(); this.rootDeviceType = instance.getRootDeviceType(); this.stateTransitionReason = instance.getStateTransitionReason(); this.spotInstanceRequest = instance.getSpotInstanceRequestId(); this.virtualizationType = instance.getVirtualizationType(); this.sourceDestCheck = instance.getSourceDestCheck(); this.launchTime = new DateTime(instance.getLaunchTime()); if (instance.getIamInstanceProfile() != null) { this.iamInstanceProfile = instance.getIamInstanceProfile().getArn().toString(); } else { this.iamInstanceProfile = null; } final StateReason stateReason = instance.getStateReason(); if (stateReason != null) this.stateReason = stateReason.getMessage(); else this.stateReason = null; this.securityGroups = new ArrayList<>(); for (GroupIdentifier identifier : instance.getSecurityGroups()) { this.securityGroups.add(new SecurityGroup(identifier)); } this.tags = new HashMap<>(); for (Tag tag : instance.getTags()) { this.tags.put(tag.getKey(), tag.getValue()); } } public float getDaysOld() { return new Interval(this.launchTime, new DateTime()).toDurationMillis() / (1000.0f * 60.0f * 60.0f * 24.0f); } private static final class SecurityGroup { @Getter private final String id; @Getter private final String name; public SecurityGroup(GroupIdentifier id) { this.id = id.getGroupId(); this.name = id.getGroupName(); } } }
9,385
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/Main.java
package com.airbnb.billow; import com.codahale.metrics.CachedGauge; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import com.codahale.metrics.jetty9.InstrumentedHandler; import com.codahale.metrics.servlets.AdminServlet; import com.codahale.metrics.servlets.HealthCheckServlet; import com.codahale.metrics.servlets.MetricsServlet; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigFactory; import lombok.extern.slf4j.Slf4j; import org.coursera.metrics.datadog.DatadogReporter; import org.coursera.metrics.datadog.transport.UdpTransport; import org.eclipse.jetty.server.*; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SimpleTrigger; import org.quartz.impl.StdSchedulerFactory; import javax.servlet.ServletContext; import java.io.IOException; import java.util.concurrent.TimeUnit; import static com.google.common.io.Resources.getResource; import static org.quartz.JobBuilder.newJob; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import static org.quartz.TriggerBuilder.newTrigger; @Slf4j public class Main { private Main(Config config) throws Exception { log.info("Startup..."); try { System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8)); } catch (IllegalArgumentException | IOException e) { log.debug("No banner.txt", e); } final MetricRegistry metricRegistry = new MetricRegistry(); final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); log.info("Creating database"); final Config awsConfig = config.getConfig("aws"); final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS); final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig); final Gauge<Long> cacheAgeGauge = new CachedGauge<Long>(1, TimeUnit.MINUTES) { @Override protected Long loadValue() { return dbHolder.getCurrent().getAgeInMs(); } }; final String databaseAgeMetricName = MetricRegistry.name("billow", "database", "age", "ms"); final String jobFailureMetricName = MetricRegistry.name("billow", "database", "refresh", "start"); final String jobStartMetricName = MetricRegistry.name("billow", "database", "refresh", "failure"); final String jobSuccessMetricName = MetricRegistry.name("billow", "database", "refresh", "success"); metricRegistry.register(databaseAgeMetricName, cacheAgeGauge); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.START_COUNTER_KEY, metricRegistry.counter(jobStartMetricName)); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.FAILURE_COUNTER_KEY, metricRegistry.counter(jobFailureMetricName)); scheduler.getContext().put(AWSDatabaseHolderRefreshJob.SUCCESS_COUNTER_KEY, metricRegistry.counter(jobSuccessMetricName)); scheduler.start(); final SimpleTrigger trigger = newTrigger(). withIdentity(AWSDatabaseHolderRefreshJob.NAME). startNow(). withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()). build(); final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class). withIdentity(AWSDatabaseHolderRefreshJob.NAME). build(); scheduler.scheduleJob(jobDetail, trigger); log.info("Creating age health check"); healthCheckRegistry.register("DB", new HealthCheck() { @Override protected Result check() throws Exception { return dbHolder.healthy(); } }); log.info("Creating HTTP servers"); final Server mainServer = new Server(config.getInt("mainPort")); final Server adminServer = new Server(config.getInt("adminPort")); configureConnectors(mainServer); configureConnectors(adminServer); log.info("Creating HTTP handlers"); final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate); final InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry); instrumentedHandler.setHandler(mainHandler); mainServer.setHandler(instrumentedHandler); final ServletContextHandler adminHandler = new ServletContextHandler(); adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*"); final Config datadogConfig = config.getConfig("datadog"); if (datadogConfig.getBoolean("enabled")) { log.info("Enabling datadog reporting..."); int datadogPort = datadogConfig.hasPath("port") ? datadogConfig.getInt("port") : 8125; DatadogReporter datadogReporter = DatadogReporter.forRegistry(metricRegistry). withTransport(new UdpTransport.Builder().withPort(datadogPort).build()).build(); datadogReporter.start(1, TimeUnit.MINUTES); } final ServletContext adminContext = adminHandler.getServletContext(); adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry); adminServer.setHandler(adminHandler); log.info("Starting HTTP servers"); adminServer.start(); mainServer.start(); log.info("Joining..."); mainServer.join(); adminServer.join(); log.info("Shutting down scheduler..."); scheduler.shutdown(); log.info("We're done!"); } public static void main(String[] args) { try { final Config config = ConfigFactory.load().getConfig("billow"); try { System.setProperty("aws.accessKeyId", config.getString("aws.accessKeyId")); System.setProperty("aws.secretKey", config.getString("aws.secretKeyId")); } catch (ConfigException.Missing _) { System.clearProperty("aws.accessKeyId"); System.clearProperty("aws.secretKey"); } Main.log.debug("Loaded config: {}", config); new Main(config); } catch (Throwable t) { Main.log.error("Failure in main thread, getting out!", t); System.exit(1); } } private static void configureConnectors(Server server) { for (Connector c : server.getConnectors()) { for (ConnectionFactory f : c.getConnectionFactories()) if (f instanceof HttpConnectionFactory) { final HttpConfiguration httpConf = ((HttpConnectionFactory) f).getHttpConfiguration(); httpConf.setSendServerVersion(false); httpConf.setSendDateHeader(false); } } } }
9,386
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/SQSQueue.java
package com.airbnb.billow; import lombok.Getter; import com.fasterxml.jackson.annotation.JsonFilter; @JsonFilter(SQSQueue.QUEUE_FILTER) public class SQSQueue { public static final String QUEUE_FILTER = "QueueFilter"; public static final String ATTR_APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED = "ApproximateNumberOfMessagesDelayed"; public static final String ATTR_RECEIVE_MESSAGE_WAIT_TIME_SECONDS = "ReceiveMessageWaitTimeSeconds"; public static final String ATTR_CREATED_TIMESTAMP = "CreatedTimestamp"; public static final String ATTR_DELAY_SECONDS = "DelaySeconds"; public static final String ATTR_MESSAGE_RETENTION_PERIOD = "MessageRetentionPeriod"; public static final String ATTR_MAXIMUM_MESSAGE_SIZE = "MaximumMessageSize"; public static final String ATTR_VISIBILITY_TIMEOUT = "VisibilityTimeout"; public static final String ATTR_APPROXIMATE_NUMBER_OF_MESSAGES = "ApproximateNumberOfMessages"; public static final String ATTR_LAST_MODIFIED_TIMESTAMP = "LastModifiedTimestamp"; public static final String ATTR_QUEUE_ARN = "QueueArn"; @Getter private final String url; @Getter private final Long approximateNumberOfMessagesDelayed; @Getter private final Long receiveMessageWaitTimeSeconds; @Getter private final Long createdTimestamp; @Getter private final Long delaySeconds; @Getter private final Long messageRetentionPeriod; @Getter private final Long maximumMessageSize; @Getter private final Long visibilityTimeout; @Getter private final Long approximateNumberOfMessages; @Getter private final Long lastModifiedTimestamp; @Getter private final String queueArn; public SQSQueue(String url, Long approximateNumberOfMessagesDelayed, Long receiveMessageWaitTimeSeconds, Long createdTimestamp, Long delaySeconds, Long messageRetentionPeriod, Long maximumMessageSize, Long visibilityTimeout, Long approximateNumberOfMessages, Long lastModifiedTimestamp, String queueArn) { this.url = url; this.approximateNumberOfMessagesDelayed = approximateNumberOfMessagesDelayed; this.receiveMessageWaitTimeSeconds = receiveMessageWaitTimeSeconds; this.createdTimestamp = createdTimestamp; this.delaySeconds = delaySeconds; this.messageRetentionPeriod = messageRetentionPeriod; this.maximumMessageSize = maximumMessageSize; this.visibilityTimeout = visibilityTimeout; this.approximateNumberOfMessages = approximateNumberOfMessages; this.lastModifiedTimestamp = lastModifiedTimestamp; this.queueArn = queueArn; } }
9,387
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/ElasticsearchCluster.java
package com.airbnb.billow; import com.amazonaws.services.elasticsearch.model.ElasticsearchClusterConfig; import com.amazonaws.services.elasticsearch.model.ElasticsearchDomainStatus; import com.amazonaws.services.elasticsearch.model.Tag; import lombok.Getter; import java.util.HashMap; import java.util.List; import java.util.Map; public class ElasticsearchCluster { @Getter private final String domainName; @Getter private final Map<String, String> tags; @Getter private final String version; @Getter private final String instanceType; @Getter private final int instanceCount; @Getter private final Map<String, String> endpoints; @Getter private final boolean dedicatedMasterEnabled; @Getter private final boolean zoneAwarenessEnabled; @Getter private final String dedicatedMasterType; @Getter private final int dedicatedMasterCount; public ElasticsearchCluster(ElasticsearchDomainStatus domainStatus, List<Tag> tagList) { this.domainName = domainStatus.getDomainName(); this.tags = new HashMap<>(tagList.size()); for(Tag tag : tagList) { this.tags.put(tag.getKey(), tag.getValue()); } this.version = domainStatus.getElasticsearchVersion(); this.endpoints = domainStatus.getEndpoints(); ElasticsearchClusterConfig esConfig = domainStatus.getElasticsearchClusterConfig(); this.instanceType = esConfig.getInstanceType(); this.instanceCount = esConfig.getInstanceCount(); this.dedicatedMasterEnabled = esConfig.getDedicatedMasterEnabled(); this.zoneAwarenessEnabled = esConfig.getZoneAwarenessEnabled(); if (esConfig.getDedicatedMasterEnabled()) { this.dedicatedMasterCount = esConfig.getDedicatedMasterCount(); this.dedicatedMasterType = esConfig.getDedicatedMasterType(); } else { this.dedicatedMasterCount = 0; this.dedicatedMasterType = ""; } } }
9,388
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/DynamoTable.java
package com.airbnb.billow; import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndexDescription; import java.util.ArrayList; import java.util.List; import lombok.Getter; import com.amazonaws.services.dynamodbv2.document.Table; import com.fasterxml.jackson.annotation.JsonFilter; import org.joda.time.DateTime; @JsonFilter(DynamoTable.TABLE_FILTER) public class DynamoTable { public static final String TABLE_FILTER = "TableFilter"; @Getter private final String tableName; @Getter private final String attributeDefinitions; @Getter private final String tableStatus; @Getter private final String keySchema; @Getter private final DateTime creationDateTime; @Getter private final long numberOfDecreasesToday; @Getter private final long readCapacityUnits; @Getter private final long writeCapacityUnits; @Getter private final long tableSizeBytes; @Getter private final long itemCount; @Getter private final String tableArn; @Getter private final String provisionedThroughput; @Getter private final List<DynamoGSI> globalSecondaryIndexes; public DynamoTable(Table table) { table.describe(); tableName = table.getTableName(); attributeDefinitions = table.getDescription().getAttributeDefinitions().toString(); tableStatus = table.getDescription().getTableStatus(); keySchema = table.getDescription().getKeySchema().toString(); creationDateTime = new DateTime(table.getDescription().getCreationDateTime()); numberOfDecreasesToday = table.getDescription().getProvisionedThroughput().getNumberOfDecreasesToday(); readCapacityUnits = table.getDescription().getProvisionedThroughput().getReadCapacityUnits(); writeCapacityUnits = table.getDescription().getProvisionedThroughput().getWriteCapacityUnits(); tableSizeBytes = table.getDescription().getTableSizeBytes(); itemCount = table.getDescription().getItemCount(); tableArn = table.getDescription().getTableArn(); provisionedThroughput = table.getDescription().getProvisionedThroughput().toString(); globalSecondaryIndexes = new ArrayList<>(); if (table.getDescription().getGlobalSecondaryIndexes() != null) { for (GlobalSecondaryIndexDescription gsiDesc : table .getDescription() .getGlobalSecondaryIndexes()) { globalSecondaryIndexes.add(new DynamoGSI(gsiDesc)); } } } private static final class DynamoGSI { @Getter private final String gsiName; @Getter private final Long readCapacityUnits; @Getter private final Long writeCapacityUnits; @Getter private final Long itemCount; @Getter private final Long indexSizeBytes; @Getter private final String indexStatus; @Getter private final Boolean backfilling; @Getter private final String indexArn; public DynamoGSI(GlobalSecondaryIndexDescription desc) { gsiName = desc.getIndexName(); readCapacityUnits = desc.getProvisionedThroughput().getReadCapacityUnits(); writeCapacityUnits = desc.getProvisionedThroughput().getWriteCapacityUnits(); itemCount = desc.getItemCount(); indexSizeBytes = desc.getIndexSizeBytes(); indexStatus = desc.getIndexStatus(); backfilling = desc.getBackfilling(); indexArn = desc.getIndexArn(); } } }
9,389
0
Create_ds/billow/src/main/java/com/airbnb
Create_ds/billow/src/main/java/com/airbnb/billow/AWSDatabase.java
package com.airbnb.billow; import com.amazonaws.services.elasticache.model.DescribeReplicationGroupsRequest; import com.amazonaws.services.elasticache.model.DescribeReplicationGroupsResult; import com.amazonaws.services.elasticache.model.NodeGroup; import com.amazonaws.services.elasticache.model.NodeGroupMember; import com.amazonaws.services.elasticache.model.ReplicationGroup; import com.amazonaws.services.elasticsearch.model.DescribeElasticsearchDomainRequest; import com.amazonaws.services.elasticsearch.model.DescribeElasticsearchDomainResult; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.TableCollection; import com.amazonaws.services.dynamodbv2.model.ListTablesResult; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.SecurityGroup; import com.amazonaws.services.elasticache.AmazonElastiCacheClient; import com.amazonaws.services.elasticache.model.CacheCluster; import com.amazonaws.services.elasticache.model.DescribeCacheClustersRequest; import com.amazonaws.services.elasticache.model.DescribeCacheClustersResult; import com.amazonaws.services.elasticsearch.AWSElasticsearchClient; import com.amazonaws.services.elasticsearch.model.DomainInfo; import com.amazonaws.services.elasticsearch.model.ListDomainNamesRequest; import com.amazonaws.services.elasticsearch.model.ListDomainNamesResult; import com.amazonaws.services.elasticsearch.model.ListTagsRequest; import com.amazonaws.services.elasticsearch.model.ListTagsResult; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata; import com.amazonaws.services.identitymanagement.model.ListAccessKeysRequest; import com.amazonaws.services.identitymanagement.model.ListUsersRequest; import com.amazonaws.services.identitymanagement.model.ListUsersResult; import com.amazonaws.services.identitymanagement.model.User; import com.amazonaws.services.rds.AmazonRDSClient; import com.amazonaws.services.rds.model.DBCluster; import com.amazonaws.services.rds.model.DBClusterMember; import com.amazonaws.services.rds.model.DBClusterSnapshot; import com.amazonaws.services.rds.model.DBInstance; import com.amazonaws.services.rds.model.DBSnapshot; import com.amazonaws.services.rds.model.DescribeDBClusterSnapshotsRequest; import com.amazonaws.services.rds.model.DescribeDBClusterSnapshotsResult; import com.amazonaws.services.rds.model.DescribeDBClustersRequest; import com.amazonaws.services.rds.model.DescribeDBClustersResult; import com.amazonaws.services.rds.model.DescribeDBInstancesRequest; import com.amazonaws.services.rds.model.DescribeDBInstancesResult; import com.amazonaws.services.rds.model.DescribeDBSnapshotsRequest; import com.amazonaws.services.rds.model.DescribeDBSnapshotsResult; import com.amazonaws.services.rds.model.ListTagsForResourceRequest; import com.amazonaws.services.rds.model.ListTagsForResourceResult; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; @Slf4j @Data public class AWSDatabase { private final ImmutableMultimap<String, EC2Instance> ec2Instances; private final ImmutableMultimap<String, DynamoTable> dynamoTables; private final ImmutableMultimap<String, RDSInstance> rdsInstances; private final ImmutableMultimap<String, SecurityGroup> ec2SGs; private final ImmutableMultimap<String, SQSQueue> sqsQueues; private final ImmutableMultimap<String, ElasticacheCluster> elasticacheClusters; private final ImmutableMultimap<String, ElasticsearchCluster> elasticsearchClusters; private final ImmutableList<IAMUserWithKeys> iamUsers; private final long timestamp; private String awsAccountNumber; private String awsARNPartition; AWSDatabase(final Map<String, AmazonEC2Client> ec2Clients, final Map<String, AmazonRDSClient> rdsClients, final Map<String, AmazonDynamoDBClient> dynamoClients, final Map<String, AmazonSQSClient> sqsClients, final Map<String, AmazonElastiCacheClient> elasticacheClients, final Map<String, AWSElasticsearchClient> elasticsearchClients, final AmazonIdentityManagement iamClient, final String configAWSAccountNumber, final String configAWSARNPartition) { timestamp = System.currentTimeMillis(); log.info("Building AWS DB with timestamp {}", timestamp); log.info("Getting EC2 instances"); final ImmutableMultimap.Builder<String, EC2Instance> ec2InstanceBuilder = new ImmutableMultimap.Builder<>(); final ImmutableMultimap.Builder<String, DynamoTable> dynamoTableBuilder = new ImmutableMultimap.Builder<>(); final ImmutableMultimap.Builder<String, SQSQueue> sqsQueueBuilder = new ImmutableMultimap.Builder<>(); final ImmutableMultimap.Builder<String, ElasticacheCluster> elasticacheClusterBuilder = new ImmutableMultimap.Builder<>(); final ImmutableMultimap.Builder<String, ElasticsearchCluster> elasticsearchClusterBuilder = new ImmutableMultimap.Builder<>(); if (configAWSAccountNumber == null) { awsAccountNumber = ""; } else { log.info("using account number '{}' from config", configAWSAccountNumber); awsAccountNumber = configAWSAccountNumber; } if (configAWSARNPartition == null) { awsARNPartition = "aws"; } else { log.info("using arn partition '{}' from config", configAWSARNPartition); awsARNPartition = configAWSARNPartition; } /* * IAM keys * Put this in the beginning to populate the awsAccountNumber. */ log.info("Getting IAM keys"); final ImmutableList.Builder<IAMUserWithKeys> usersBuilder = new ImmutableList.Builder<>(); final ListUsersRequest listUsersRequest = new ListUsersRequest(); ListUsersResult listUsersResult; do { log.debug("Performing IAM request: {}", listUsersRequest); listUsersResult = iamClient.listUsers(listUsersRequest); final List<User> users = listUsersResult.getUsers(); log.debug("Found {} users", users.size()); for (User user : users) { final ListAccessKeysRequest listAccessKeysRequest = new ListAccessKeysRequest(); listAccessKeysRequest.setUserName(user.getUserName()); final List<AccessKeyMetadata> accessKeyMetadata = iamClient.listAccessKeys(listAccessKeysRequest).getAccessKeyMetadata(); final IAMUserWithKeys userWithKeys = new IAMUserWithKeys(user, ImmutableList.<AccessKeyMetadata>copyOf(accessKeyMetadata)); usersBuilder.add(userWithKeys); if (awsAccountNumber.isEmpty()) { awsAccountNumber = user.getArn().split(":")[4]; } } listUsersRequest.setMarker(listUsersResult.getMarker()); } while (listUsersResult.isTruncated()); this.iamUsers = usersBuilder.build(); /* * ElasticCache */ for (Map.Entry<String, AmazonElastiCacheClient> clientPair : elasticacheClients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonElastiCacheClient client = clientPair.getValue(); final Map<String, NodeGroupMember> clusterIdToNodeGroupMember = new HashMap<>(); DescribeCacheClustersRequest describeCacheClustersRequest = new DescribeCacheClustersRequest(); DescribeReplicationGroupsRequest describeReplicationGroupsRequest = new DescribeReplicationGroupsRequest(); DescribeCacheClustersResult describeCacheClustersResult; DescribeReplicationGroupsResult describeReplicationGroupsResult; do { log.info("Getting Elasticache replication groups from {} with marker {}", regionName, describeReplicationGroupsRequest.getMarker()); describeReplicationGroupsResult = client.describeReplicationGroups(describeReplicationGroupsRequest); for (ReplicationGroup replicationGroup: describeReplicationGroupsResult.getReplicationGroups()) { for (NodeGroup nodeGroup: replicationGroup.getNodeGroups()) { for (NodeGroupMember nodeGroupMember: nodeGroup.getNodeGroupMembers()) { clusterIdToNodeGroupMember.put(nodeGroupMember.getCacheClusterId(), nodeGroupMember); } } } describeReplicationGroupsRequest.setMarker(describeReplicationGroupsResult.getMarker()); } while (describeReplicationGroupsResult.getMarker() != null); do { log.info("Getting Elasticache from {} with marker {}", regionName, describeCacheClustersRequest.getMarker()); describeCacheClustersResult = client.describeCacheClusters(describeCacheClustersRequest); int cntClusters = 0; for (CacheCluster cluster : describeCacheClustersResult.getCacheClusters()) { com.amazonaws.services.elasticache.model.ListTagsForResourceRequest tagsRequest = new com.amazonaws.services.elasticache.model.ListTagsForResourceRequest() .withResourceName(elasticacheARN(awsARNPartition, regionName, awsAccountNumber, cluster)); com.amazonaws.services.elasticache.model.ListTagsForResourceResult tagsResult = client.listTagsForResource(tagsRequest); elasticacheClusterBuilder.putAll(regionName, new ElasticacheCluster(cluster, clusterIdToNodeGroupMember.get(cluster.getCacheClusterId()), tagsResult.getTagList())); cntClusters++; } log.debug("Found {} cache clusters in {}", cntClusters, regionName); describeCacheClustersRequest.setMarker(describeCacheClustersResult.getMarker()); } while (describeCacheClustersResult.getMarker() != null); } this.elasticacheClusters = elasticacheClusterBuilder.build(); /* * Elasticsearch */ for (Map.Entry<String, AWSElasticsearchClient> clientPair : elasticsearchClients.entrySet()) { final String regionName = clientPair.getKey(); final AWSElasticsearchClient client = clientPair.getValue(); ListDomainNamesRequest domainNamesRequest = new ListDomainNamesRequest(); ListDomainNamesResult domainNamesResult = client.listDomainNames(domainNamesRequest); List<DomainInfo> domainInfoList = domainNamesResult.getDomainNames(); for (DomainInfo domainInfo : domainInfoList) { ListTagsRequest listTagsRequest = new ListTagsRequest(); listTagsRequest.setARN(elasticsearchARN(awsARNPartition, regionName, awsAccountNumber, domainInfo.getDomainName())); ListTagsResult tagList = client.listTags(listTagsRequest); DescribeElasticsearchDomainRequest describeDomainRequest = new DescribeElasticsearchDomainRequest(); describeDomainRequest.setDomainName(domainInfo.getDomainName()); DescribeElasticsearchDomainResult describeDomainResult = client.describeElasticsearchDomain(describeDomainRequest); elasticsearchClusterBuilder.putAll(regionName, new ElasticsearchCluster(describeDomainResult.getDomainStatus(), tagList.getTagList())); } log.debug("Found {} Elasticsearch domains in {}", domainInfoList.size(), regionName); } this.elasticsearchClusters = elasticsearchClusterBuilder.build(); /* * SQS Queues */ for (Map.Entry<String, AmazonSQSClient> clientPair : sqsClients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonSQSClient client = clientPair.getValue(); ListQueuesResult queues = client.listQueues(); log.info("Getting SQS from {}", regionName); int cnt = 0; for (String url : queues.getQueueUrls()) { List<String> attrs = new ArrayList<>(); attrs.add("All"); Map<String, String> map = client.getQueueAttributes(url, attrs).getAttributes(); String approximateNumberOfMessagesDelayed = map.get(SQSQueue.ATTR_APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED); String receiveMessageWaitTimeSeconds = map.get(SQSQueue.ATTR_RECEIVE_MESSAGE_WAIT_TIME_SECONDS); String createdTimestamp = map.get(SQSQueue.ATTR_CREATED_TIMESTAMP); String delaySeconds = map.get(SQSQueue.ATTR_DELAY_SECONDS); String messageRetentionPeriod = map.get(SQSQueue.ATTR_MESSAGE_RETENTION_PERIOD); String maximumMessageSize = map.get(SQSQueue.ATTR_MAXIMUM_MESSAGE_SIZE); String visibilityTimeout = map.get(SQSQueue.ATTR_VISIBILITY_TIMEOUT); String approximateNumberOfMessages = map.get(SQSQueue.ATTR_APPROXIMATE_NUMBER_OF_MESSAGES); String lastModifiedTimestamp = map.get(SQSQueue.ATTR_LAST_MODIFIED_TIMESTAMP); String queueArn = map.get(SQSQueue.ATTR_QUEUE_ARN); SQSQueue queue = new SQSQueue(url, Long.valueOf(approximateNumberOfMessagesDelayed), Long.valueOf(receiveMessageWaitTimeSeconds), Long.valueOf(createdTimestamp), Long.valueOf(delaySeconds), Long.valueOf(messageRetentionPeriod), Long.valueOf(maximumMessageSize), Long.valueOf(visibilityTimeout), Long.valueOf(approximateNumberOfMessages), Long.valueOf(lastModifiedTimestamp), queueArn); sqsQueueBuilder.putAll(regionName, queue); cnt++; } log.debug("Found {} queues in {}", cnt, regionName); } this.sqsQueues = sqsQueueBuilder.build(); /* * DynamoDB Tables */ for (Map.Entry<String, AmazonDynamoDBClient> clientPair : dynamoClients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonDynamoDBClient client = clientPair.getValue(); final DynamoDB dynamoDB = new DynamoDB(client); TableCollection<ListTablesResult> tables = dynamoDB.listTables(); Iterator<Table> iterator = tables.iterator(); log.info("Getting DynamoDB from {}", regionName); int cnt = 0; while (iterator.hasNext()) { Table table = iterator.next(); dynamoTableBuilder.putAll(regionName, new DynamoTable(table)); cnt++; } log.debug("Found {} dynamodbs in {}", cnt, regionName); } this.dynamoTables = dynamoTableBuilder.build(); /* * EC2 Instances */ for (Map.Entry<String, AmazonEC2Client> clientPair : ec2Clients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonEC2Client client = clientPair.getValue(); log.info("Getting EC2 reservations from {}", regionName); final List<Reservation> reservations = client.describeInstances().getReservations(); log.debug("Found {} reservations in {}", reservations.size(), regionName); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) ec2InstanceBuilder.putAll(regionName, new EC2Instance(instance)); } } this.ec2Instances = ec2InstanceBuilder.build(); /* * EC2 security groups */ log.info("Getting EC2 security groups"); final ImmutableMultimap.Builder<String, SecurityGroup> ec2SGbuilder = new ImmutableMultimap.Builder<String, SecurityGroup>(); for (Map.Entry<String, AmazonEC2Client> clientPair : ec2Clients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonEC2Client client = clientPair.getValue(); final List<SecurityGroup> securityGroups = client.describeSecurityGroups().getSecurityGroups(); log.debug("Found {} security groups in {}", securityGroups.size(), regionName); ec2SGbuilder.putAll(regionName, securityGroups); } this.ec2SGs = ec2SGbuilder.build(); /* * RDS Instances */ log.info("Getting RDS instances and clusters"); final ImmutableMultimap.Builder<String, RDSInstance> rdsBuilder = new ImmutableMultimap.Builder<String, RDSInstance>(); for (Map.Entry<String, AmazonRDSClient> clientPair : rdsClients.entrySet()) { final String regionName = clientPair.getKey(); final AmazonRDSClient client = clientPair.getValue(); final Map<String, DBCluster> instanceIdToCluster = new HashMap<>(); DescribeDBClustersRequest dbClustersRequest = new DescribeDBClustersRequest(); DescribeDBClustersResult clustersResult; log.info("Getting RDS clusters from {}", regionName); do { log.debug("Performing RDS request: {}", dbClustersRequest); clustersResult = client.describeDBClusters(dbClustersRequest); final List<DBCluster> clusters = clustersResult.getDBClusters(); log.debug("Found {} DB clusters", clusters.size()); for (DBCluster cluster : clusters) { for (DBClusterMember member : cluster.getDBClusterMembers()) { instanceIdToCluster.put(member.getDBInstanceIdentifier(), cluster); } } dbClustersRequest.setMarker(clustersResult.getMarker()); } while (clustersResult.getMarker() != null); DescribeDBInstancesRequest rdsRequest = new DescribeDBInstancesRequest(); DescribeDBInstancesResult result; log.info("Getting RDS instances from {}", regionName); do { log.debug("Performing RDS request: {}", rdsRequest); result = client.describeDBInstances(rdsRequest); final List<DBInstance> instances = result.getDBInstances(); log.debug("Found {} RDS instances", instances.size()); for (DBInstance instance : instances) { ListTagsForResourceRequest tagsRequest = new ListTagsForResourceRequest() .withResourceName(rdsARN(awsARNPartition, regionName, awsAccountNumber, instance)); ListTagsForResourceResult tagsResult = client.listTagsForResource(tagsRequest); List<String> snapshots = new ArrayList<>(); // Get snapshot for masters only. if (RDSInstance.checkIfMaster(instance, instanceIdToCluster.get(instance.getDBInstanceIdentifier()))) { if ("aurora".equals(instance.getEngine()) || "aurora-mysql".equals(instance.getEngine())) { DescribeDBClusterSnapshotsRequest snapshotsRequest = new DescribeDBClusterSnapshotsRequest() .withDBClusterIdentifier(instance.getDBClusterIdentifier()) .withSnapshotType("Automated"); DescribeDBClusterSnapshotsResult snapshotsResult = client.describeDBClusterSnapshots(snapshotsRequest); for (DBClusterSnapshot s : snapshotsResult.getDBClusterSnapshots()) { snapshots.add(s.getDBClusterSnapshotIdentifier()); } } else { DescribeDBSnapshotsRequest snapshotsRequest = new DescribeDBSnapshotsRequest() .withDBInstanceIdentifier(instance.getDBInstanceIdentifier()); DescribeDBSnapshotsResult snapshotsResult = client.describeDBSnapshots(snapshotsRequest); for (DBSnapshot s : snapshotsResult.getDBSnapshots()) { snapshots.add(s.getDBSnapshotIdentifier()); } } } rdsBuilder.putAll(regionName, new RDSInstance(instance, instanceIdToCluster.get(instance.getDBInstanceIdentifier()), tagsResult.getTagList(), snapshots)); } rdsRequest.setMarker(result.getMarker()); } while (result.getMarker() != null); } this.rdsInstances = rdsBuilder.build(); log.info("Done building AWS DB"); } public long getAgeInMs() { return System.currentTimeMillis() - getTimestamp(); } private String rdsARN(String partition, String regionName, String accountNumber, DBInstance instance) { return String.format( "arn:%s:rds:%s:%s:db:%s", partition, regionName, accountNumber, instance.getDBInstanceIdentifier() ); } private String elasticacheARN(String partition, String regionName, String accountNumber, CacheCluster cacheCluster) { return String.format( "arn:%s:elasticache:%s:%s:cluster:%s", partition, regionName, accountNumber, cacheCluster.getCacheClusterId() ); } private String elasticsearchARN(String partition, String regionName, String accountNumber, String domainName) { return String.format( "arn:%s:es:%s:%s:domain/%s", partition, regionName, accountNumber, domainName ); } }
9,390
0
Create_ds/reair/web-server/src/main/java/com/airbnb
Create_ds/reair/web-server/src/main/java/com/airbnb/reair/PageData.java
package com.airbnb.reair; import com.airbnb.reair.incremental.thrift.TReplicationJob; import com.airbnb.reair.incremental.thrift.TReplicationService; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import java.util.ArrayList; import java.util.List; public class PageData { // Number of jobs to fetch per Thrift call private static final int JOB_FETCH_SIZE = 100; private String host; private int port; private List<TReplicationJob> activeJobs = null; private List<TReplicationJob> retiredJobs = null; private long lag; public PageData(String host, int port) { this.host = host; this.port = port; } /** * Gets replication job data from the Thrift server. * * @throws TException if there's an error connecting to the Thrift server */ public void fetchData() throws TException { TTransport transport; transport = new TSocket(host, port); transport.open(); try { TProtocol protocol = new TBinaryProtocol(transport); TReplicationService.Client client = new TReplicationService.Client(protocol); retiredJobs = new ArrayList<>(); long marker = -1; while (true) { List<TReplicationJob> jobBatch = client.getRetiredJobs(marker, JOB_FETCH_SIZE); if (jobBatch.size() == 0) { break; } retiredJobs.addAll(jobBatch); // The marker should be the id of the last job marker = jobBatch.get(jobBatch.size() - 1).getId(); } // Get the active jobs activeJobs = new ArrayList<>(); marker = -1; while (true) { List<TReplicationJob> jobBatch = client.getActiveJobs(marker, JOB_FETCH_SIZE); if (jobBatch.size() == 0) { break; } activeJobs.addAll(jobBatch); // The marker should be the id of the last job marker = jobBatch.get(jobBatch.size() - 1).getId(); } // Get the lag lag = client.getLag(); } finally { transport.close(); } } public List<TReplicationJob> getActiveJobs() { return activeJobs; } public List<TReplicationJob> getRetiredJobs() { return retiredJobs; } public long getLag() { return lag; } }
9,391
0
Create_ds/reair/web-server/src/main/java/com/airbnb
Create_ds/reair/web-server/src/main/java/com/airbnb/reair/ThymeleafTemplateEngine.java
/* * Copyright 2015 - Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.airbnb.reair; import org.thymeleaf.context.Context; import org.thymeleaf.resourceresolver.ClassLoaderResourceResolver; import org.thymeleaf.templateresolver.TemplateResolver; import spark.ModelAndView; import spark.TemplateEngine; import java.util.Map; /** * Note: Pulled from Thymeleaf examples. */ /** * Defaults to the 'templates' directory under the resource path * * @author David Vaillant https://github.com/dvaillant */ public class ThymeleafTemplateEngine extends TemplateEngine { private static final String DEFAULT_PREFIX = "templates/"; private static final String DEFAULT_SUFFIX = ".html"; private static final String DEFAULT_TEMPLATE_MODE = "XHTML"; private static final long DEFAULT_CACHE_TTL_MS = 3600000L; private org.thymeleaf.TemplateEngine templateEngine; /** * Constructs a default thymeleaf template engine. Defaults prefix (template directory in resource * path) to templates/ and suffix to .html */ public ThymeleafTemplateEngine() { this(DEFAULT_PREFIX, DEFAULT_SUFFIX); } /** * Constructs a thymeleaf template engine with specified prefix and suffix * * @param prefix the prefix (template directory in resource path) * @param suffix the suffix (e.g. .html) */ public ThymeleafTemplateEngine(String prefix, String suffix) { TemplateResolver defaultTemplateResolver = createDefaultTemplateResolver(prefix, suffix); initialize(defaultTemplateResolver); } /** * Constructs a thymeleaf template engine with a proprietary initialize * * @param templateResolver the template resolver. */ public ThymeleafTemplateEngine(TemplateResolver templateResolver) { initialize(templateResolver); } /** * Initializes and sets the template resolver. */ private void initialize(TemplateResolver templateResolver) { templateEngine = new org.thymeleaf.TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); } @Override @SuppressWarnings("unchecked") public String render(ModelAndView modelAndView) { Object model = modelAndView.getModel(); if (model instanceof Map) { Map<String, ?> modelMap = (Map<String, ?>) model; Context context = new Context(); context.setVariables(modelMap); return templateEngine.process(modelAndView.getViewName(), context); } else { throw new IllegalArgumentException("modelAndView.getModel() must return a java.util.Map"); } } private static TemplateResolver createDefaultTemplateResolver(String prefix, String suffix) { TemplateResolver defaultTemplateResolver = new TemplateResolver(); defaultTemplateResolver.setTemplateMode(DEFAULT_TEMPLATE_MODE); defaultTemplateResolver.setPrefix(prefix != null ? prefix : DEFAULT_PREFIX); defaultTemplateResolver.setSuffix(suffix != null ? suffix : DEFAULT_SUFFIX); defaultTemplateResolver.setCacheTTLMs(DEFAULT_CACHE_TTL_MS); defaultTemplateResolver.setResourceResolver(new ClassLoaderResourceResolver()); return defaultTemplateResolver; } }
9,392
0
Create_ds/reair/web-server/src/main/java/com/airbnb
Create_ds/reair/web-server/src/main/java/com/airbnb/reair/DateUtils.java
package com.airbnb.reair; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class DateUtils { /** * Converts the unix time into an ISO8601 time. * * @param time unix time to convert * @return a String representing the specified unix time */ public String convertToIso8601(long time) { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); return df.format(time); } }
9,393
0
Create_ds/reair/web-server/src/main/java/com/airbnb
Create_ds/reair/web-server/src/main/java/com/airbnb/reair/WebServer.java
package com.airbnb.reair; import static spark.Spark.get; import static spark.Spark.port; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.ModelAndView; import java.util.HashMap; import java.util.Map; public class WebServer { private static Logger LOG = LoggerFactory.getLogger(WebServer.class); /** * TODO. Warning suppression needed for the OptionBuilder API * * @param argv TODO * * @throws Exception TODO */ @SuppressWarnings("static-access") public static void main(final String[] argv) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("thrift-host") .withDescription("Host name for the thrift service").hasArg().withArgName("HOST").create()); options.addOption(OptionBuilder.withLongOpt("thrift-port") .withDescription("Port for the thrift service").hasArg().withArgName("PORT").create()); options.addOption(OptionBuilder.withLongOpt("http-port") .withDescription("Port for the HTTP service").hasArg().withArgName("PORT").create()); CommandLineParser parser = new BasicParser(); CommandLine cl = parser.parse(options, argv); String thriftHost = "localhost"; int thriftPort = 9996; int httpPort = 8080; if (cl.hasOption("thrift-host")) { thriftHost = cl.getOptionValue("thrift-host"); LOG.info("thriftHost=" + thriftHost); } if (cl.hasOption("thrift-port")) { thriftPort = Integer.valueOf(cl.getOptionValue("thrift-port")); LOG.info("thriftPort=" + thriftPort); } if (cl.hasOption("http-port")) { httpPort = Integer.valueOf(cl.getOptionValue("http-port")); LOG.info("httpPort=" + httpPort); } port(httpPort); final String finalThriftHost = thriftHost; final int finalThriftPort = thriftPort; LOG.info(String.format("Connecting to thrift://%s:%s and " + "serving HTTP on %s", finalThriftHost, finalThriftPort, httpPort)); get("/jobs", (request, response) -> { PageData pd = new PageData(finalThriftHost, finalThriftPort); boolean dataFetchSuccessful = false; try { pd.fetchData(); dataFetchSuccessful = true; } catch (TException e) { LOG.error("Error while fetching data!", e); } Map<String, Object> model = new HashMap<>(); model.put("host", finalThriftHost); model.put("port", finalThriftPort); model.put("data_fetch_successful", dataFetchSuccessful); model.put("lag_in_minutes", pd.getLag() / 1000 / 60); model.put("active_jobs", pd.getActiveJobs()); model.put("retired_jobs", pd.getRetiredJobs()); model.put("date_utils", new DateUtils()); return new ModelAndView(model, "jobs"); } , new ThymeleafTemplateEngine()); } }
9,394
0
Create_ds/reair/utils/src/main/java/com/airbnb/reair
Create_ds/reair/utils/src/main/java/com/airbnb/reair/multiprocessing/LockSet.java
package com.airbnb.reair.multiprocessing; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class LockSet { private Set<Lock> allLocks; private Set<String> exclusiveLockNames; private Set<String> sharedLockNames; /** * TODO. */ public LockSet() { allLocks = new HashSet<>(); exclusiveLockNames = new HashSet<>(); sharedLockNames = new HashSet<>(); } /** * TODO. * * @param lock TODO */ public void add(Lock lock) { allLocks.add(lock); if (lock.getType() == Lock.Type.SHARED) { sharedLockNames.add(lock.getName()); } else if (lock.getType() == Lock.Type.EXCLUSIVE) { exclusiveLockNames.add(lock.getName()); } else { throw new RuntimeException("Unhandled lock type " + lock.getType()); } } /** * TODO. * * @param lockName TODO * @return TODO */ public Lock.Type getType(String lockName) { if (sharedLockNames.contains(lockName)) { return Lock.Type.SHARED; } else if (exclusiveLockNames.contains(lockName)) { return Lock.Type.EXCLUSIVE; } else { throw new RuntimeException("Unknown lock name " + lockName); } } public boolean contains(String lockName) { return exclusiveLockNames.contains(lockName) || sharedLockNames.contains(lockName); } public Set<String> getExclusiveLocks() { return Collections.unmodifiableSet(exclusiveLockNames); } public Set<String> getSharedLocks() { return Collections.unmodifiableSet(sharedLockNames); } @Override public String toString() { return allLocks.toString(); } }
9,395
0
Create_ds/reair/utils/src/main/java/com/airbnb/reair
Create_ds/reair/utils/src/main/java/com/airbnb/reair/multiprocessing/ParallelJobExecutor.java
package com.airbnb.reair.multiprocessing; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Accepts a bunch of jobs, executes them in parallel while observing the locks that each jobs * needs. */ public class ParallelJobExecutor { private static final Log LOG = LogFactory.getLog(ParallelJobExecutor.class); private BlockingQueue<Job> jobsToRun; private JobDagManager dagManager; private int numWorkers = 0; private Set<Worker> workers = new HashSet<>(); // Vars for counting the number of jobs // Lock to hold when incrementing either count private Lock countLock = new ReentrantLock(); // Condition variable to signal when submitted and done counts are equal private Condition equalCountCv = countLock.newCondition(); private int submittedJobCount = 0; private int doneJobCount = 0; private String workerName = "Worker"; /** * Constructor for a job executor that run jobs in multiple threads. * * @param numWorkers the number of threads (i.e. workers) to create */ public ParallelJobExecutor(int numWorkers) { dagManager = new JobDagManager(); jobsToRun = new LinkedBlockingQueue<Job>(); this.numWorkers = numWorkers; } /** * Constructor for a job executor that run jobs in multiple threads with the option to give a * prefix to the workers' thread names. * * @param workerName a prefix use for the worker thread name * @param numWorkers the number of threads (i.e. workers) to create */ public ParallelJobExecutor(String workerName, int numWorkers) { this.workerName = workerName; dagManager = new JobDagManager(); jobsToRun = new LinkedBlockingQueue<Job>(); this.numWorkers = numWorkers; } /** * Add the given job to run. It will attempt to acquire the locks needed by the job, but if not * possible, it will wait until the jobs that hold the required locks give them up. With this * requirement in mind, jobs will be executed in the order that they are added. * * @param job the job that should be run */ public synchronized void add(Job job) { boolean canRunImmediately = dagManager.addJob(job); if (canRunImmediately) { LOG.debug("Job " + job + " is ready to run."); jobsToRun.add(job); } incrementSubmittedJobCount(); } /** * Should be called by the workers to indicate that a job has finished running. This removes the * job from the DAG so that other jobs that depended on the finished job can now be run. * * @param doneJob the job that is done running */ public synchronized void notifyDone(Job doneJob) { LOG.debug("Done notification received for " + doneJob); Set<Job> newReadyJobs = dagManager.removeJob(doneJob); for (Job jobToRun : newReadyJobs) { LOG.debug("Job " + jobToRun + " is ready to run."); jobsToRun.add(jobToRun); } incrementDoneJobCount(); countLock.lock(); try { LOG.debug("Submitted jobs: " + submittedJobCount + " Pending jobs: " + (submittedJobCount - doneJobCount) + " Completed jobs: " + doneJobCount); } finally { countLock.unlock(); } } /** * This is used with incrementJobDoneCount() to know when all the jobs submitted to the executor * has finished. */ private void incrementSubmittedJobCount() { countLock.lock(); try { submittedJobCount++; } finally { countLock.unlock(); } } private void incrementDoneJobCount() { countLock.lock(); try { doneJobCount++; if (doneJobCount == submittedJobCount) { equalCountCv.signal(); } } finally { countLock.unlock(); } } /** * Get the number of jobs that are not done. * * @return the number of jobs that are not done */ public long getNotDoneJobCount() { countLock.lock(); try { return submittedJobCount - doneJobCount; } finally { countLock.unlock(); } } /** * Wait for the number of finished jobs to equal to the number of submitted jobs. */ public void waitUntilDone() { countLock.lock(); try { equalCountCv.await(); } catch (InterruptedException e) { throw new RuntimeException("Shouldn't happen!"); } finally { countLock.unlock(); } } /** * Kick off the worker threads that run a job. */ public synchronized void start() { if (workers.size() > 0) { throw new RuntimeException("Start called while there are workers" + " still running"); } for (int i = 0; i < numWorkers; i++) { Worker worker = new Worker<Job>(workerName, jobsToRun, this); workers.add(worker); } for (Worker w : workers) { try { Thread.sleep(100); } catch (Exception e) { LOG.error(e); } w.start(); } } /** * Interrupt the threads that are currently working on the jobs and wait for them to stop. * * @throws InterruptedException if interrupted while waiting for threads to finish */ public synchronized void stop() throws InterruptedException { for (Worker w : workers) { w.interrupt(); } for (Worker w : workers) { w.join(); } // Do this after interrupting? Think about case when a worker takes an // item from the queue and is then interrupted. for (Worker w : workers) { if (w.getJob() != null) { jobsToRun.add(w.getJob()); } } workers.clear(); } }
9,396
0
Create_ds/reair/utils/src/main/java/com/airbnb/reair
Create_ds/reair/utils/src/main/java/com/airbnb/reair/multiprocessing/Job.java
package com.airbnb.reair.multiprocessing; import java.util.HashSet; import java.util.Set; /** * A Job is anything that needs to run, along with a set of pre-requisites. In this case, the * prerequisites are represented as a set of shared/exclusive locks. */ public abstract class Job { /** * Before the Job runs, it needs to acquire a set of shared or exclusive locks. Multiple jobs can * have the same shared lock, but only one job can have an exclusive one. */ public enum LockType { SHARED, EXCLUSIVE } // A list of jobs in progress that need to finish before this job can run. private Set<Job> parentJobs = new HashSet<>(); // A set of jobs that are waiting for this job to finish before running private Set<Job> childJobs = new HashSet<>(); // Method that gets called when this job should run public abstract int run(); // // A set of locks that the job needs to get before running // abstract public Set<String> getRequiredExclusiveLocks(); // // A set of shared locks that the job needs to get before running // abstract public Set<String> getRequiredSharedLocks(); /** * Add the specified job as a parent job. * * @param parentJob the parent job */ public void addParent(Job parentJob) { parentJobs.add(parentJob); } /** * Add the specified job as a child job. * * @param childJob the child job */ public void addChild(Job childJob) { childJobs.add(childJob); } /** * @return a set of Jobs that need to finish before this job can run. */ public Set<Job> getParentJobs() { return parentJobs; } /** * @return a set of jobs that require this job to finish before it runs. */ public Set<Job> getChildJobs() { return childJobs; } /** * Removes a parent job from this job's set of parent jobs. This should be called when the parent * job has finished running. * * @param parentJob the parent job */ public void removeParentJob(Job parentJob) { if (!parentJobs.contains(parentJob)) { throw new RuntimeException("Tried to remove job " + parentJob + " when it wasn't a parent"); } boolean removed = parentJobs.remove(parentJob); if (!removed) { throw new RuntimeException("Shouldn't happen!"); } } /** * Removes a child job from this job's set of child jobs. This should be called when the this job * has finished running and is being removed from the DAG. * * @param childJob the child job */ public void removeChildJob(Job childJob) { if (!childJobs.contains(childJob)) { throw new RuntimeException("Tried to remove job " + childJob + " when it wasn't a child"); } boolean removed = childJobs.remove(childJob); if (!removed) { throw new RuntimeException("Shouldn't happen!"); } } /** * To handle concurrency issues, jobs should specify a set of locks so that two conflicting jobs * do not run at the same time. * * @return a set of locks that this job should acquire before running */ public abstract LockSet getRequiredLocks(); }
9,397
0
Create_ds/reair/utils/src/main/java/com/airbnb/reair
Create_ds/reair/utils/src/main/java/com/airbnb/reair/multiprocessing/Worker.java
package com.airbnb.reair.multiprocessing; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.concurrent.BlockingQueue; /** * Executes a job in a thread. The job is required to return a return code of 0 or else an exception * will be thrown. */ public class Worker<T extends Job> extends Thread { private static final Log LOG = LogFactory.getLog(Worker.class); private static int nextWorkerId = 0; private int workerId; private BlockingQueue<T> inputQueue; private ParallelJobExecutor parallelJobExecutor; private Job job = null; /** * Constructor for a worker that gets and runs jobs from the input queue. * * @param inputQueue the queue to get jobs from * @param parallelJobExecutor the executor to notify when the job is done */ public Worker(BlockingQueue<T> inputQueue, ParallelJobExecutor parallelJobExecutor) { this.inputQueue = inputQueue; this.workerId = nextWorkerId++; this.parallelJobExecutor = parallelJobExecutor; setName(Worker.class.getSimpleName() + "-" + workerId); setDaemon(true); } /** * Constructor for a worker that gets and runs jobs from the input queue with the option to * specify a prefix for the worker thread name. * * @param workerNamePrefix prefix for the thread name * @param inputQueue the queue to get jobs from * @param parallelJobExecutor the executor to notify when the job is done */ public Worker( String workerNamePrefix, BlockingQueue<T> inputQueue, ParallelJobExecutor parallelJobExecutor) { this.inputQueue = inputQueue; this.workerId = nextWorkerId++; this.parallelJobExecutor = parallelJobExecutor; setName(workerNamePrefix + "-" + workerId); setDaemon(true); } @Override public void run() { try { while (true) { if (job == null) { LOG.debug("Waiting for a job"); job = inputQueue.take(); } else { LOG.debug("Using existing job"); } LOG.debug("**** Running job: " + job + " ****"); int ret = job.run(); if (ret != 0) { LOG.error("Error running job " + job + " return code: " + ret); throw new RuntimeException(String.format("Job %s returned %s", job, ret)); } LOG.debug("**** Done running job: " + job + " ****"); parallelJobExecutor.notifyDone(job); job = null; } } catch (InterruptedException e) { LOG.debug("Got interrupted"); } // Any other exception should cause the process to exit via uncaught exception handler } public Job getJob() { return job; } }
9,398
0
Create_ds/reair/utils/src/main/java/com/airbnb/reair
Create_ds/reair/utils/src/main/java/com/airbnb/reair/multiprocessing/JobDagManager.java
package com.airbnb.reair.multiprocessing; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Given jobs (that need to get specific locks before running), this class helps create and manage a * DAG of jobs. For example, job 1 needs lock a, job 2 needs lock b and job 3 needs lock a and lock * b. The DAG would look like: * * <p>(job 1, job 2) -> job 3 * * <p>job 1 and job 2 would run in parallel, and once those 2 are done, job 3 can run. */ public class JobDagManager { private static final Log LOG = LogFactory.getLog(JobDagManager.class); // Maps from a lock to the jobs holding the lock Map<String, HashSet<Job>> sharedLocksHeld = new HashMap<>(); Map<String, Job> exclusiveLocksHeld = new HashMap<>(); // A map of a lock to the jobs needing the resource, in the order that they // were submitted. Map<String, ArrayList<Job>> lockToJobsNeedingLock = new HashMap<>(); Set<Job> jobsWithAllRequiredLocks = new HashSet<>(); private boolean canGetAllLocks(Job job) { LockSet lockSet = job.getRequiredLocks(); for (String exclusiveLock : lockSet.getExclusiveLocks()) { if (exclusiveLocksHeld.containsKey(exclusiveLock)) { return false; } if (lockToJobsNeedingLock.containsKey(exclusiveLock)) { for (Job j : lockToJobsNeedingLock.get(exclusiveLock)) { if (j.getRequiredLocks().contains(exclusiveLock)) { return false; } } } } for (String sharedLock : lockSet.getSharedLocks()) { if (exclusiveLocksHeld.containsKey(sharedLock)) { return false; } if (lockToJobsNeedingLock.containsKey(sharedLock)) { for (Job j : lockToJobsNeedingLock.get(sharedLock)) { if (j.getRequiredLocks().getExclusiveLocks().contains(sharedLock)) { return false; } } } } return true; } /** * To keep track of what jobs need what lock, update the internal data structures to indicate that * the supplied job needs the specified lock before running. * * @param lock the lock that the job needs * @param job the job that has the lock requirement */ private void addLockToJobsNeedingLock(String lock, Job job) { ArrayList<Job> jobs = lockToJobsNeedingLock.get(lock); if (jobs == null) { jobs = new ArrayList<>(); lockToJobsNeedingLock.put(lock, jobs); } jobs.add(job); } /** * Mark the lock as not being needed by the specified job in the internal data structures. * * @param lock the lock that is no longer needed * @param job the job that no longer needs the lock * @param shouldBeAtHead Whether the job should have been at the head of the queue for the log. * Note that the job at the head of queue represents the job that has the * lock. This is used as a sanity check only. */ private void removeLockToJobsNeedingLock(String lock, Job job, boolean shouldBeAtHead) { ArrayList<Job> jobs = lockToJobsNeedingLock.get(lock); if (shouldBeAtHead && jobs.get(0) != job) { throw new RuntimeException("Tried to remove " + job + " but it " + "wasn't at the head of the list for lock " + lock + "! List is: " + jobs); } boolean removed = jobs.remove(job); if (!removed) { throw new RuntimeException("Didn't remove job " + job + " from list " + jobs); } } private void grantExclusiveLock(String lock, Job job) { if (exclusiveLocksHeld.containsKey(lock)) { throw new RuntimeException("Tried to give exclusive lock to " + job + " when it was held by " + exclusiveLocksHeld.get(lock)); } exclusiveLocksHeld.put(lock, job); } private void grantSharedLock(String lock, Job job) { if (exclusiveLocksHeld.containsKey(lock)) { throw new RuntimeException("Tried to give shared lock " + lock + " to " + job + " when an exclusive lock was held by " + exclusiveLocksHeld.get(lock)); } HashSet<Job> jobsHoldingSharedLock = sharedLocksHeld.get(lock); if (jobsHoldingSharedLock == null) { jobsHoldingSharedLock = new HashSet<>(); sharedLocksHeld.put(lock, jobsHoldingSharedLock); } jobsHoldingSharedLock.add(job); } /** * Add the job to run. * * @param jobToAdd the job to add * @return true if the job that was added can be run immediately. */ public synchronized boolean addJob(Job jobToAdd) { LOG.debug("Adding job " + jobToAdd + " requiring locks " + jobToAdd.getRequiredLocks()); LockSet lockSet = jobToAdd.getRequiredLocks(); // See if it can get all the locks if (canGetAllLocks(jobToAdd)) { // It can get the locks for (String exclusiveLock : lockSet.getExclusiveLocks()) { grantExclusiveLock(exclusiveLock, jobToAdd); addLockToJobsNeedingLock(exclusiveLock, jobToAdd); } for (String sharedLock : lockSet.getSharedLocks()) { grantSharedLock(sharedLock, jobToAdd); addLockToJobsNeedingLock(sharedLock, jobToAdd); } jobsWithAllRequiredLocks.add(jobToAdd); return true; } // Otherwise, it can't get all the locks. Find all the jobs that it // depends on. Parents is a set of jobs that need to complete before // this job can run. Set<Job> parents = new HashSet<>(); // If this job needs an exclusive lock, it needs to wait for the last // jobs to require the same shared lock, or the job that last required // the exclusive lock. for (String exclusiveLockToGet : lockSet.getExclusiveLocks()) { // LOG.debug("Lock " + lockToGet + " is needed by " + // lockToJobsNeedingLock.get(lockToGet)); if (!lockToJobsNeedingLock.containsKey(exclusiveLockToGet)) { // No need to do anything if no job is waiting for it continue; } List<Job> jobs = lockToJobsNeedingLock.get(exclusiveLockToGet); for (int i = jobs.size() - 1; i >= 0; i--) { Job otherJob = jobs.get(i); // The job that needs the same named lock could need it as // a shared lock or an exclusive lock Lock.Type requiredLockType = otherJob.getRequiredLocks().getType(exclusiveLockToGet); if (requiredLockType == Lock.Type.EXCLUSIVE) { parents.add(otherJob); break; } else if (requiredLockType == Lock.Type.SHARED) { parents.add(otherJob); // Don't break as it should depend on all the jobs needing // the same shared lock } } } for (String lockToGet : lockSet.getSharedLocks()) { if (!lockToJobsNeedingLock.containsKey(lockToGet)) { continue; } List<Job> jobs = lockToJobsNeedingLock.get(lockToGet); for (int i = jobs.size() - 1; i >= 0; i--) { Job otherJob = jobs.get(i); Lock.Type requiredLockType = otherJob.getRequiredLocks().getType(lockToGet); // A shared lock doesn't depend on other shared locks if (requiredLockType == Lock.Type.EXCLUSIVE) { parents.add(otherJob); break; } } } if (parents.size() == 0) { throw new RuntimeException("Shouldn't happen!"); } // Now that you know the parents of the job to add, setup all parent // child relationships for (Job parent : parents) { jobToAdd.addParent(parent); parent.addChild(jobToAdd); } // Record all the locks that it needs for (String lock : lockSet.getExclusiveLocks()) { addLockToJobsNeedingLock(lock, jobToAdd); } for (String lock : lockSet.getSharedLocks()) { addLockToJobsNeedingLock(lock, jobToAdd); } LOG.debug("Added job " + jobToAdd + " with parents " + parents); return false; } private boolean hasExclusiveLock(String exclusiveLock, Job job) { return exclusiveLocksHeld.containsKey(exclusiveLock) && exclusiveLocksHeld.get(exclusiveLock) == job; } private boolean hasSharedLock(String sharedLock, Job job) { return sharedLocksHeld.containsKey(sharedLock) && sharedLocksHeld.get(sharedLock).contains(job); } private void removeExclusiveLock(String exclusiveLock, Job job) { if (!hasExclusiveLock(exclusiveLock, job)) { throw new RuntimeException("Job " + job + " was supposed to " + "have exclusive lock " + exclusiveLock + " but it didn't!"); } Job removedJob = exclusiveLocksHeld.remove(exclusiveLock); if (removedJob != job) { throw new RuntimeException("Shouldn't happen!"); } } private void removeSharedLock(String sharedLock, Job job) { if (!hasSharedLock(sharedLock, job)) { throw new RuntimeException("Job " + job + " was supposed to " + "have shared lock " + sharedLock + " but it didn't!"); } Set<Job> jobsWithSharedLock = sharedLocksHeld.get(sharedLock); boolean removed = jobsWithSharedLock.remove(job); if (!removed) { throw new RuntimeException("Shouldn't happen!"); } if (jobsWithSharedLock.size() == 0) { Set<Job> removedSet = sharedLocksHeld.remove(sharedLock); if (removedSet != jobsWithSharedLock) { throw new RuntimeException("Shouldn't happen!"); } } } /** * * @param job The job to remove from the DAG * @return A set of jobs that can now run since the specified job was removed. */ public synchronized Set<Job> removeJob(Job job) { if (!jobsWithAllRequiredLocks.contains(job)) { throw new RuntimeException("Trying to remove job without " + "having all the locks"); } LockSet lockSet = job.getRequiredLocks(); // Free up locks for (String exclusiveLock : lockSet.getExclusiveLocks()) { removeExclusiveLock(exclusiveLock, job); removeLockToJobsNeedingLock(exclusiveLock, job, true); } for (String sharedLock : lockSet.getSharedLocks()) { removeSharedLock(sharedLock, job); removeLockToJobsNeedingLock(sharedLock, job, false); } // Make a copy since we'll be removing from it Set<Job> childJobs = new HashSet<>(job.getChildJobs()); // Remove self as a parent of the children for (Job child : childJobs) { child.removeParentJob(job); } // Remove children from self for (Job child : childJobs) { job.removeChildJob(child); } // If any of the child jobs have no parent jobs, that means they should // be run. Set<Job> newJobsWithRequiredLocks = new HashSet<>(); for (Job child : childJobs) { LOG.debug("Job " + child + " has parents " + child.getParentJobs()); if (child.getParentJobs().size() == 0) { LockSet childLockSet = child.getRequiredLocks(); // Job is ready to run for (String lock : childLockSet.getExclusiveLocks()) { grantExclusiveLock(lock, child); } for (String lock : childLockSet.getSharedLocks()) { grantSharedLock(lock, child); } jobsWithAllRequiredLocks.add(child); newJobsWithRequiredLocks.add(child); } } return newJobsWithRequiredLocks; } }
9,399