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/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ConversionUtil.java | package com.airbnb.android.react.navigation;
import android.os.Bundle;
import android.util.Log;
import com.facebook.react.bridge.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unused")
final class ConversionUtil {
private static final String TAG = ConversionUtil.class.getSimpleName();
private ConversionUtil() {
}
static final ReadableMap EMPTY_MAP = new WritableNativeMap();
static Map<String, Object> toMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Object> result = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
result.put(key, null);
break;
case Boolean:
result.put(key, readableMap.getBoolean(key));
break;
case Number:
try {
result.put(key, readableMap.getInt(key));
} catch (Exception e) {
result.put(key, readableMap.getDouble(key));
}
break;
case String:
result.put(key, readableMap.getString(key));
break;
case Map:
result.put(key, toMap(readableMap.getMap(key)));
break;
case Array:
result.put(key, toArray(readableMap.getArray(key)));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
/** Converts the provided {@code readableMap} into an object of the provided {@code targetType} */
static <T> T toType(ObjectMapper objectMapper, ReadableMap readableMap, Class<T>
targetType) {
ObjectNode jsonNode = toJsonObject(readableMap);
ObjectReader objectReader = JacksonUtils.readerForType(objectMapper, targetType);
//noinspection OverlyBroadCatchBlock
try {
return objectReader.readValue(jsonNode);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Converts a {@link ReadableMap} into an Json {@link ObjectNode} */
static ObjectNode toJsonObject(ReadableMap readableMap) {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode result = nodeFactory.objectNode();
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
result.putNull(key);
break;
case Boolean:
result.put(key, readableMap.getBoolean(key));
break;
case Number:
result.put(key, readableMap.getDouble(key));
break;
case String:
result.put(key, readableMap.getString(key));
break;
case Map:
result.set(key, toJsonObject(readableMap.getMap(key)));
break;
case Array:
result.set(key, toJsonArray(readableMap.getArray(key)));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
/** Converts a {@link ReadableArray} into an Json {@link ArrayNode} */
static ArrayNode toJsonArray(ReadableArray readableArray) {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ArrayNode result = nodeFactory.arrayNode();
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Null:
result.addNull();
break;
case Boolean:
result.add(readableArray.getBoolean(i));
break;
case Number:
result.add(readableArray.getDouble(i));
break;
case String:
result.add(readableArray.getString(i));
break;
case Map:
result.add(toJsonObject(readableArray.getMap(i)));
break;
case Array:
result.add(toJsonArray(readableArray.getArray(i)));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static Bundle toBundle(ReadableMap readableMap) {
Bundle result = new Bundle();
if (readableMap == null) {
return result;
}
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
result.putString(key, null);
break;
case Boolean:
result.putBoolean(key, readableMap.getBoolean(key));
break;
case Number:
try {
// NOTE(lmr):
// this is a bit of a hack right now to prefer integer types in cases where the
// number can be a valid int,
// and fall back to doubles in every other case. Long-term we will figure out a
// reliable way to add this meta
// data.
result.putInt(key, readableMap.getInt(key));
} catch (Exception e) {
result.putDouble(key, readableMap.getDouble(key));
}
break;
case String:
result.putString(key, readableMap.getString(key));
break;
case Map:
result.putBundle(key, toBundle(readableMap.getMap(key)));
break;
case Array:
// NOTE(lmr): This is a limitation of the Bundle class. Wonder if there is a clean way
// for us
// to get around it. For now i'm just skipping...
Log.e(TAG, "Cannot put arrays of objects into bundles. Failed on: " + key + ".");
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
static void merge(WritableMap target, ReadableMap map) {
ReadableMapKeySetIterator iterator = map.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = map.getType(key);
switch (type) {
case Null:
target.putNull(key);
break;
case Boolean:
target.putBoolean(key, map.getBoolean(key));
break;
case Number:
try {
target.putInt(key, map.getInt(key));
} catch (Exception e) {
target.putDouble(key, map.getDouble(key));
}
break;
case String:
target.putString(key, map.getString(key));
break;
case Map:
target.putMap(key, cloneMap(map.getMap(key)));
break;
case Array:
target.putArray(key, cloneArray(map.getArray(key)));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
}
static WritableMap cloneMap(ReadableMap map) {
WritableNativeMap target = new WritableNativeMap();
merge(target, map);
return target;
}
static WritableArray cloneArray(ReadableArray source) {
WritableNativeArray result = new WritableNativeArray();
for (int i = 0; i < source.size(); i++) {
ReadableType indexType = source.getType(i);
switch (indexType) {
case Null:
result.pushNull();
break;
case Boolean:
result.pushBoolean(source.getBoolean(i));
break;
case Number:
try {
result.pushInt(source.getInt(i));
} catch (Exception e) {
result.pushDouble(source.getDouble(i));
}
break;
case String:
result.pushString(source.getString(i));
break;
case Map:
result.pushMap(cloneMap(source.getMap(i)));
break;
case Array:
result.pushArray(cloneArray(source.getArray(i)));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static ReadableMap combine(ReadableMap a, ReadableMap b) {
WritableMap result = new WritableNativeMap();
merge(result, a);
merge(result, b);
return result;
}
static Map<String, String> toStringMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, String> result = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
result.put(key, null);
break;
case String:
result.put(key, readableMap.getString(key));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
static Map<String, Double> toDoubleMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Double> result = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Number:
result.put(key, readableMap.getDouble(key));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
static Map<String, Integer> toIntegerMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Integer> result = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Number:
result.put(key, readableMap.getInt(key));
break;
default:
Log.e(TAG, "Could not convert object with key: " + key + ".");
}
}
return result;
}
static List<Object> toArray(ReadableArray readableArray) {
List<Object> result = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Null:
result.add(i, null);
break;
case Boolean:
result.add(i, readableArray.getBoolean(i));
break;
case Number:
result.add(i, readableArray.getDouble(i));
break;
case String:
result.add(i, readableArray.getString(i));
break;
case Map:
result.add(i, toMap(readableArray.getMap(i)));
break;
case Array:
result.add(i, toArray(readableArray.getArray(i)));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static List<String> toStringArray(ReadableArray readableArray) {
List<String> result = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Null:
result.add(i, null);
break;
case String:
result.add(i, readableArray.getString(i));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static List<Double> toDoubleArray(ReadableArray readableArray) {
List<Double> result = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Number:
result.add(i, readableArray.getDouble(i));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static List<Integer> toIntArray(ReadableArray readableArray) {
List<Integer> result = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Number:
result.add(i, readableArray.getInt(i));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static List<Map<String, Object>> toMapArray(ReadableArray readableArray) {
List<Map<String, Object>> result = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Map:
result.add(i, toMap(readableArray.getMap(i)));
break;
default:
Log.e(TAG, "Could not convert object at index " + i + ".");
}
}
return result;
}
static WritableMap toWritableMap(Map<String, Object> map) {
WritableNativeMap result = new WritableNativeMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value == null) {
result.putNull(key);
} else if (value instanceof Map) {
//noinspection unchecked,rawtypes
result.putMap(key, toWritableMap((Map) value));
} else if (value instanceof List) {
//noinspection unchecked,rawtypes
result.putArray(key, toWritableArray((List) value));
} else if (value instanceof Boolean) {
result.putBoolean(key, (Boolean) value);
} else if (value instanceof Integer) {
result.putInt(key, (Integer) value);
} else if (value instanceof String) {
result.putString(key, (String) value);
} else if (value instanceof Double) {
result.putDouble(key, (Double) value);
} else {
Log.e(TAG, "Could not convert object " + value.toString());
}
}
return result;
}
private static WritableArray toWritableArray(List<Object> array) {
WritableNativeArray result = new WritableNativeArray();
for (Object value : array) {
if (value == null) {
result.pushNull();
} else if (value instanceof Map) {
//noinspection unchecked,rawtypes
result.pushMap(toWritableMap((Map) value));
} else if (value instanceof List) {
//noinspection unchecked,rawtypes
result.pushArray(toWritableArray((List) value));
} else if (value instanceof Boolean) {
result.pushBoolean((Boolean) value);
} else if (value instanceof Integer) {
result.pushInt((Integer) value);
} else if (value instanceof String) {
result.pushString((String) value);
} else if (value instanceof Double) {
result.pushDouble((Double) value);
} else {
Log.e(TAG, "Could not convert object " + value.toString());
}
}
return result;
}
}
| 900 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/TabBarView.java | package com.airbnb.android.react.navigation;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.react.bridge.ReadableMap;
/**
* This view is used as a data structure to hold configuration for a TabBar in a
* ReactNativeTabActivity, and doesn't actually render anything that will be visible
* to the user.
*/
public class TabBarView extends ViewGroup {
private ReadableMap prevConfig = ConversionUtil.EMPTY_MAP;
private ReadableMap renderedConfig = ConversionUtil.EMPTY_MAP;
public TabBarView(Context context, AttributeSet attrs) {
super(context, attrs);
setVisibility(View.GONE);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
public void setConfig(ReadableMap config) {
this.prevConfig = this.renderedConfig;
this.renderedConfig = config;
}
public ReadableMap getConfig() {
return renderedConfig;
}
}
| 901 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ActivityUtils.java | package com.airbnb.android.react.navigation;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
final class ActivityUtils {
private ActivityUtils() {
}
static boolean hasActivityStopped(Activity activity) {
return activity.getWindow() == null || activity.isFinishing();
}
private static int getAndroidDimension(Context context, String resourceIdName) {
Resources resources = context.getResources();
try {
int id = resources.getIdentifier(resourceIdName, "dimen", "android");
return id > 0 ? resources.getDimensionPixelSize(id) : 0;
} catch (Resources.NotFoundException exception) {
return 0;
}
}
private static int getStatusBarHeight(Activity activity) {
Rect rectangle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
if (rectangle.top > 0) {
return rectangle.top;
}
return getAndroidDimension(activity, "status_bar_height");
}
/**
* Returns the height of the standard status bar and action bar height. Should be called AFTER the
* initial view layout pass (e.g. wrapped in a post() call).
*/
static int getStatusBarActionBarHeight(AppCompatActivity activity) {
return getStatusBarHeight(activity) + activity.getSupportActionBar().getHeight();
}
static boolean hasTranslucentStatusBar(Window window) {
if (AndroidVersion.isAtLeastKitKat()) {
int flags = window.getAttributes().flags;
return (flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) ==
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
}
return false;
}
static int getNavBarHeight(Context context) {
if (ActivityUtils.isPortraitMode(context)) {
return getAndroidDimension(context, "navigation_bar_height");
}
return getAndroidDimension(context, "navigation_bar_height_landscape");
}
private static boolean isPortraitMode(Context context) {
Point point = ViewUtils.getScreenSize(context);
return point.x < point.y;
}
static boolean isLandscapeMode(Context context) {
return !isPortraitMode(context);
}
}
| 902 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ExtendableBundleBuilder.java | package com.airbnb.android.react.navigation;
import android.os.Bundle;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.ArrayList;
/**
* This class can be extended to provide a bundler builder as part of a parent class.
*
* @param <T> The class that is extending this like: class Foo extends ExtendableBundleBuilder<Foo>
* which allows the builder pattern via returning the parent class for each bundle
* operation.
*/
@SuppressWarnings("unchecked")
abstract class ExtendableBundleBuilder<T extends ExtendableBundleBuilder<?>> {
private final Bundle bundle = new Bundle();
protected ExtendableBundleBuilder() {
}
public T putBoolean(String key, boolean value) {
bundle.putBoolean(key, value);
return (T) this;
}
public T putByte(String key, byte value) {
bundle.putByte(key, value);
return (T) this;
}
public T putChar(String key, char value) {
bundle.putChar(key, value);
return (T) this;
}
public T putShort(String key, short value) {
bundle.putShort(key, value);
return (T) this;
}
public T putInt(String key, int value) {
bundle.putInt(key, value);
return (T) this;
}
public T putBundle(String key, Bundle value) {
bundle.putBundle(key, value);
return (T) this;
}
public T putLong(String key, long value) {
bundle.putLong(key, value);
return (T) this;
}
public T putFloat(String key, float value) {
bundle.putFloat(key, value);
return (T) this;
}
public T putDouble(String key, double value) {
bundle.putDouble(key, value);
return (T) this;
}
public T putString(String key, String value) {
bundle.putString(key, value);
return (T) this;
}
public T putIntArray(String key, int[] value) {
bundle.putIntArray(key, value);
return (T) this;
}
public T putStringArray(String key, String[] value) {
bundle.putStringArray(key, value);
return (T) this;
}
public T putStringArrayList(String key, ArrayList<String> array) {
bundle.putStringArrayList(key, array);
return (T) this;
}
public T putParcelable(String key, Parcelable value) {
bundle.putParcelable(key, value);
return (T) this;
}
public T putParcelableArrayList(String key, ArrayList<? extends Parcelable> value) {
bundle.putParcelableArrayList(key, value);
return (T) this;
}
public T putAll(Bundle bundle) {
this.bundle.putAll(bundle);
return (T) this;
}
public T putSerializable(String key, Serializable value) {
bundle.putSerializable(key, value);
return (T) this;
}
/**
* Converts this BundleBuilder into a plain Bundle object.
*
* @return A new Bundle containing all the mappings from the current BundleBuilder.
*/
public Bundle toBundle() {
return new Bundle(bundle);
}
}
| 903 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactNativeTabActivity.java | package com.airbnb.android.react.navigation;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import com.airbnb.android.R;
import com.facebook.react.bridge.ReadableMap;
import java.util.Map;
import java.util.Stack;
public class ReactNativeTabActivity extends ReactAwareActivity
implements ScreenCoordinatorComponent, BottomNavigationView.OnNavigationItemSelectedListener {
private static final String TAG = ReactNativeTabActivity.class.getSimpleName();
private ViewGroup.OnHierarchyChangeListener reactViewChangeListener = new ViewGroup.OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
Log.d(TAG, "onChildViewAdded");
if (child instanceof ViewGroup) {
Log.d(TAG, "onChildViewAdded: adding child listener");
// onChildViewAdded is a shallow listener, so we want to recursively listen
// to all children that are ViewGroups as well. For a tab scene, the view
// hierarchy should not be very deep, so this seems okay to me. We should be
// careful though.
((ViewGroup)child).setOnHierarchyChangeListener(reactViewChangeListener);
}
debouncedRefreshTabs();
}
@Override
public void onChildViewRemoved(View parent, View child) {
Log.d(TAG, "onChildViewRemoved");
// TODO(lmr): is there any reason we would need to clean up the onHierarchyChangeListener here?
debouncedRefreshTabs();
}
};
private TabCoordinator tabCoordinator;
private ReactBottomNavigation bottomNavigationView;
private ViewGroup tabConfigContainer;
private boolean tabViewsIsDirty = false;
private Map<Integer, TabView> tabViews = new ArrayMap<>();
private ReadableMap prevTabBarConfig = ConversionUtil.EMPTY_MAP;
private ReadableMap renderedTabBarConfig = ConversionUtil.EMPTY_MAP;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_2);
bottomNavigationView = (ReactBottomNavigation) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
tabConfigContainer = (ViewGroup) findViewById(R.id.tab_config_container);
tabConfigContainer.setOnHierarchyChangeListener(reactViewChangeListener);
ScreenCoordinatorLayout container = (ScreenCoordinatorLayout) findViewById(R.id.content);
tabCoordinator = new TabCoordinator(this, container, savedInstanceState);
ReactNativeFragment tabConfigFragment = ReactNativeFragment.newInstance("TabScreen", null);
getSupportFragmentManager().beginTransaction()
.add(R.id.tab_config_container, tabConfigFragment)
.commitNow();
}
@Override
public ScreenCoordinator getScreenCoordinator() {
return tabCoordinator.getCurrentScreenCoordinator();
}
@Override
public void onBackPressed() {
if (!tabCoordinator.onBackPressed()) {
super.onBackPressed();
}
}
private void debouncedRefreshTabs() {
if (tabViewsIsDirty) {
return;
}
tabViewsIsDirty = true;
tabConfigContainer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
tabViewsIsDirty = false;
tabConfigContainer.getViewTreeObserver().removeOnPreDrawListener(this);
refreshTabs();
return true;
}
});
}
private void refreshTabs() {
Log.d(TAG, "refreshTabs");
traverseTabs();
notifyTabsHaveChanged();
}
private void traverseTabs() {
Stack<ViewGroup> stack = new Stack<>();
stack.push(tabConfigContainer);
prevTabBarConfig = renderedTabBarConfig;
renderedTabBarConfig = ConversionUtil.EMPTY_MAP;
tabViews = new ArrayMap<>();
while (!stack.empty()) {
ViewGroup view = stack.pop();
int childCount = view.getChildCount();
for (int i = 0; i < childCount; ++i) {
View child = view.getChildAt(i);
if (child instanceof TabView) {
tabViews.put(child.getId(), (TabView) child);
} else if (child instanceof TabBarView) {
TabBarView tabBarView = (TabBarView) child;
renderedTabBarConfig = ConversionUtil.combine(renderedTabBarConfig, tabBarView.getConfig());
stack.push(tabBarView);
} else if (child instanceof ViewGroup) {
stack.push((ViewGroup) child);
}
}
}
}
private void notifyTabsHaveChanged() {
Log.d(TAG, "notifyTabsHaveChanged");
Menu menu = bottomNavigationView.getMenu();
getImplementation().reconcileTabBarProperties(
bottomNavigationView,
menu,
prevTabBarConfig,
renderedTabBarConfig
);
menu.clear();
bottomNavigationView.clearIconHolders();
int index = 0;
for (TabView tab : tabViews.values()) {
getImplementation().makeTabItem(
bottomNavigationView,
menu,
index,
tab.getId(),
tab.getRenderedConfig()
);
index++;
}
if (tabViews.size() > 0) {
TabView view = tabViews.values().iterator().next();
tabCoordinator.showTab(view.getFragment(), view.getId());
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected");
TabView tab = tabViews.get(item.getItemId());
if (tab != null) {
Log.d(TAG, "found tab");
Fragment fragment = tab.getFragment();
tabCoordinator.showTab(fragment, item.getItemId());
}
return true;
}
}
| 904 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactBottomNavigation.java | package com.airbnb.android.react.navigation;
import android.content.Context;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.design.widget.BottomNavigationView;
import android.util.AttributeSet;
import android.view.MenuItem;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.DraweeHolder;
import com.facebook.drawee.view.MultiDraweeHolder;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.image.QualityInfo;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.views.toolbar.DrawableWithIntrinsicSize;
// TODO(lmr): we might want to make this an abstract class and have a default implementation
public class ReactBottomNavigation extends BottomNavigationView {
private static final String TAG = "ReactBottomNavigation";
private static final String PROP_ICON_URI = "uri";
private static final String PROP_ICON_WIDTH = "width";
private static final String PROP_ICON_HEIGHT = "height";
private final DraweeHolder mBackgroundHolder;
private final MultiDraweeHolder<GenericDraweeHierarchy> mItemIconHolders =
new MultiDraweeHolder<>();
private IconControllerListener mBackgroundControllerListener;
/**
* Attaches specific icon width & height to a BaseControllerListener which will be used to
* create the Drawable
*/
public abstract class IconControllerListener extends BaseControllerListener<ImageInfo> {
private final DraweeHolder mHolder;
private IconImageInfo mIconImageInfo;
public IconControllerListener(DraweeHolder holder) {
mHolder = holder;
}
public void setIconImageInfo(IconImageInfo iconImageInfo) {
mIconImageInfo = iconImageInfo;
}
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
super.onFinalImageSet(id, imageInfo, animatable);
final ImageInfo info = mIconImageInfo != null ? mIconImageInfo : imageInfo;
setDrawable(new DrawableWithIntrinsicSize(mHolder.getTopLevelDrawable(), info));
}
protected abstract void setDrawable(Drawable d);
}
public class ActionIconControllerListener extends IconControllerListener {
private final MenuItem mItem;
ActionIconControllerListener(MenuItem item, DraweeHolder holder) {
super(holder);
mItem = item;
}
@Override
protected void setDrawable(Drawable d) {
mItem.setIcon(d);
}
}
/**
* Simple implementation of ImageInfo, only providing width & height
*/
private static class IconImageInfo implements ImageInfo {
private int mWidth;
private int mHeight;
public IconImageInfo(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
@Override
public QualityInfo getQualityInfo() {
return null;
}
}
public ReactBottomNavigation(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
mBackgroundHolder = DraweeHolder.create(createDraweeHierarchy(), context);
init(context);
}
public ReactBottomNavigation(Context context) {
super(context);
mBackgroundHolder = DraweeHolder.create(createDraweeHierarchy(), context);
init(context);
}
private void init(Context context) {
mBackgroundControllerListener = new IconControllerListener(mBackgroundHolder) {
@Override
protected void setDrawable(Drawable d) {
setBackground(d);
}
};
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
detachDraweeHolders();
}
@Override
public void onStartTemporaryDetach() {
super.onStartTemporaryDetach();
detachDraweeHolders();
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
attachDraweeHolders();
}
@Override
public void onFinishTemporaryDetach() {
super.onFinishTemporaryDetach();
attachDraweeHolders();
}
private void detachDraweeHolders() {
mBackgroundHolder.onDetach();
mItemIconHolders.onDetach();
}
private void attachDraweeHolders() {
mBackgroundHolder.onAttach();
mItemIconHolders.onAttach();
}
/* package */ void setBackgroundSource(ReadableMap source) {
setIconSource(source, mBackgroundControllerListener, mBackgroundHolder);
}
public void clearIconHolders() {
mItemIconHolders.clear();
}
public void setMenuItemIcon(final MenuItem item, ReadableMap iconSource) {
DraweeHolder<GenericDraweeHierarchy> holder =
DraweeHolder.create(createDraweeHierarchy(), getContext());
ActionIconControllerListener controllerListener = new ActionIconControllerListener(item, holder);
controllerListener.setIconImageInfo(getIconImageInfo(iconSource));
setIconSource(iconSource, controllerListener, holder);
mItemIconHolders.add(holder);
}
/**
* Sets an icon for a specific icon source. If the uri indicates an icon
* to be somewhere remote (http/https) or on the local filesystem, it uses fresco to load it.
* Otherwise it loads the Drawable from the Resources and directly returns it via a callback
*/
private void setIconSource(ReadableMap source, IconControllerListener controllerListener, DraweeHolder holder) {
String uri = source != null ? source.getString(PROP_ICON_URI) : null;
if (uri == null) {
controllerListener.setIconImageInfo(null);
controllerListener.setDrawable(null);
} else if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("file://")) {
controllerListener.setIconImageInfo(getIconImageInfo(source));
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(Uri.parse(uri))
.setControllerListener(controllerListener)
.setOldController(holder.getController())
.build();
holder.setController(controller);
holder.getTopLevelDrawable().setVisible(true, true);
} else {
controllerListener.setDrawable(getDrawableByName(uri));
}
}
private GenericDraweeHierarchy createDraweeHierarchy() {
return new GenericDraweeHierarchyBuilder(getResources())
.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
.setFadeDuration(0)
.build();
}
private int getDrawableResourceByName(String name) {
return getResources().getIdentifier(
name,
"drawable",
getContext().getPackageName());
}
private Drawable getDrawableByName(String name) {
int drawableResId = getDrawableResourceByName(name);
if (drawableResId != 0) {
return getResources().getDrawable(getDrawableResourceByName(name));
} else {
return null;
}
}
private IconImageInfo getIconImageInfo(ReadableMap source) {
if (source.hasKey(PROP_ICON_WIDTH) && source.hasKey(PROP_ICON_HEIGHT)) {
final int width = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_WIDTH)));
final int height = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_HEIGHT)));
return new IconImageInfo(width, height);
} else {
return null;
}
}
}
| 905 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactToolbar.java | package com.airbnb.android.react.navigation;
import android.content.Context;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.views.toolbar.DrawableWithIntrinsicSize;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.DraweeHolder;
import com.facebook.drawee.view.MultiDraweeHolder;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.image.QualityInfo;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.PixelUtil;
// TODO(lmr): we might want to make this an abstract class and have a default implementation
public class ReactToolbar extends Toolbar {
// private static final String PROP_ACTION_ICON = "icon";
// private static final String PROP_ACTION_SHOW = "show";
// private static final String PROP_ACTION_SHOW_WITH_TEXT = "showWithText";
private static final String TAG = "ReactToolbar";
private static final String PROP_ICON_URI = "uri";
private static final String PROP_ICON_WIDTH = "width";
private static final String PROP_ICON_HEIGHT = "height";
private final DraweeHolder mLogoHolder;
private final DraweeHolder mNavIconHolder;
private final DraweeHolder mOverflowIconHolder;
private final MultiDraweeHolder<GenericDraweeHierarchy> mActionsHolder =
new MultiDraweeHolder<>();
private IconControllerListener mLogoControllerListener;
private IconControllerListener mNavIconControllerListener;
private IconControllerListener mOverflowIconControllerListener;
private int foregroundColor;
/**
* Attaches specific icon width & height to a BaseControllerListener which will be used to
* create the Drawable
*/
public abstract class IconControllerListener extends BaseControllerListener<ImageInfo> {
private final DraweeHolder mHolder;
private IconImageInfo mIconImageInfo;
public IconControllerListener(DraweeHolder holder) {
mHolder = holder;
}
public void setIconImageInfo(IconImageInfo iconImageInfo) {
mIconImageInfo = iconImageInfo;
}
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
super.onFinalImageSet(id, imageInfo, animatable);
final ImageInfo info = mIconImageInfo != null ? mIconImageInfo : imageInfo;
setDrawable(new DrawableWithIntrinsicSize(mHolder.getTopLevelDrawable(), info));
}
protected abstract void setDrawable(Drawable d);
}
public class ActionIconControllerListener extends IconControllerListener {
private final MenuItem mItem;
ActionIconControllerListener(MenuItem item, DraweeHolder holder) {
super(holder);
mItem = item;
}
@Override
protected void setDrawable(Drawable d) {
mItem.setIcon(d);
}
}
/**
* Simple implementation of ImageInfo, only providing width & height
*/
private static class IconImageInfo implements ImageInfo {
private int mWidth;
private int mHeight;
public IconImageInfo(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
@Override
public QualityInfo getQualityInfo() {
return null;
}
}
public ReactToolbar(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
mLogoHolder = DraweeHolder.create(createDraweeHierarchy(), context);
mNavIconHolder = DraweeHolder.create(createDraweeHierarchy(), context);
mOverflowIconHolder = DraweeHolder.create(createDraweeHierarchy(), context);
init(context);
}
public ReactToolbar(Context context) {
super(context);
mLogoHolder = DraweeHolder.create(createDraweeHierarchy(), context);
mNavIconHolder = DraweeHolder.create(createDraweeHierarchy(), context);
mOverflowIconHolder = DraweeHolder.create(createDraweeHierarchy(), context);
init(context);
}
private void init(Context context) {
mLogoControllerListener = new IconControllerListener(mLogoHolder) {
@Override
protected void setDrawable(Drawable d) {
setLogo(d);
}
};
mNavIconControllerListener = new IconControllerListener(mNavIconHolder) {
@Override
protected void setDrawable(Drawable d) {
setNavigationIcon(d);
}
};
mOverflowIconControllerListener = new IconControllerListener(mOverflowIconHolder) {
@Override
protected void setDrawable(Drawable d) {
setOverflowIcon(d);
}
};
}
// private final Runnable mLayoutRunnable = new Runnable() {
// @Override
// public void run() {
// measure(
// MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
// MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
// layout(getLeft(), getTop(), getRight(), getBottom());
// }
// };
//
// @Override
// public void requestLayout() {
// super.requestLayout();
//
// // The toolbar relies on a measure + layout pass happening after it calls requestLayout().
// // Without this, certain calls (e.g. setLogo) only take effect after a second invalidation.
// post(mLayoutRunnable);
// }
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
detachDraweeHolders();
}
@Override
public void onStartTemporaryDetach() {
super.onStartTemporaryDetach();
detachDraweeHolders();
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
attachDraweeHolders();
}
@Override
public void onFinishTemporaryDetach() {
super.onFinishTemporaryDetach();
attachDraweeHolders();
}
private void detachDraweeHolders() {
mLogoHolder.onDetach();
mNavIconHolder.onDetach();
mOverflowIconHolder.onDetach();
mActionsHolder.onDetach();
}
private void attachDraweeHolders() {
mLogoHolder.onAttach();
mNavIconHolder.onAttach();
mOverflowIconHolder.onAttach();
mActionsHolder.onAttach();
}
/* package */ void setLogoSource(ReadableMap source) {
setIconSource(source, mLogoControllerListener, mLogoHolder);
}
/* package */ void setNavIconSource(ReadableMap source) {
setIconSource(source, mNavIconControllerListener, mNavIconHolder);
}
/* package */ void setOverflowIconSource(ReadableMap source) {
setIconSource(source, mOverflowIconControllerListener, mOverflowIconHolder);
}
/* package */ void setRightButtons(Menu menu, ReadableArray buttons, final ReactInterface component) {
mActionsHolder.clear();
int length = buttons.size();
for (int i = 0; i < length; i++) {
ReadableMap button = buttons.getMap(i);
String title = button.hasKey("title") && button.getType("title") == ReadableType.String
? button.getString("title")
: String.format("Item %s", i);
// use `length - i` for ordering so the button ordering is consistent with iOS
MenuItem item = menu.add(Menu.NONE, Menu.NONE, length - i, title);
if (button.hasKey("image")) {
setMenuItemIcon(item, button.getMap("image"));
}
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
final Object data = i;
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
component.emitEvent("onRightPress", data);
return false;
}
});
}
}
private void setMenuItemIcon(final MenuItem item, ReadableMap iconSource) {
DraweeHolder<GenericDraweeHierarchy> holder =
DraweeHolder.create(createDraweeHierarchy(), getContext());
ActionIconControllerListener controllerListener = new ActionIconControllerListener(item, holder);
controllerListener.setIconImageInfo(getIconImageInfo(iconSource));
setIconSource(iconSource, controllerListener, holder);
mActionsHolder.add(holder);
}
/**
* Sets an icon for a specific icon source. If the uri indicates an icon
* to be somewhere remote (http/https) or on the local filesystem, it uses fresco to load it.
* Otherwise it loads the Drawable from the Resources and directly returns it via a callback
*/
private void setIconSource(ReadableMap source, IconControllerListener controllerListener, DraweeHolder holder) {
String uri = source != null ? source.getString(PROP_ICON_URI) : null;
if (uri == null) {
controllerListener.setIconImageInfo(null);
controllerListener.setDrawable(null);
} else if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("file://")) {
controllerListener.setIconImageInfo(getIconImageInfo(source));
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(Uri.parse(uri))
.setControllerListener(controllerListener)
.setOldController(holder.getController())
.build();
holder.setController(controller);
holder.getTopLevelDrawable().setVisible(true, true);
} else {
controllerListener.setDrawable(getDrawableByName(uri));
}
}
private GenericDraweeHierarchy createDraweeHierarchy() {
return new GenericDraweeHierarchyBuilder(getResources())
.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
.setFadeDuration(0)
.build();
}
private int getDrawableResourceByName(String name) {
return getResources().getIdentifier(
name,
"drawable",
getContext().getPackageName());
}
private Drawable getDrawableByName(String name) {
int drawableResId = getDrawableResourceByName(name);
if (drawableResId != 0) {
return getResources().getDrawable(getDrawableResourceByName(name));
} else {
return null;
}
}
private IconImageInfo getIconImageInfo(ReadableMap source) {
if (source.hasKey(PROP_ICON_WIDTH) && source.hasKey(PROP_ICON_HEIGHT)) {
final int width = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_WIDTH)));
final int height = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_HEIGHT)));
return new IconImageInfo(width, height);
} else {
return null;
}
}
public boolean onCreateOptionsMenu(int menuRes, Menu menu, MenuInflater inflater) {
menu.clear();
if (menuRes != 0) {
inflater.inflate(menuRes, menu);
// refreshForegroundColor();
}
return true;
}
private void refreshForegroundColor() {
setForegroundColor(foregroundColor);
}
public void setForegroundColor(int color) {
if (color == 0) {
return;
}
foregroundColor = color;
// setTitleTextColor(color);
// setSubtitleTextColor(color);
}
}
| 906 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactExposedActivityParamsConstants.java | package com.airbnb.android.react.navigation;
public final class ReactExposedActivityParamsConstants {
public static final String KEY_ARGUMENT = "KEY_RN_ACTIVITY_ARGUMENT";
}
| 907 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/NativeNavigationPackage.java | package com.airbnb.android.react.navigation;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@SuppressWarnings("unused")
public class NativeNavigationPackage implements ReactPackage {
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.<NativeModule>singletonList(
new NavigatorModule(reactContext, ReactNavigationCoordinator.sharedInstance));
}
@Override public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@SuppressWarnings("rawtypes") @Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new SharedElementGroupManager(),
new SharedElementViewManager(ReactNavigationCoordinator.sharedInstance),
new TabBarViewManager(),
new TabViewManager()
);
}
}
| 908 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/TabView.java | package com.airbnb.android.react.navigation;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.View;
import com.facebook.react.bridge.ReadableMap;
/**
* This view is used as a data structure to hold configuration for a Tab in a
* ReactNativeTabActivity, and doesn't actually render anything that will be visible
* to the user.
*/
public class TabView extends View {
private String route;
private String title;
private ReadableMap prevConfig;
private ReadableMap renderedConfig;
private Bundle props;
private Fragment fragment;
public TabView(Context context, AttributeSet attrs) {
super(context, attrs);
setVisibility(View.GONE);
}
public void setRoute(String route) {
this.route = route;
}
public void setProps(ReadableMap props) {
this.props = ConversionUtil.toBundle(props);
}
public void setConfig(ReadableMap config) {
this.prevConfig = this.renderedConfig;
this.renderedConfig = config;
}
public ReadableMap getPrevConfig() {
return prevConfig;
}
public ReadableMap getRenderedConfig() {
return renderedConfig;
}
public Fragment getFragment() {
if (fragment == null) {
fragment = instantiateFragment();
}
return fragment;
}
public String getRoute() {
return route;
}
private ReactNativeFragment instantiateFragment() {
return ReactNativeFragment.newInstance(route, props);
}
}
| 909 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactNativeIntents.java | package com.airbnb.android.react.navigation;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.ViewGroup;
import com.airbnb.android.R;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.ReadableMap;
public final class ReactNativeIntents {
static final String EXTRA_MODULE_NAME = "REACT_MODULE_NAME";
static final String EXTRA_PROPS = "REACT_PROPS";
static final String EXTRA_CODE = "code";
static final String EXTRA_IS_DISMISS = "isDismiss";
static final String INSTANCE_ID_PROP = "nativeNavigationInstanceId";
static final String INITIAL_BAR_HEIGHT_PROP = "nativeNavigationInitialBarHeight";
private static final String SHARED_ELEMENT_TRANSITION_GROUP_OPTION = "transitionGroup";
private static ReactNavigationCoordinator coordinator = ReactNavigationCoordinator.sharedInstance;
private ReactNativeIntents() {
}
@SuppressWarnings({"WeakerAccess", "unused"})
public static void pushScreen(Activity activity, String moduleName) {
pushScreen(activity, moduleName, null);
}
@SuppressWarnings("WeakerAccess")
public static void pushScreen(Activity activity, String moduleName, @Nullable Bundle props) {
// TODO: right now this is the same as presentScreen but eventually it should just do
// a fragment transaction
Intent intent = pushIntent(activity, moduleName, props);
//noinspection unchecked
Bundle options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity)
.toBundle();
activity.startActivity(intent, options);
}
@SuppressWarnings("WeakerAccess")
public static void presentScreen(Activity context, String moduleName) {
presentScreen(context, moduleName, null);
}
@SuppressWarnings("WeakerAccess")
public static void presentScreen(Activity activity, String moduleName, @Nullable Bundle props) {
Intent intent = presentIntent(activity, moduleName, props);
//noinspection unchecked
Bundle options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity)
.toBundle();
activity.startActivity(intent, options);
}
static Bundle getSharedElementOptionsBundle(
Activity activity, Intent intent, @Nullable ReadableMap options) {
ViewGroup transitionGroup = null;
if (activity instanceof ReactInterface && options != null &&
options.hasKey(SHARED_ELEMENT_TRANSITION_GROUP_OPTION)) {
ReactRootView reactRootView = ((ReactInterface) activity).getReactRootView();
transitionGroup = ViewUtils.findViewGroupWithTag(
reactRootView,
R.id.react_shared_element_group_id,
options.getString(SHARED_ELEMENT_TRANSITION_GROUP_OPTION));
}
if (transitionGroup == null) {
// Even though there is no transition group, we want the activity options to include a scene
// transition so that we can postpone the enter transition.
//noinspection unchecked
return ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle();
} else {
ReactNativeUtils.setIsSharedElementTransition(intent);
return AutoSharedElementCallback.getActivityOptionsBundle(activity, transitionGroup);
}
}
static Intent pushIntent(Context context, String moduleName, @Nullable Bundle props) {
Class destClass = coordinator.getOrDefault(moduleName).mode.getPushActivityClass();
return new Intent(context, destClass)
.putExtras(intentExtras(moduleName, props));
}
static Intent presentIntent(
Context context, String moduleName, @Nullable Bundle props) {
Class destClass = coordinator.getOrDefault(moduleName).mode.getPresentActivityClass();
return new Intent(context, destClass)
.putExtras(intentExtras(moduleName, props));
}
private static Bundle intentExtras(String moduleName, @Nullable Bundle props) {
return new BundleBuilder()
.putString(EXTRA_MODULE_NAME, moduleName)
.putBundle(EXTRA_PROPS, props)
.toBundle();
}
}
| 910 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/TabBarViewManager.java | package com.airbnb.android.react.navigation;
import android.util.Log;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
public class TabBarViewManager extends ViewGroupManager<TabBarView> {
private static final String TAG = "TabBarViewManager";
@Override
public String getName() {
return "NativeNavigationTabBarView";
}
@Override
protected TabBarView createViewInstance(ThemedReactContext reactContext) {
return new TabBarView(reactContext, null);
}
@ReactProp(name="config")
public void setConfig(TabBarView view, ReadableMap config) {
Log.d(TAG, "setConfig");
view.setConfig(config);
}
}
| 911 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/AutoSharedElementCallback.java | // REVIEWERS: gabriel-peal
package com.airbnb.android.react.navigation;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.Fade;
import android.transition.Transition;
import android.transition.TransitionSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Shared element helper which will automatically find and coordinate shared element transitions.
*/
@SuppressWarnings({"WeakerAccess", "unused"}) public class AutoSharedElementCallback
extends SharedElementCallback {
/**
* Target > 5.0 because of: https://app.bugsnag .com/airbnb/android-1/errors/576174ba26963cde6fd02002?filters[error
* .status][]=in%20progress&filters[event.severity][]=error&filters[error
* .assigned_to][]=me&pivot_tab=event http://stackoverflow .com/questions/34658911/entertransitioncoordinator-causes-npe-in-android
* -5-0 Target > 5.1 because of: https://app.bugsnag .com/airbnb/android-1/errors/57e594ab2f7103a1e02c1a61
* https://app.bugsnag.com/airbnb/android-1/errors/57ed9a742f7103a1e02c9225
* https://app.bugsnag.com/airbnb/android-1/errors/57d13d8d2f7103a1e029b988
*/
private static final int TARGET_API = VERSION_CODES.M;
private static final String TAG = AutoSharedElementCallback.class.getSimpleName();
private static final long ASYNC_VIEWS_TIMEOUT_MS = 500;
private static final int DEFAULT_WINDOW_ENTER_FADE_DURATION_MS = 350;
private static final int DEFAULT_WINDOW_RETURN_FADE_DURATION_MS = 200;
private static final int DEFAULT_SHARED_ELEMENT_ENTER_DURATION_MS = 300;
private static final int DEFAULT_SHARED_ELEMENT_RETURN_DURATION_MS = 200;
/** 2 frames */
private static final int ASYNC_VIEW_POLL_MS = 32;
/** Copied from {@link SharedElementCallback} */
public static final String BUNDLE_SNAPSHOT_BITMAP = "sharedElement:snapshot:bitmap";
public static final String BUNDLE_SNAPSHOT_IMAGE_SCALETYPE =
"sharedElement:snapshot:imageScaleType";
public static final String BUNDLE_SNAPSHOT_IMAGE_MATRIX = "sharedElement:snapshot:imageMatrix";
private static Transition sDefaultEnterTransition;
private static Transition sDefaultReturnTransition;
/**
* @see #getActivityOptions(Activity, String, long)
*/
public static Bundle getActivityOptionsBundle(Activity activity, String type, long id) {
return getActivityOptions(activity, type, id).toBundle();
}
/**
* Automatically configure the activity options. This will walk the Activity view hierarchy and
* look for any potential transition views. It will then throw out any transition views with the
* same type but a different id.
*/
public static ActivityOptionsCompat getActivityOptions(Activity activity, String type, long id) {
List<Pair<View, String>> transitionViews = new ArrayList<>();
ViewUtils.findTransitionViews(activity.getWindow().getDecorView(), transitionViews);
Iterator<Pair<View, String>> it = transitionViews.iterator();
while (it.hasNext()) {
Pair<View, String> tv = it.next();
String transitionName = ViewCompat.getTransitionName(tv.first);
TransitionName tn = TransitionName.parse(transitionName);
// If a transition view has the same type but a different ID then remove it.
if (tn.id() != id && tn.type().equals(type)) {
it.remove();
}
}
//noinspection unchecked
return ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionViews.toArray
(new Pair[transitionViews.size()]));
}
/**
* Walks the given view group and adds all view with a set transition name to the fragment
* transaction.
*/
public static void addSharedElementsToFragmentTransaction(
FragmentTransaction ft, ViewGroup viewGroup) {
List<Pair<View, String>> transitionViews = new ArrayList<>();
ViewUtils.findTransitionViews(viewGroup, transitionViews);
for (Pair<View, String> tv : transitionViews) {
ft.addSharedElement(tv.first, tv.second);
}
}
/**
* @see #getActivityOptions(Activity, View)
*/
public static Bundle getActivityOptionsBundle(Activity activity, View view) {
return getActivityOptions(activity, view).toBundle();
}
public static ActivityOptionsCompat getActivityOptions(Activity activity, View view) {
return getActivityOptions(activity, view, true);
}
/**
* Automatically creates activity options with all of the transition views within view.
*/
public static ActivityOptionsCompat getActivityOptions(Activity activity, View view, boolean
includeSystemUi) {
List<Pair<View, String>> transitionViews = new ArrayList<>();
if (VERSION.SDK_INT >= TARGET_API) {
ViewUtils.findTransitionViews(view, transitionViews);
if (includeSystemUi) {
addSystemUi(activity, transitionViews);
}
}
//noinspection unchecked
return ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionViews.toArray
(new Pair[transitionViews.size()]));
}
@TargetApi(TARGET_API)
private static void addSystemUi(Activity activity, List<Pair<View, String>> transitionViews) {
View decor = activity.getWindow().getDecorView();
View statusBar = decor.findViewById(android.R.id.statusBarBackground);
if (statusBar != null) {
transitionViews.add(Pair.create(statusBar, ViewCompat.getTransitionName(statusBar)));
}
View navBar = decor.findViewById(android.R.id.navigationBarBackground);
if (navBar != null) {
transitionViews.add(Pair.create(navBar, ViewCompat.getTransitionName(navBar)));
}
}
/**
* Delegate to intercept and control the behavior of shared elements and {@link
* AutoSharedElementCallback}.
*/
@SuppressWarnings("UnusedParameters") public static class AutoSharedElementCallbackDelegate {
/**
* Called before {@link AutoSharedElementCallback} runs its mapSharedElements logic. Return
* whether the mapping was fully handled and no further mappings should be automatically
* attempted.
*/
public boolean onPreMapSharedElements(List<String> names, Map<String, View> sharedElements) {
return false;
}
/**
* Called after {@link AutoSharedElementCallback} has run its auto mapping. If {@link
* #onPreMapSharedElements(List, Map)} returns true, this will be called immediately after.
*/
public void onPostMapSharedElements(List<String> names, Map<String, View> sharedElements) {
}
}
private final Runnable checkForAsyncViewsRunnable;
private final Runnable cancelAsyncViewsRunnable;
private final AppCompatActivity activity;
private final List<TransitionName> asyncTransitionViews;
private Transition sharedElementEnterTransition;
private Transition sharedElementReturnTransition;
private AutoSharedElementCallbackDelegate delegate;
/**
* Whether or not onSharedElementEnd has been called since the last onMapSharedElements. In an
* entering transition, onSharedElementStart will be called before onSharedElementEnd. In a
* returning transition, onSharedElementEnd will be called before onSharedElementStart.
*/
private boolean endCalledSinceOnMap;
private long enterBackgroundFadeDuration = DEFAULT_WINDOW_ENTER_FADE_DURATION_MS;
private long returnBackgroundFadeDuration = DEFAULT_WINDOW_RETURN_FADE_DURATION_MS;
public AutoSharedElementCallback(AppCompatActivity activity) {
this.activity = activity;
checkForAsyncViewsRunnable = null;
cancelAsyncViewsRunnable = null;
asyncTransitionViews = null;
}
/**
* Sets up the {@link SharedElementCallback} for the given activity.
*
* However, some views may not be available immediately such as views inside of a RecyclerView or
* in a toolbar. Use asyncTransitionViews to postpone the shared element transition until all
* async views are ready.
*
* However, it will only look for type, id, and subtype and will instead do a crossfade if the
* subid doesn't match.
*/
public AutoSharedElementCallback(AppCompatActivity activity, TransitionName...
asyncTransitionViews) {
this.activity = activity;
if (VERSION.SDK_INT >= TARGET_API) {
// Using Arrays.asList() by itself doesn't support iterator.remove().
this.asyncTransitionViews = new LinkedList<>(Arrays.asList(asyncTransitionViews));
activity.supportPostponeEnterTransition();
startPostponedTransitionsIfReady();
checkForAsyncViewsRunnable = new Runnable() {
@Override public void run() {
startPostponedTransitionsIfReady();
}
};
cancelAsyncViewsRunnable = new Runnable() {
@Override public void run() {
if (AutoSharedElementCallback.this.hasActivityStopped()) {
return;
}
AutoSharedElementCallback.this.scheduleStartPostponedTransition();
Log.w(TAG, "Timed out waiting for async views to load!");
}
};
startPostponedTransitionsIfReady();
getDecorView().postDelayed(cancelAsyncViewsRunnable, ASYNC_VIEWS_TIMEOUT_MS);
} else {
checkForAsyncViewsRunnable = null;
cancelAsyncViewsRunnable = null;
this.asyncTransitionViews = null;
}
}
private boolean hasActivityStopped() {
// Attempt to fix https://app.bugsnag
// .com/airbnb/android-1/errors/5784e47d26963cde6fd22bb5?filters%5Berror
// .status%5D%5B%5D=in%20progress&filters%5Bevent.since%5D%5B%5D=7d&filters%5Bevent
// .severity%5D%5B%5D=error&filters%5Berror.assigned_to%5D%5B%5D=me
return activity.getWindow() == null || activity.isFinishing();
}
/**
* Scans all transition views for a partial match with all remaining async transition views.
*/
private void startPostponedTransitionsIfReady() {
List<Pair<View, String>> transitionViewPairs = new ArrayList<>();
ViewUtils.findTransitionViews(getDecorView(), transitionViewPairs);
for (Pair<View, String> p : transitionViewPairs) {
if (p.first.getParent() == null) {
// Attempt to fix https://app.bugsnag
// .com/airbnb/android-1/errors/57ed9a742f7103a1e02c9225?filters%5Berror
// .status%5D%5B%5D=in%20progress&filters%5Bevent.since%5D%5B%5D=7d&filters%5Bevent
// .severity%5D%5B%5D=error&filters%5Berror.assigned_to%5D%5B%5D=me
return;
}
}
for (Iterator<TransitionName> it = asyncTransitionViews.iterator(); it.hasNext(); ) {
TransitionName tn = it.next();
for (Pair<View, String> p : transitionViewPairs) {
// We only look for a partial match which doesn't match on subid because we can crossfade
// views that match everything
// except for subid.
if (tn.partialEquals(TransitionName.parse(ViewCompat.getTransitionName(p.first)))) {
it.remove();
break;
}
}
}
if (asyncTransitionViews.isEmpty()) {
getDecorView().removeCallbacks(checkForAsyncViewsRunnable);
getDecorView().removeCallbacks(cancelAsyncViewsRunnable);
scheduleStartPostponedTransition();
} else {
getDecorView().postDelayed(checkForAsyncViewsRunnable, ASYNC_VIEW_POLL_MS);
}
}
public void scheduleStartPostponedTransition() {
activity.getWindow().getDecorView().getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
@Override public boolean onPreDraw() {
activity.getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);
activity.supportStartPostponedEnterTransition();
return true;
}
});
}
public AutoSharedElementCallback setSharedElementEnterTransition(Transition transition) {
sharedElementEnterTransition = transition;
return this;
}
public AutoSharedElementCallback setEnterBackgroundFadeDuration(long duration) {
enterBackgroundFadeDuration = duration;
return this;
}
public AutoSharedElementCallback setSharedElementReturnTransition(Transition transition) {
sharedElementReturnTransition = transition;
return this;
}
public AutoSharedElementCallback setReturnBackgroundFadeDuration(long duration) {
returnBackgroundFadeDuration = duration;
return this;
}
public AutoSharedElementCallback setDelegate(AutoSharedElementCallbackDelegate delegate) {
this.delegate = delegate;
return this;
}
@Override
public Parcelable onCaptureSharedElementSnapshot(View sharedElement, Matrix viewToGlobalMatrix,
RectF screenBounds) {
// This is a replacement for the platform's overzealous onCaptureSharedElementSnapshot.
// If you look at what it's doing, it's creating an ARGB_8888 copy of every single shared
// element.
// This was causing us to allocate 7+mb of bitmaps on every P3 load even though we didn't
// need any of them...
// They're slow to garbage collect and lead to OOMs too....
// This just pulls the bitmap from the ImageView that we're already using and shoves it into
// the a bundle formatted all nice
// and pretty like the platform wants it to be and never has to know the difference.
if (sharedElement instanceof ImageView) {
ImageView imageView = (ImageView) sharedElement;
Drawable drawable = ((ImageView) sharedElement).getDrawable();
if (drawable != null && drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bundle bundle = new Bundle();
bundle.putParcelable(BUNDLE_SNAPSHOT_BITMAP, bitmap);
bundle.putString(BUNDLE_SNAPSHOT_IMAGE_SCALETYPE, imageView.getScaleType().toString());
if (imageView.getScaleType() == ImageView.ScaleType.MATRIX) {
Matrix matrix = imageView.getImageMatrix();
float[] values = new float[9];
matrix.getValues(values);
bundle.putFloatArray(BUNDLE_SNAPSHOT_IMAGE_MATRIX, values);
}
return bundle;
}
}
return null;
}
@Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
getDecorView().removeCallbacks(cancelAsyncViewsRunnable);
endCalledSinceOnMap = false;
boolean handled = delegate != null && delegate.onPreMapSharedElements(names, sharedElements);
if (!handled) {
mapBestPartialMatches(names, sharedElements);
}
if (delegate != null) {
delegate.onPostMapSharedElements(names, sharedElements);
}
}
private void mapBestPartialMatches(List<String> names, Map<String, View> sharedElements) {
List<Pair<View, String>> allTransitionViews = new ArrayList<>();
ViewUtils.findTransitionViews(getDecorView(), allTransitionViews);
List<View> partialMatches = new ArrayList<>();
for (String name : names) {
if (sharedElements.containsKey(name)) {
// Exact match
continue;
}
TransitionName tn = TransitionName.parse(name);
findAllPartialMatches(tn, allTransitionViews, partialMatches);
if (!partialMatches.isEmpty()) {
View mostVisibleView = ViewUtils.getMostVisibleView(partialMatches);
sharedElements.put(name, mostVisibleView);
}
}
if (delegate != null) {
delegate.onPostMapSharedElements(names, sharedElements);
}
}
/**
* Clears and populates partialMatches with all views from transitionViews that is a partial match
* with the supplied transition name.
*/
private void findAllPartialMatches(TransitionName tn, List<Pair<View, String>> transitionViews,
List<View> partialMatches) {
partialMatches.clear();
for (Pair<View, String> p : transitionViews) {
TransitionName tn2 = TransitionName.parse(p.second /* transition name */);
// If there is no views that perfectly matches the transition name but there is one that is
// a partial match, we will automatically
// map it. This will commonly occur when the user is viewing pictures and swipes to a
// different one.
if (tn.partialEquals(tn2)) {
// Partial match
partialMatches.add(p.first);
}
}
}
@TargetApi(TARGET_API) @Override
public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
List<View> sharedElementSnapshots) {
Transition enterTransition =
sharedElementEnterTransition == null ? getDefaultSharedElementEnterTransition() :
sharedElementEnterTransition;
Transition returnTransition =
sharedElementReturnTransition == null ? getDefaultSharedElementReturnTransition() :
sharedElementReturnTransition;
crossFadePartialMatchImageViews(sharedElementNames, sharedElements, sharedElementSnapshots,
(int) returnTransition.getDuration());
Window window = activity.getWindow();
window.setSharedElementEnterTransition(enterTransition);
window.setSharedElementReturnTransition(returnTransition);
boolean entering = !endCalledSinceOnMap;
window.setTransitionBackgroundFadeDuration(
entering ? enterBackgroundFadeDuration : returnBackgroundFadeDuration);
}
@Override
public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements,
List<View> sharedElementSnapshots) {
endCalledSinceOnMap = true;
}
/**
* Iterates through all shared elements and all mapp shared elements. If there is a mapped shared
* element that is only a partial match with its shared element then we will cross fade from the
* shared element to the shared element snapshot which is a bitmap created by Activity A that
* represents the appearance of the view that the shared element is transitioning back to.
*/
private void crossFadePartialMatchImageViews(List<String> sharedElementNames, List<View>
sharedElements, List<View> sharedElementSnapshots, int duration) {
// Fixes a crash in which sharedElementNames and sharedElementSnapshots are different lengths.
// According to the javadocs, these should be 1:1 but for some reason they are not sometimes.
// I have no idea why or what it means when they are
// different. However, the crossfading relies on the assumption that they are so we'll just
// ignore that case.
// https://bugsnag.com/airbnb/android-1/errors/563d370d8203f6a6502fe8fc?filters[event
// .file][]=AutoSharedElementCallback.java&filters[event.since][]=7d
// Also, either of these lists can be null ¯\_(ツ)_/¯
if (sharedElementNames == null || sharedElementSnapshots == null ||
sharedElementNames.size() != sharedElementSnapshots.size()) {
return;
}
for (int i = sharedElementNames.size() - 1; i >= 0; i--) {
View snapshotView = sharedElementSnapshots.get(i);
if (snapshotView == null || !(snapshotView instanceof ImageView)) {
continue;
}
TransitionName tn1 = TransitionName.parse(sharedElementNames.get(i));
for (View se : sharedElements) {
// We need to be able to get the drawable from the ImageView to do the crossfade so if
// it's not an ImageView then there isn't much we can do.
if (!(se instanceof ImageView)) {
continue;
}
String transitionName = ViewCompat.getTransitionName(se);
TransitionName tn2 = TransitionName.parse(transitionName);
if (tn1.partialEquals(tn2) && tn1.subId() != tn2.subId()) {
// If The views are the same except for the subId then we can attempt to crossfade them.
Drawable sharedElementDrawable = ((ImageView) se).getDrawable();
if (sharedElementDrawable == null) {
sharedElementDrawable = new ColorDrawable(Color.TRANSPARENT);
}
Drawable sharedElementSnapshotDrawable = ((ImageView) snapshotView).getDrawable();
if (sharedElementSnapshotDrawable == null) {
sharedElementSnapshotDrawable = new ColorDrawable(Color.TRANSPARENT);
}
TransitionDrawable transitionDrawable =
new TransitionDrawable(new Drawable[]{sharedElementDrawable,
sharedElementSnapshotDrawable});
((ImageView) se).setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(duration);
}
}
}
}
@TargetApi(TARGET_API) private Transition getDefaultSharedElementEnterTransition() {
if (sDefaultEnterTransition == null) {
sDefaultEnterTransition = getDefaultTransition();
sDefaultEnterTransition.setDuration(DEFAULT_SHARED_ELEMENT_ENTER_DURATION_MS);
}
return sDefaultEnterTransition;
}
@TargetApi(TARGET_API) private Transition getDefaultSharedElementReturnTransition() {
if (sDefaultReturnTransition == null) {
sDefaultReturnTransition = getDefaultTransition();
sDefaultReturnTransition.setDuration(DEFAULT_SHARED_ELEMENT_RETURN_DURATION_MS);
}
return sDefaultReturnTransition;
}
@TargetApi(TARGET_API) private Transition getDefaultTransition() {
TransitionSet set = new TransitionSet();
set.addTransition(new ChangeBounds());
set.addTransition(new Fade());
set.addTransition(new ChangeImageTransform());
set.setInterpolator(new FastOutSlowInInterpolator());
return set;
}
private View getDecorView() {
return activity.getWindow().getDecorView();
}
}
| 912 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactInterface.java | package com.airbnb.android.react.navigation;
import android.support.v4.app.FragmentActivity;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.ReadableMap;
import java.util.Map;
public interface ReactInterface {
// @formatter:off
String getInstanceId();
ReactRootView getReactRootView();
ReactToolbar getToolbar();
boolean isDismissible();
void signalFirstRenderComplete();
void notifySharedElementAddition();
FragmentActivity getActivity();
void emitEvent(String eventName, Object object);
void receiveNavigationProperties(ReadableMap properties);
void dismiss();
// @formatter:on
}
| 913 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ScreenCoordinator.java | package com.airbnb.android.react.navigation;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.transition.Fade;
import android.util.Log;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import com.airbnb.android.R;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import java.util.Map;
import java.util.Stack;
import static com.airbnb.android.react.navigation.ReactNativeIntents.EXTRA_CODE;
/**
* Owner of the navigation stack for a given Activity. There should be one per activity.
*/
public class ScreenCoordinator {
private static final String TAG = ScreenCoordinator.class.getSimpleName();
static final String EXTRA_PAYLOAD = "payload";
private static final String TRANSITION_GROUP = "transitionGroup";
enum PresentAnimation {
Modal(R.anim.slide_up, R.anim.delay, R.anim.delay, R.anim.slide_down),
Push(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right),
Fade(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out);
@AnimRes int enter;
@AnimRes int exit;
@AnimRes int popEnter;
@AnimRes int popExit;
PresentAnimation(int enter, int exit, int popEnter, int popExit) {
this.enter = enter;
this.exit = exit;
this.popEnter = popEnter;
this.popExit = popExit;
}
}
private final Stack<BackStack> backStacks = new Stack<>();
private final AppCompatActivity activity;
private final ScreenCoordinatorLayout container;
private ReactNavigationCoordinator reactNavigationCoordinator = ReactNavigationCoordinator.sharedInstance;
private int stackId = 0;
/**
* When we dismiss a back stack, the fragment manager would normally execute the latest fragment's
* pop exit animation. However, if we present A as a modal, push, B, then dismiss(), the latest
* pop exit animation would be from when B was pushed, not from when A was presented.
* We want the dismiss animation to be the popExit of the original present transaction.
*/
@AnimRes private int nextPopExitAnim;
public ScreenCoordinator(AppCompatActivity activity, ScreenCoordinatorLayout container,
@Nullable Bundle savedInstanceState) {
this.activity = activity;
this.container = container;
container.setFragmentManager(activity.getSupportFragmentManager());
// TODO: restore state
}
void onSaveInstanceState(Bundle outState) {
// TODO
}
public void pushScreen(String moduleName) {
pushScreen(moduleName, null, null);
}
public void pushScreen(String moduleName, @Nullable Bundle props, @Nullable Bundle options) {
Fragment fragment = ReactNativeFragment.newInstance(moduleName, props);
pushScreen(fragment, options);
}
public void pushScreen(Fragment fragment) {
pushScreen(fragment, null);
}
public void pushScreen(Fragment fragment, @Nullable Bundle options) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction()
.setAllowOptimization(true);
Fragment currentFragment = getCurrentFragment();
if (currentFragment == null) {
throw new IllegalStateException("There is no current fragment. You must present one first.");
}
if (ViewUtils.isAtLeastLollipop() && options != null && options.containsKey(TRANSITION_GROUP)) {
setupFragmentForSharedElement(currentFragment, fragment, ft, options);
} else {
PresentAnimation anim = PresentAnimation.Push;
ft.setCustomAnimations(anim.enter, anim.exit, anim.popEnter, anim.popExit);
}
BackStack bsi = getCurrentBackStack();
ft
.detach(currentFragment)
.add(container.getId(), fragment)
.addToBackStack(null)
.commit();
bsi.pushFragment(fragment);
Log.d(TAG, toString());
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setupFragmentForSharedElement(
Fragment outFragment, Fragment inFragment, FragmentTransaction transaction, Bundle options) {
FragmentSharedElementTransition transition = new FragmentSharedElementTransition();
inFragment.setSharedElementEnterTransition(transition);
inFragment.setSharedElementReturnTransition(transition);
Fade fade = new Fade();
inFragment.setEnterTransition(fade);
inFragment.setReturnTransition(fade);
ViewGroup rootView = (ViewGroup) outFragment.getView();
ViewGroup transitionGroup = ViewUtils.findViewGroupWithTag(
rootView,
R.id.react_shared_element_group_id,
options.getString(TRANSITION_GROUP));
AutoSharedElementCallback.addSharedElementsToFragmentTransaction(transaction, transitionGroup);
}
public void presentScreen(String moduleName) {
presentScreen(moduleName, null, null, null);
}
public void presentScreen(
String moduleName,
@Nullable Bundle props,
@Nullable Bundle options,
@Nullable Promise promise) {
// TODO: use options
Fragment fragment = ReactNativeFragment.newInstance(moduleName, props);
presentScreen(fragment, PresentAnimation.Modal, promise);
}
public void presentScreen(Fragment fragment) {
presentScreen(fragment, null);
}
private Boolean isFragmentTranslucent(Fragment fragment) {
Bundle bundle = fragment.getArguments();
if (bundle != null) {
String moduleName = bundle.getString(ReactNativeIntents.EXTRA_MODULE_NAME);
if (moduleName != null) {
ReadableMap config = reactNavigationCoordinator.getInitialConfigForModuleName(moduleName);
if (config != null && config.hasKey("screenColor")) {
return Color.alpha(config.getInt("screenColor")) < 255;
}
}
}
return false;
}
public void presentScreen(Fragment fragment, @Nullable Promise promise) {
presentScreen(fragment, PresentAnimation.Modal, promise);
}
public void presentScreen(Fragment fragment, PresentAnimation anim, @Nullable Promise promise) {
if (fragment == null) {
throw new IllegalArgumentException("Fragment must not be null.");
}
BackStack bsi = new BackStack(getNextStackTag(), anim, promise);
backStacks.push(bsi);
// TODO: dry this up with pushScreen
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction()
.setAllowOptimization(true)
.setCustomAnimations(anim.enter, anim.exit, anim.popEnter, anim.popExit);
Fragment currentFragment = getCurrentFragment();
if (currentFragment != null && !isFragmentTranslucent(fragment)) {
container.willDetachCurrentScreen();
ft.detach(currentFragment);
}
ft
.add(container.getId(), fragment)
.addToBackStack(bsi.getTag())
.commit();
activity.getSupportFragmentManager().executePendingTransactions();
bsi.pushFragment(fragment);
Log.d(TAG, toString());
}
public void dismissAll() {
while (!backStacks.isEmpty()) {
dismiss(0, null, false);
activity.getFragmentManager().executePendingTransactions();
}
}
public void onBackPressed() {
pop();
}
public void pop() {
BackStack bsi = getCurrentBackStack();
if (bsi.getSize() == 1) {
dismiss();
return;
}
bsi.popFragment();
activity.getSupportFragmentManager().popBackStack();
Log.d(TAG, toString());
}
public void dismiss() {
dismiss(Activity.RESULT_OK, null);
}
public void dismiss(int resultCode, Map<String, Object> payload) {
dismiss(resultCode, payload, true);
}
private void dismiss(int resultCode, Map<String, Object> payload, boolean finishIfEmpty) {
BackStack bsi = backStacks.pop();
Promise promise = bsi.getPromise();
deliverPromise(promise, resultCode, payload);
// This is needed so we can override the pop exit animation to slide down.
PresentAnimation anim = bsi.getAnimation();
if (backStacks.isEmpty()) {
if (finishIfEmpty) {
activity.supportFinishAfterTransition();
return;
}
} else {
// This will be used when the fragment delegates its onCreateAnimation to this.
nextPopExitAnim = anim.popExit;
}
activity.getSupportFragmentManager()
.popBackStackImmediate(bsi.getTag(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
Log.d(TAG, toString());
}
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (!enter && nextPopExitAnim != 0) {
// If this fragment was pushed on to the stack, it's pop exit animation will be
// slide out right. However, we want it to be slide down in this case.
int anim = nextPopExitAnim;
nextPopExitAnim = 0;
return AnimationUtils.loadAnimation(activity, anim);
}
return null;
}
private void deliverPromise(Promise promise, int resultCode, Map<String, Object> payload) {
if (promise != null) {
Map<String, Object> newPayload =
MapBuilder.of(EXTRA_CODE, resultCode, EXTRA_PAYLOAD, payload);
promise.resolve(ConversionUtil.toWritableMap(newPayload));
}
}
private String getNextStackTag() {
return getStackTag(stackId++);
}
private String getStackTag(int id) {
return "STACK" + id;
}
@Nullable
private Fragment getCurrentFragment() {
return activity.getSupportFragmentManager().findFragmentById(container.getId());
}
private BackStack getCurrentBackStack() {
return backStacks.peek();
}
@NonNull
private FrameLayout createContainerView() {
return new FrameLayout(activity);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ScreenCoordinator{");
for (int i = 0; i < backStacks.size(); i++) {
sb.append("Back stack ").append(i).append(":\t").append(backStacks.get(i));
}
sb.append('}');
return sb.toString();
}
}
| 914 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/ReactNativeFragmentViewGroup.java | package com.airbnb.android.react.navigation;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import com.facebook.react.ReactRootView;
/**
* Root ViewGroup for {@link ReactNativeFragment} that allows it to get KeyEvents.
*/
public class ReactNativeFragmentViewGroup extends FrameLayout {
public interface KeyListener {
boolean onKeyDown(int keyCode, KeyEvent event);
boolean onKeyUp(int keyCode, KeyEvent event);
}
@Nullable private ReactRootView reactRootView;
@Nullable private KeyListener keyListener;
public ReactNativeFragmentViewGroup(Context context) {
super(context);
}
public ReactNativeFragmentViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReactNativeFragmentViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
void setKeyListener(@Nullable KeyListener keyListener) {
this.keyListener = keyListener;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = super.onKeyDown(keyCode, event);
if (!handled && keyListener != null) {
handled = keyListener.onKeyDown(keyCode, event);
}
return handled;
}
void unmountReactApplicationAfterAnimation(ReactRootView reactRootView) {
this.reactRootView = reactRootView;
}
@Override
protected void onAnimationEnd() {
super.onAnimationEnd();
if (reactRootView != null) {
reactRootView.unmountReactApplication();
reactRootView = null;
}
}
}
| 915 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/AndroidVersion.java | package com.airbnb.android.react.navigation;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
final class AndroidVersion {
static boolean isAtLeastJellyBeanMR1() {
return VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1;
}
static boolean isAtLeastJellyBeanMR2() {
return VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2;
}
static boolean isAtLeastKitKat() {
return VERSION.SDK_INT >= VERSION_CODES.KITKAT;
}
static boolean isAtLeastLollipop() {
return VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP;
}
static boolean isAtLeastMarshmallow() {
return VERSION.SDK_INT >= VERSION_CODES.M;
}
static boolean isAtLeastLollipopMR1() {
return VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1;
}
static boolean isJellyBean() {
return VERSION.SDK_INT == VERSION_CODES.JELLY_BEAN;
}
static boolean isAtLeastNougat() {
return VERSION.SDK_INT >= VERSION_CODES.N;
}
private AndroidVersion() {
// Prevent users from instantiating this class.
}
}
| 916 |
0 | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react | Create_ds/native-navigation/lib/android/src/main/java/com/airbnb/android/react/navigation/TransitionName.java | package com.airbnb.android.react.navigation;
import android.support.annotation.NonNull;
import android.text.TextUtils;
/**
* Helper to create higher fidelity transition names. <p> This can be used by shared element
* transitions to understand what a particular element actually corresponds to. For example, a
* listing card may use listing|1337|photo|0 which would have the exact same transition name in a
* listing marquee and image viewer. However, if the user scrolls to photo 5 within the Listing
* Marquee and then goes back to a page with the listing card, it could be understood that
* listing|1337|photo|5 can be transitioned to listing|1337|photo|0 with a crossfade.
*/
public class TransitionName {
private static final char DELIMETER = '|';
private final String type;
private final long id;
private final String subtype;
private final long subId;
private TransitionName(String type, long id, String subtype, long subId) {
this.type = type;
this.id = id;
this.subtype = subtype;
this.subId = subId;
}
public static TransitionName create(@NonNull String type) {
return create(type, 0);
}
public static TransitionName create(@NonNull String type, long id) {
return create(type, id, "");
}
public static TransitionName create(@NonNull String type, long id, @NonNull String subtype) {
return create(type, id, subtype, 0);
}
/**
* Use empty string instead of null of subtype is not applicabale.
*/
public static TransitionName create(
@NonNull String type, long id, @NonNull String subtype, long subId) {
return new TransitionName(type, id, subtype, subId);
}
public static String toString(@NonNull String type) {
return toString(type, 0);
}
public static String toString(@NonNull String type, long id) {
return toString(type, id, "");
}
public static String toString(@NonNull String type, long id, @NonNull String subtype) {
return toString(type, id, subtype, 0);
}
/**
* Use empty string instead of null of subtype is not applicabale.
*/
public static String toString(
@NonNull String type, long id, @NonNull String subtype, long subId) {
if (type.indexOf(DELIMETER) != -1) {
throw new IllegalArgumentException("Invalid type " + type + ". Delimeter is " + DELIMETER);
} else if (subtype.indexOf(DELIMETER) != -1) {
throw new IllegalArgumentException(
"Invalid subtype " + subtype + ". Delimeter is " + DELIMETER);
}
return type + DELIMETER + id + DELIMETER + subtype + DELIMETER + subId;
}
public static TransitionName parse(String transitionNameString) {
if (TextUtils.isEmpty(transitionNameString)) {
return new TransitionName("", 0, "", 0);
}
String[] parsed = transitionNameString.split("[" + DELIMETER + "]");
switch (parsed.length) {
case 1:
return new TransitionName(parsed[0], 0, "", 0);
case 2:
return new TransitionName(parsed[0], Long.parseLong(parsed[1]), "", 0);
case 3:
return new TransitionName(parsed[0], Long.parseLong(parsed[1]), parsed[2], 0);
case 4:
return new TransitionName(parsed[0], Long.parseLong(parsed[1]), parsed[2], Long
.parseLong(parsed[3]));
default:
throw new IllegalArgumentException(
"Invalid transition name " + transitionNameString + ". Split into " + parsed.length +
". Should be less than 4.");
}
}
/**
* Returns whether at least the type, id, and subtype match. This could be useful when there are 2
* elements that represent the same thing (like a listing photo) but they are just different
* indices. With this knowledge, we can safely maintain the shared element mapping and crossfade
* them instead.
*/
public boolean partialEquals(TransitionName other) {
return type.equals(other.type) && id == other.id && subtype.equals(other.subtype);
}
public long subId() {
return subId;
}
public long id() {
return id;
}
public String type() {
return type;
}
}
| 917 |
0 | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb/android/Manifest.java | /*___Generated_by_IDEA___*/
package com.airbnb.android;
/* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */
public final class Manifest {
} | 918 |
0 | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb/android/R.java | /*___Generated_by_IDEA___*/
package com.airbnb.android;
/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
public final class R {
} | 919 |
0 | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb | Create_ds/native-navigation/lib/android/src/main/gen/com/airbnb/android/BuildConfig.java | /*___Generated_by_IDEA___*/
package com.airbnb.android;
/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */
public final class BuildConfig {
public final static boolean DEBUG = Boolean.parseBoolean(null);
} | 920 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/invoke/runtimes/java8/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/invoke/runtimes/java8/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
return "Hello World";
}
}
| 921 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/invoke/credential_tests/incontainer/java8/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/invoke/credential_tests/incontainer/java8/src/main/java/sts/App.java | package sts;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult;
import java.util.HashMap;
import java.util.Map;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
AWSSecurityTokenServiceClientBuilder awsSecurityTokenServiceClientBuilder =
AWSSecurityTokenServiceClientBuilder.standard();
awsSecurityTokenServiceClientBuilder.setCredentials(new EnvironmentVariableCredentialsProvider());
AWSSecurityTokenService securityClient = awsSecurityTokenServiceClientBuilder.build();
GetCallerIdentityRequest securityRequest = new GetCallerIdentityRequest();
GetCallerIdentityResult securityResponse = securityClient.getCallerIdentity(securityRequest);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
String output = String.format("{ \"message\": \"hello world\", \"account\": \"%s\" }",
securityResponse.getAccount());
return response
.withStatusCode(200)
.withBody(output);
}
}
| 922 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/11/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/11/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
} | 923 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/17/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/17/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
} | 924 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/8/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven/8/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
} | 925 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/11/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/11/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 926 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/17/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/17/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 927 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/8/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle-kotlin/8/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 928 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/11/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/11/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 929 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/17/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/17/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 930 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/8/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradle/8/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 931 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/11/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/11/src/main/java/aws/example/SecondFunction.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class SecondFunction {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Second function Invoked\n");
return "Hello Mars";
}
} | 932 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/11/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/11/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 933 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/17/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/17/src/main/java/aws/example/SecondFunction.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class SecondFunction {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Second function Invoked\n");
return "Hello Mars";
}
} | 934 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/17/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/17/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 935 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/8/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/8/src/main/java/aws/example/SecondFunction.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class SecondFunction {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Second function Invoked\n");
return "Hello Mars";
}
} | 936 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/8/src/main/java/aws | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/gradlew/8/src/main/java/aws/example/Hello.java | package aws.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Function Invoked\n");
return "Hello World";
}
}
| 937 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven-with-layer/HelloWorldLayer/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven-with-layer/HelloWorldLayer/src/main/java/helloworldlayer/SimpleMath.java | package helloworldlayer;
public class SimpleMath {
public static int sum(int a, int b) {
return a + b;
}
}
| 938 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven-with-layer/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/buildcmd/Java/maven-with-layer/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import helloworldlayer.SimpleMath;
/**
* Handler for requests to Lambda function.
*/
public class App {
public String handleRequest(Context context) {
int sumResult = SimpleMath.sum(7, 5);
return String.format("hello world. sum is %d.", sumResult);
}
}
| 939 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/sync/infra/before/Java/HelloWorldLayer/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/sync/infra/before/Java/HelloWorldLayer/src/main/java/helloworldlayer/SimpleMath.java | package helloworldlayer;
public class SimpleMath {
public static int sum(int a, int b) {
return a + b;
}
}
| 940 |
0 | Create_ds/aws-sam-cli/tests/integration/testdata/sync/infra/before/Java/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/tests/integration/testdata/sync/infra/before/Java/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import helloworldlayer.SimpleMath;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
int sumResult = SimpleMath.sum(7, 5);
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\", \"sum\": %d }", pageContents, sumResult);
return response
.withStatusCode(200)
.withBody(output);
} catch (IOException e) {
return response
.withBody("{}")
.withStatusCode(500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 941 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java/helloworld/AppTest.java | package helloworld;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AppTest {
@Test
public void successfulResponse() {
App app = new App();
GatewayResponse result = (GatewayResponse) app.handleRequest(null, null);
assertEquals(result.getStatusCode(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
assertTrue(content.contains("\"message\""));
assertTrue(content.contains("\"hello world\""));
assertTrue(content.contains("\"location\""));
}
}
| 942 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return new GatewayResponse(output, headers, 200);
} catch (IOException e) {
return new GatewayResponse("{}", headers, 500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 943 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-maven/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/GatewayResponse.java | package helloworld;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* POJO containing response object for API Gateway.
*/
public class GatewayResponse {
private final String body;
private final Map<String, String> headers;
private final int statusCode;
public GatewayResponse(final String body, final Map<String, String> headers, final int statusCode) {
this.statusCode = statusCode;
this.body = body;
this.headers = Collections.unmodifiableMap(new HashMap<>(headers));
}
public String getBody() {
return body;
}
public Map<String, String> getHeaders() {
return headers;
}
public int getStatusCode() {
return statusCode;
}
}
| 944 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/test/java/helloworld/AppTest.java | package helloworld;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AppTest {
@Test
public void successfulResponse() {
App app = new App();
GatewayResponse result = (GatewayResponse) app.handleRequest(null, null);
assertEquals(result.getStatusCode(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
assertTrue(content.contains("\"message\""));
assertTrue(content.contains("\"hello world\""));
assertTrue(content.contains("\"location\""));
}
}
| 945 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/App.java | package helloworld;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return new GatewayResponse(output, headers, 200);
} catch (IOException e) {
return new GatewayResponse("{}", headers, 500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
| 946 |
0 | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java | Create_ds/aws-sam-cli/samcli/lib/init/templates/cookiecutter-aws-sam-hello-java-gradle/{{cookiecutter.project_name}}/HelloWorldFunction/src/main/java/helloworld/GatewayResponse.java | package helloworld;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* POJO containing response object for API Gateway.
*/
public class GatewayResponse {
private final String body;
private final Map<String, String> headers;
private final int statusCode;
public GatewayResponse(final String body, final Map<String, String> headers, final int statusCode) {
this.statusCode = statusCode;
this.body = body;
this.headers = Collections.unmodifiableMap(new HashMap<>(headers));
}
public String getBody() {
return body;
}
public Map<String, String> getHeaders() {
return headers;
}
public int getStatusCode() {
return statusCode;
}
}
| 947 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static software.amazon.awssdk.http.Header.ACCEPT;
import static software.amazon.awssdk.http.Header.CHUNKED;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.junit.After;
import org.junit.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.utils.AttributeMap;
public final class UrlConnectionHttpClientWireMockTest extends SdkHttpClientTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
UrlConnectionHttpClient.Builder builder = UrlConnectionHttpClient.builder();
AttributeMap.Builder attributeMap = AttributeMap.builder();
if (options.tlsTrustManagersProvider() != null) {
builder.tlsTrustManagersProvider(options.tlsTrustManagersProvider());
}
if (options.trustAll()) {
attributeMap.put(TRUST_ALL_CERTIFICATES, options.trustAll());
}
return builder.buildWithDefaults(attributeMap.build());
}
@Override
public void connectionsAreNotReusedOn5xxErrors() {
// We cannot support this because the URL connection client doesn't allow us to disable connection reuse
}
// https://bugs.openjdk.org/browse/JDK-8163921
@Test
public void noAcceptHeader_shouldSet() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(ACCEPT, equalTo("*/*")));
}
@Test
public void hasAcceptHeader_shouldNotOverride() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
req = req.toBuilder().putHeader(ACCEPT, "text/html").build();
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(ACCEPT, equalTo("text/html")));
}
@Test
public void hasTransferEncodingHeader_shouldBeSet() throws IOException {
SdkHttpClient client = createSdkHttpClient();
stubForMockRequest(200);
SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST);
req = req.toBuilder().putHeader(TRANSFER_ENCODING, CHUNKED).build();
HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider()
.orElse(null))
.build())
.call();
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withHeader(TRANSFER_ENCODING, equalTo(CHUNKED)));
mockServer.verify(postRequestedFor(urlPathEqualTo("/")).withRequestBody(equalTo("Body")));
}
@After
public void reset() {
HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
}
}
| 948 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/Expect100ContinueTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.Level;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.testutils.LogCaptor;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.StringInputStream;
public class Expect100ContinueTest {
@Test
public void expect100ContinueWorksWithZeroContentLength200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.setContentLength(0);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(200);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith204() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(204);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(204);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith304() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(304);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(304);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWith417() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(417);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(417);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWithZeroContentLength500() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(500);
response.setContentLength(0);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(500);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
}
}
@Test
public void expect100ContinueWorksWithPositiveContentLength500() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(500);
response.setContentLength(5);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (LogCaptor logCaptor = LogCaptor.create(Level.DEBUG);
SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(500);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
assertThat(logCaptor.loggedEvents()).anySatisfy(logEvent -> {
assertThat(logEvent.getLevel()).isEqualTo(Level.DEBUG);
assertThat(logEvent.getMessage().getFormattedMessage()).contains("response payload has been dropped");
});
}
}
@Test
public void expect100ContinueWorksWithPositiveContentLength400() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(400);
response.setContentLength(5);
response.addHeader("x-amz-test-header", "foo");
response.flushBuffer();
}
};
try (LogCaptor logCaptor = LogCaptor.create(Level.DEBUG);
SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
HttpExecuteResponse response = sendRequest(client, server);
assertThat(response.httpResponse().statusCode()).isEqualTo(400);
assertThat(response.httpResponse().firstMatchingHeader("x-amz-test-header")).hasValue("foo");
assertThat(logCaptor.loggedEvents()).anySatisfy(logEvent -> {
assertThat(logEvent.getLevel()).isEqualTo(Level.DEBUG);
assertThat(logEvent.getMessage().getFormattedMessage()).contains("response payload has been dropped");
});
}
}
@Test
public void expect100ContinueFailsWithPositiveContentLength200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.setContentLength(1);
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
assertThatThrownBy(() -> sendRequest(client, server)).isInstanceOf(UncheckedIOException.class);
}
}
@Test
public void expect100ContinueFailsWithChunkedEncoded200() throws Exception {
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(200);
response.addHeader("Transfer-Encoding", "chunked");
response.flushBuffer();
}
};
try (SdkHttpClient client = UrlConnectionHttpClient.create();
EmbeddedServer server = new EmbeddedServer(handler)) {
assertThatThrownBy(() -> sendRequest(client, server)).isInstanceOf(UncheckedIOException.class);
}
}
private HttpExecuteResponse sendRequest(SdkHttpClient client, EmbeddedServer server) throws IOException {
return client.prepareRequest(HttpExecuteRequest.builder()
.request(SdkHttpRequest.builder()
.uri(server.uri())
.putHeader("Expect", "100-continue")
.putHeader("Content-Length", "0")
.method(SdkHttpMethod.PUT)
.build())
.contentStreamProvider(() -> new StringInputStream(""))
.build())
.call();
}
private static class EmbeddedServer implements SdkAutoCloseable {
private final Server server;
public EmbeddedServer(Handler handler) throws Exception {
server = new Server(0);
server.setHandler(handler);
server.start();
}
public URI uri() {
return server.getURI();
}
@Override
public void close() {
try {
server.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 949 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientDefaultWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.junit.jupiter.api.AfterEach;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientDefaultTestSuite;
public class UrlConnectionHttpClientDefaultWireMockTest extends SdkHttpClientDefaultTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient() {
return UrlConnectionHttpClient.create();
}
@AfterEach
public void reset() {
HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
}
}
| 950 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class UrlProxyConfigurationTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings,
Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
if (hostName != null && portNumber != null) {
builder.endpoint(URI.create(String.format("%s://%s:%d", protocol, hostName, portNumber)));
}
Optional.ofNullable(userName).ifPresent(builder::username);
Optional.ofNullable(password).ifPresent(builder::password);
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariablesValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 951 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ProxyConfigurationTest {
@AfterAll
public static void cleanup() {
clearProxyProperties();
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
}
@BeforeEach
public void setup() {
clearProxyProperties();
}
@Test
void testEndpointValues_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", Integer.toString(port));
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_SystemPropertyDisabled() {
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testProxyConfigurationWithSystemPropertyDisabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.username()).isNull();
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithoutNonProxyHosts_toBuilder_shouldNotThrowNPE() {
ProxyConfiguration proxyConfiguration =
ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:4321"))
.username("username")
.password("password")
.build();
assertThat(proxyConfiguration.toBuilder()).isNotNull();
}
}
| 952 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWithCustomCreateWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.Permission;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.junit.Ignore;
import org.junit.Test;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
public final class UrlConnectionHttpClientWithCustomCreateWireMockTest extends SdkHttpClientTestSuite {
private Function<HttpURLConnection, HttpURLConnection> connectionInterceptor = Function.identity();
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
return UrlConnectionHttpClient.create(uri -> invokeSafely(() -> {
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
return connectionInterceptor.apply(connection);
}));
}
// Empty test; behavior not supported when using custom factory
@Override
public void testCustomTlsTrustManager() {
}
// Empty test; behavior not supported when using custom factory
@Override
public void testTrustAllWorks() {
}
// Empty test; behavior not supported when using custom factory
@Override
public void testCustomTlsTrustManagerAndTrustAllFails() {
}
// Empty test; behavior not supported because the URL connection client does not allow disabling connection reuse
@Override
public void connectionsAreNotReusedOn5xxErrors() throws Exception {
}
@Test
public void testGetResponseCodeNpeIsWrappedAsIo() throws Exception {
connectionInterceptor = safeFunction(connection -> new DelegateHttpURLConnection(connection) {
@Override
public int getResponseCode() {
throw new NullPointerException();
}
});
assertThatThrownBy(() -> testForResponseCode(HttpURLConnection.HTTP_OK))
.isInstanceOf(IOException.class)
.hasMessage("Unexpected NullPointerException when trying to read response from HttpURLConnection")
.hasCauseInstanceOf(NullPointerException.class);
}
private class DelegateHttpURLConnection extends HttpURLConnection {
private final HttpURLConnection delegate;
private DelegateHttpURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
@Override
public String getHeaderFieldKey(int n) {
return delegate.getHeaderFieldKey(n);
}
@Override
public void setFixedLengthStreamingMode(int contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setFixedLengthStreamingMode(long contentLength) {
delegate.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setChunkedStreamingMode(int chunklen) {
delegate.setChunkedStreamingMode(chunklen);
}
@Override
public String getHeaderField(int n) {
return delegate.getHeaderField(n);
}
@Override
public void setInstanceFollowRedirects(boolean followRedirects) {
delegate.setInstanceFollowRedirects(followRedirects);
}
@Override
public boolean getInstanceFollowRedirects() {
return delegate.getInstanceFollowRedirects();
}
@Override
public void setRequestMethod(String method) throws ProtocolException {
delegate.setRequestMethod(method);
}
@Override
public String getRequestMethod() {
return delegate.getRequestMethod();
}
@Override
public int getResponseCode() throws IOException {
return delegate.getResponseCode();
}
@Override
public String getResponseMessage() throws IOException {
return delegate.getResponseMessage();
}
@Override
public long getHeaderFieldDate(String name, long Default) {
return delegate.getHeaderFieldDate(name, Default);
}
@Override
public void disconnect() {
delegate.disconnect();
}
@Override
public boolean usingProxy() {
return delegate.usingProxy();
}
@Override
public Permission getPermission() throws IOException {
return delegate.getPermission();
}
@Override
public InputStream getErrorStream() {
return delegate.getErrorStream();
}
@Override
public void connect() throws IOException {
delegate.connect();
}
@Override
public void setConnectTimeout(int timeout) {
delegate.setConnectTimeout(timeout);
}
@Override
public int getConnectTimeout() {
return delegate.getConnectTimeout();
}
@Override
public void setReadTimeout(int timeout) {
delegate.setReadTimeout(timeout);
}
@Override
public int getReadTimeout() {
return delegate.getReadTimeout();
}
@Override
public URL getURL() {
return delegate.getURL();
}
@Override
public int getContentLength() {
return delegate.getContentLength();
}
@Override
public long getContentLengthLong() {
return delegate.getContentLengthLong();
}
@Override
public String getContentType() {
return delegate.getContentType();
}
@Override
public String getContentEncoding() {
return delegate.getContentEncoding();
}
@Override
public long getExpiration() {
return delegate.getExpiration();
}
@Override
public long getDate() {
return delegate.getDate();
}
@Override
public long getLastModified() {
return delegate.getLastModified();
}
@Override
public String getHeaderField(String name) {
return delegate.getHeaderField(name);
}
@Override
public Map<String, List<String>> getHeaderFields() {
return delegate.getHeaderFields();
}
@Override
public int getHeaderFieldInt(String name, int Default) {
return delegate.getHeaderFieldInt(name, Default);
}
@Override
public long getHeaderFieldLong(String name, long Default) {
return delegate.getHeaderFieldLong(name, Default);
}
@Override
public Object getContent() throws IOException {
return delegate.getContent();
}
@Override
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream();
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public void setDoInput(boolean doinput) {
delegate.setDoInput(doinput);
}
@Override
public boolean getDoInput() {
return delegate.getDoInput();
}
@Override
public void setDoOutput(boolean dooutput) {
delegate.setDoOutput(dooutput);
}
@Override
public boolean getDoOutput() {
return delegate.getDoOutput();
}
@Override
public void setAllowUserInteraction(boolean allowuserinteraction) {
delegate.setAllowUserInteraction(allowuserinteraction);
}
@Override
public boolean getAllowUserInteraction() {
return delegate.getAllowUserInteraction();
}
@Override
public void setUseCaches(boolean usecaches) {
delegate.setUseCaches(usecaches);
}
@Override
public boolean getUseCaches() {
return delegate.getUseCaches();
}
@Override
public void setIfModifiedSince(long ifmodifiedsince) {
delegate.setIfModifiedSince(ifmodifiedsince);
}
@Override
public long getIfModifiedSince() {
return delegate.getIfModifiedSince();
}
@Override
public boolean getDefaultUseCaches() {
return delegate.getDefaultUseCaches();
}
@Override
public void setDefaultUseCaches(boolean defaultusecaches) {
delegate.setDefaultUseCaches(defaultusecaches);
}
@Override
public void setRequestProperty(String key, String value) {
delegate.setRequestProperty(key, value);
}
@Override
public void addRequestProperty(String key, String value) {
delegate.addRequestProperty(key, value);
}
@Override
public String getRequestProperty(String key) {
return delegate.getRequestProperty(key);
}
@Override
public Map<String, List<String>> getRequestProperties() {
return delegate.getRequestProperties();
}
}
}
| 953 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/test/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClientWithProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.requestMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.mockito.ArgumentMatchers.anyString;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.matching.MatchResult;
import java.io.IOException;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.AttributeMap;
class UrlConnectionHttpClientWithProxyTest {
@RegisterExtension
static WireMockExtension httpsWm = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.configureStaticDsl(true)
.build();
@RegisterExtension
static WireMockExtension httpWm = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.proxyMode(true)
.build();
private SdkHttpClient client;
@Test
void Http_ProxyCallFrom_Https_Client_getsRejectedWith_404() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(404);
}
@Test
void Http_ProxyCallFromWithDenyList_HttpsClient_bypassesProxy_AndReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
Set<String> nonProxyHost = new HashSet<>();
nonProxyHost.add(httpWm.getRuntimeInfo().getHttpBaseUrl());
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.nonProxyHosts(nonProxyHost)
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
@Test
void emptyProxyConfig_Https_Client_byPassesProxy_dReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
httpsWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
WireMockRuntimeInfo wireMockRuntimeInfoHttp = httpsWm.getRuntimeInfo();
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder().build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttps_Client(client, wireMockRuntimeInfoHttp);
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
@Test
void http_ProxyCallFrom_Http_Client_isAcceptedByHttpProxy_AndReturns_OK() throws IOException {
httpWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
httpsWm.stubFor(requestMatching(
request -> MatchResult.of(request.getUrl().contains(anyString()))
).willReturn(aResponse()));
client = createHttpsClientForHttpServer(
ProxyConfiguration.builder()
.endpoint(URI.create(httpWm.getRuntimeInfo().getHttpBaseUrl()))
.build());
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttp_Client(client, httpWm.getRuntimeInfo());
Assertions.assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
}
private HttpExecuteResponse makeRequestWithHttps_Client(SdkHttpClient httpClient, WireMockRuntimeInfo wm) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost:" + wm.getHttpsPort())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
private HttpExecuteResponse makeRequestWithHttp_Client(SdkHttpClient httpClient, WireMockRuntimeInfo wm) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host(wm.getHttpBaseUrl())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
private SdkHttpClient createHttpsClientForHttpServer(ProxyConfiguration proxyConfiguration) {
UrlConnectionHttpClient.Builder builder =
UrlConnectionHttpClient.builder().proxyConfiguration(proxyConfiguration);
AttributeMap.Builder attributeMap = AttributeMap.builder();
attributeMap.put(TRUST_ALL_CERTIFICATES, true);
return builder.buildWithDefaults(attributeMap.build());
}
}
| 954 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/S3WithUrlHttpClientIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.AwsTestBase.CREDENTIALS_PROVIDER_CHAIN;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpHeaders;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class S3WithUrlHttpClientIntegrationTest {
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static final String BUCKET_NAME = "java-sdk-integ-" + System.currentTimeMillis();
private static final String KEY = "key";
private static final Region REGION = Region.US_WEST_2;
private static final CapturingInterceptor capturingInterceptor = new CapturingInterceptor();
private static final String SIGNED_PAYLOAD_HEADER_VALUE = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
private static final String UNSIGNED_PAYLOAD_HEADER_VALUE = "UNSIGNED-PAYLOAD";
private static S3Client s3;
private static S3Client s3Http;
/**
* Creates all the test resources for the tests.
*/
@BeforeAll
public static void createResources() throws Exception {
S3ClientBuilder s3ClientBuilder = S3Client.builder()
.region(REGION)
.httpClient(UrlConnectionHttpClient.builder().build())
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(new UserAgentVerifyingInterceptor())
.addExecutionInterceptor(capturingInterceptor));
s3 = s3ClientBuilder.build();
s3Http = s3ClientBuilder.endpointOverride(URI.create("http://s3.us-west-2.amazonaws.com"))
.build();
createBucket(BUCKET_NAME, REGION);
}
/**
* Releases all resources created in this test.
*/
@AfterAll
public static void tearDown() {
deleteObject(BUCKET_NAME, KEY);
deleteBucket(BUCKET_NAME);
}
@BeforeEach
public void methodSetup() {
capturingInterceptor.reset();
}
@Test
public void verifyPutObject() {
assertThat(objectCount(BUCKET_NAME)).isEqualTo(0);
s3.putObject(PutObjectRequest.builder().bucket(BUCKET_NAME).key(KEY).build(), RequestBody.fromString("foobar"));
assertThat(objectCount(BUCKET_NAME)).isEqualTo(1);
assertThat(getSha256Values()).contains(UNSIGNED_PAYLOAD_HEADER_VALUE);
}
@Test
public void verifyPutObject_httpCauses_payloadSigning() {
s3Http.putObject(PutObjectRequest.builder().bucket(BUCKET_NAME).key(KEY).build(), RequestBody.fromString("foobar"));
assertThat(getSha256Values()).contains(SIGNED_PAYLOAD_HEADER_VALUE);
}
private static void createBucket(String bucket, Region region) {
s3.createBucket(CreateBucketRequest
.builder()
.bucket(bucket)
.createBucketConfiguration(
CreateBucketConfiguration.builder()
.locationConstraint(region.id())
.build())
.build());
}
private static void deleteObject(String bucket, String key) {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder().bucket(bucket).key(key).build();
s3.deleteObject(deleteObjectRequest);
}
private static void deleteBucket(String bucket) {
DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);
}
private int objectCount(String bucket) {
ListObjectsV2Request listReq = ListObjectsV2Request.builder()
.bucket(bucket)
.build();
return s3.listObjectsV2(listReq).keyCount();
}
private List<String> getSha256Values() {
return capturingInterceptor.capturedRequests().stream()
.map(SdkHttpHeaders::headers)
.map(m -> m.getOrDefault("x-amz-content-sha256", Collections.emptyList()))
.flatMap(Collection::stream).collect(Collectors.toList());
}
private static final class UserAgentVerifyingInterceptor implements ExecutionInterceptor {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("io/sync");
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("http/UrlConnection");
}
}
private static class CapturingInterceptor implements ExecutionInterceptor {
private final List<SdkHttpRequest> capturedRequests = new ArrayList<>();
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
capturedRequests.add(context.httpRequest());
}
public void reset() {
capturedRequests.clear();
}
public List<SdkHttpRequest> capturedRequests() {
return capturedRequests;
}
}
}
| 955 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/UrlHttpConnectionS3IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.Waiter;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for S3 integration tests. Loads AWS credentials from a properties
* file and creates an S3 client for callers to use.
*/
public class UrlHttpConnectionS3IntegrationTestBase extends AwsTestBase {
protected static final Region DEFAULT_REGION = Region.US_WEST_2;
/**
* The S3 client for all tests to use.
*/
protected static S3Client s3;
/**
* Loads the AWS account info for the integration tests and creates an S3
* client for tests to use.
*/
@BeforeAll
public static void setUp() throws Exception {
s3 = s3ClientBuilder().build();
}
protected static S3ClientBuilder s3ClientBuilder() {
return S3Client.builder()
.httpClient(UrlConnectionHttpClient.create())
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
protected static void createBucket(String bucket) {
Waiter.run(() -> s3.createBucket(r -> r.bucket(bucket)))
.ignoringException(NoSuchBucketException.class)
.orFail();
s3.waiter().waitUntilBucketExists(r -> r.bucket(bucket));
}
protected static void deleteBucketAndAllContents(String bucketName) {
deleteBucketAndAllContents(s3, bucketName);
}
public static void deleteBucketAndAllContents(S3Client s3, String bucketName) {
try {
System.out.println("Deleting S3 bucket: " + bucketName);
ListObjectsResponse response = Waiter.run(() -> s3.listObjects(r -> r.bucket(bucketName)))
.ignoringException(NoSuchBucketException.class)
.orFail();
List<S3Object> objectListing = response.contents();
if (objectListing != null) {
while (true) {
for (Iterator<?> iterator = objectListing.iterator(); iterator.hasNext(); ) {
S3Object objectSummary = (S3Object) iterator.next();
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build());
}
if (response.isTruncated()) {
objectListing = s3.listObjects(ListObjectsRequest.builder()
.bucket(bucketName)
.marker(response.marker())
.build())
.contents();
} else {
break;
}
}
}
ListObjectVersionsResponse versions = s3
.listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build());
if (versions.deleteMarkers() != null) {
versions.deleteMarkers().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
if (versions.versions() != null) {
versions.versions().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());
} catch (Exception e) {
System.err.println("Failed to delete bucket: " + bucketName);
e.printStackTrace();
}
}
}
| 956 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/HeadObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class HeadObjectIntegrationTest extends UrlHttpConnectionS3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(HeadObjectIntegrationTest.class);
private static final String GZIPPED_KEY = "some-key";
@BeforeAll
public static void setupFixture() throws IOException {
createBucket(BUCKET);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write("Test".getBytes(StandardCharsets.UTF_8));
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(GZIPPED_KEY)
.contentEncoding("gzip")
.build(),
RequestBody.fromBytes(baos.toByteArray()));
}
@Test
public void syncClientSupportsGzippedObjects() {
HeadObjectResponse response = s3.headObject(r -> r.bucket(BUCKET).key(GZIPPED_KEY));
assertThat(response.contentEncoding()).isEqualTo("gzip");
}
@Test
public void syncClient_throwsRightException_withGzippedObjects() {
assertThrows(NoSuchKeyException.class,
() -> s3.headObject(r -> r.bucket(BUCKET + UUID.randomUUID()).key(GZIPPED_KEY)));
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
}
| 957 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/it/java/software/amazon/awssdk/http/urlconnection/EmptyFileS3IntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
public class EmptyFileS3IntegrationTest extends UrlHttpConnectionS3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(EmptyFileS3IntegrationTest.class);
@BeforeAll
public static void setup() {
createBucket(BUCKET);
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void s3EmptyFileGetAsBytesWorksWithoutChecksumValidationEnabled() {
try (S3Client s3 = s3ClientBuilder().serviceConfiguration(c -> c.checksumValidationEnabled(false))
.build()) {
s3.putObject(r -> r.bucket(BUCKET).key("x"), RequestBody.empty());
assertThat(s3.getObjectAsBytes(r -> r.bucket(BUCKET).key("x")).asUtf8String()).isEmpty();
}
}
@Test
public void s3EmptyFileContentLengthIsCorrectWithoutChecksumValidationEnabled() {
try (S3Client s3 = s3ClientBuilder().serviceConfiguration(c -> c.checksumValidationEnabled(false))
.build()) {
s3.putObject(r -> r.bucket(BUCKET).key("x"), RequestBody.empty());
assertThat(s3.getObject(r -> r.bucket(BUCKET).key("x")).response().contentLength()).isEqualTo(0);
}
}
}
| 958 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import java.net.HttpURLConnection;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An interface that, given a {@link URI} creates a new {@link HttpURLConnection}. This allows customization
* of the creation and configuration of the {@link HttpURLConnection}.
*/
@FunctionalInterface
@SdkPublicApi
public interface UrlConnectionFactory {
/**
* For the given {@link URI} create an {@link HttpURLConnection}.
* @param uri the {@link URI} of the request
* @return a {@link HttpURLConnection} to the given {@link URI}
*/
HttpURLConnection createConnection(URI uri);
}
| 959 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static software.amazon.awssdk.utils.StringUtils.isEmpty;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.ProxyEnvironmentSetting;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Proxy configuration for {@link UrlConnectionHttpClient}. This class is used to configure an HTTP proxy to be used by
* the {@link UrlConnectionHttpClient}.
*
* @see UrlConnectionHttpClient.Builder#proxyConfiguration(ProxyConfiguration)
*/
@SdkPublicApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final URI endpoint;
private final String username;
private final String password;
private final Set<String> nonProxyHosts;
private final String host;
private final int port;
private final String scheme;
private final boolean useSystemPropertyValues;
private final boolean useEnvironmentVariablesValues;
/**
* Initialize this configuration. Private to require use of {@link #builder()}.
*/
private ProxyConfiguration(DefaultClientProxyConfigurationBuilder builder) {
this.endpoint = builder.endpoint;
String resolvedScheme = resolveScheme(builder);
this.scheme = resolvedScheme;
ProxyConfigProvider proxyConfigProvider =
ProxyConfigProvider.fromSystemEnvironmentSettings(
builder.useSystemPropertyValues,
builder.useEnvironmentVariablesValues,
resolvedScheme);
this.username = resolveUsername(builder, proxyConfigProvider);
this.password = resolvePassword(builder, proxyConfigProvider);
this.nonProxyHosts = resolveNonProxyHosts(builder, proxyConfigProvider);
this.useSystemPropertyValues = builder.useSystemPropertyValues;
if (builder.endpoint != null) {
this.host = builder.endpoint.getHost();
this.port = builder.endpoint.getPort();
} else {
this.host = proxyConfigProvider != null ? proxyConfigProvider.host() : null;
this.port = proxyConfigProvider != null ? proxyConfigProvider.port() : 0;
}
this.useEnvironmentVariablesValues = builder.useEnvironmentVariablesValues;
}
private String resolveScheme(DefaultClientProxyConfigurationBuilder builder) {
if (endpoint != null) {
return endpoint.getScheme();
} else {
return builder.scheme;
}
}
private static String resolvePassword(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
if (builder.password != null || proxyConfigProvider == null) {
return builder.password;
}
return proxyConfigProvider.password().orElseGet(() -> builder.password);
}
private static Set<String> resolveNonProxyHosts(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
return builder.nonProxyHosts != null || proxyConfigProvider == null ? builder.nonProxyHosts :
proxyConfigProvider.nonProxyHosts();
}
private static String resolveUsername(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfigProvider) {
if (builder.username != null || proxyConfigProvider == null) {
return builder.username;
}
return proxyConfigProvider.userName().orElseGet(() -> builder.username);
}
/**
* Returns the proxy host name either from the configured endpoint or
* from the "http.proxyHost" system property if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*/
public String host() {
return host;
}
/**
* Returns the proxy port either from the configured endpoint or
* from the "http.proxyPort" system property if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*
* If no value is found in neither of the above options, the default value of 0 is returned.
*/
public int port() {
return port;
}
/**
* Returns the {@link URI#scheme} from the configured endpoint. Otherwise return null.
*/
public String scheme() {
return scheme;
}
/**
* The username to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String username() {
return username;
}
/**
* The password to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String password() {
return password;
}
/**
* The hosts that the client is allowed to access without going through the proxy.
*
* If the value is not set on the object, the value represent by "http.nonProxyHosts" system property is returned.
* If system property is also not set, an unmodifiable empty set is returned.
*
* @see Builder#nonProxyHosts(Set)
*/
public Set<String> nonProxyHosts() {
return Collections.unmodifiableSet(nonProxyHosts != null ? nonProxyHosts : Collections.emptySet());
}
@Override
public Builder toBuilder() {
return builder()
.endpoint(endpoint)
.username(username)
.password(password)
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(useSystemPropertyValues)
.scheme(scheme)
.useEnvironmentVariablesValues(useEnvironmentVariablesValues);
}
/**
* Create a {@link Builder}, used to create a {@link ProxyConfiguration}.
*/
public static Builder builder() {
return new DefaultClientProxyConfigurationBuilder();
}
@Override
public String toString() {
return ToString.builder("ProxyConfiguration")
.add("endpoint", endpoint)
.add("username", username)
.add("nonProxyHosts", nonProxyHosts)
.build();
}
public String resolveScheme() {
return endpoint != null ? endpoint.getScheme() : scheme;
}
/**
* A builder for {@link ProxyConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Configure the endpoint of the proxy server that the SDK should connect through. Currently, the endpoint is limited to
* a host and port. Any other URI components will result in an exception being raised.
*/
Builder endpoint(URI endpoint);
/**
* Configure the username to use when connecting through a proxy.
*/
Builder username(String username);
/**
* Configure the password to use when connecting through a proxy.
*/
Builder password(String password);
/**
* Configure the hosts that the client is allowed to access without going through the proxy.
*/
Builder nonProxyHosts(Set<String> nonProxyHosts);
/**
* Add a host that the client is allowed to access without going through the proxy.
*
* @see ProxyConfiguration#nonProxyHosts()
*/
Builder addNonProxyHost(String nonProxyHost);
/**
* Option whether to use system property values from {@link ProxySystemSetting} if any of the config options are missing.
* <p>
* This value is set to "true" by default which means SDK will automatically use system property values for options that
* are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this value to
* "false".It is important to note that when this property is set to "true," all proxy settings will exclusively originate
* from system properties, and no partial settings will be obtained from EnvironmentVariableValues
*/
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
/**
* Option whether to use environment variable values from {@link ProxyEnvironmentSetting} if any of the config options are
* missing. This value is set to "true" by default, which means SDK will automatically use environment variable values for
* options that are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this
* value to "false".It is important to note that when this property is set to "true," all proxy settings will exclusively
* originate from environment variableValues, and no partial settings will be obtained from SystemPropertyValues.
*
* @param useEnvironmentVariablesValues The option whether to use environment variable values
* @return This object for method chaining.
*/
Builder useEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
Builder scheme(String scheme);
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultClientProxyConfigurationBuilder implements Builder {
private URI endpoint;
private String username;
private String scheme = "http";
private String password;
private Set<String> nonProxyHosts;
private Boolean useSystemPropertyValues = Boolean.TRUE;
private Boolean useEnvironmentVariablesValues = Boolean.TRUE;
@Override
public Builder endpoint(URI endpoint) {
if (endpoint != null) {
Validate.isTrue(isEmpty(endpoint.getUserInfo()), "Proxy endpoint user info is not supported.");
Validate.isTrue(isEmpty(endpoint.getPath()), "Proxy endpoint path is not supported.");
Validate.isTrue(isEmpty(endpoint.getQuery()), "Proxy endpoint query is not supported.");
Validate.isTrue(isEmpty(endpoint.getFragment()), "Proxy endpoint fragment is not supported.");
}
this.endpoint = endpoint;
return this;
}
public void setEndpoint(URI endpoint) {
endpoint(endpoint);
}
@Override
public Builder username(String username) {
this.username = username;
return this;
}
public void setUsername(String username) {
username(username);
}
@Override
public Builder password(String password) {
this.password = password;
return this;
}
public void setPassword(String password) {
password(password);
}
@Override
public Builder nonProxyHosts(Set<String> nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts != null ? new HashSet<>(nonProxyHosts) : null;
return this;
}
@Override
public Builder addNonProxyHost(String nonProxyHost) {
if (this.nonProxyHosts == null) {
this.nonProxyHosts = new HashSet<>();
}
this.nonProxyHosts.add(nonProxyHost);
return this;
}
public void setNonProxyHosts(Set<String> nonProxyHosts) {
nonProxyHosts(nonProxyHosts);
}
@Override
public Builder useSystemPropertyValues(Boolean useSystemPropertyValues) {
this.useSystemPropertyValues = useSystemPropertyValues;
return this;
}
public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) {
useSystemPropertyValues(useSystemPropertyValues);
}
@Override
public Builder useEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues) {
this.useEnvironmentVariablesValues = useEnvironmentVariablesValues;
return this;
}
@Override
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
public void setScheme(String scheme) {
scheme(scheme);
}
public void setUseEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues) {
useEnvironmentVariablesValues(useEnvironmentVariablesValues);
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
}
| 960 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import static software.amazon.awssdk.http.Header.ACCEPT;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.HttpStatusFamily.CLIENT_ERROR;
import static software.amazon.awssdk.http.HttpStatusFamily.SERVER_ERROR;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkHttpClient} that uses {@link HttpURLConnection} to communicate with the service. This is the
* leanest synchronous client that optimizes for minimum dependencies and startup latency in exchange for having less
* functionality than other implementations.
*
* <p>See software.amazon.awssdk.http.apache.ApacheHttpClient for an alternative implementation.</p>
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class UrlConnectionHttpClient implements SdkHttpClient {
private static final Logger log = Logger.loggerFor(UrlConnectionHttpClient.class);
private static final String CLIENT_NAME = "UrlConnection";
private final AttributeMap options;
private final UrlConnectionFactory connectionFactory;
private final ProxyConfiguration proxyConfiguration;
private UrlConnectionHttpClient(AttributeMap options, UrlConnectionFactory connectionFactory, DefaultBuilder builder) {
this.options = options;
this.proxyConfiguration = builder != null ? builder.proxyConfiguration : null;
if (connectionFactory != null) {
this.connectionFactory = connectionFactory;
} else {
// Note: This socket factory MUST be reused between requests because the connection pool in the JVM is keyed by both
// URL and SSLSocketFactory. If the socket factory is not reused, connections will not be reused between requests.
SSLSocketFactory socketFactory = getSslContext(options).getSocketFactory();
this.connectionFactory = url -> createDefaultConnection(url, socketFactory);
}
}
private UrlConnectionHttpClient(AttributeMap options, UrlConnectionFactory connectionFactory) {
this(options, connectionFactory, null);
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link HttpURLConnection} client with the default properties
*
* @return an {@link UrlConnectionHttpClient}
*/
public static SdkHttpClient create() {
return new DefaultBuilder().build();
}
/**
* Use this method if you want to control the way a {@link HttpURLConnection} is created.
* This will ignore SDK defaults like {@link SdkHttpConfigurationOption#CONNECTION_TIMEOUT}
* and {@link SdkHttpConfigurationOption#READ_TIMEOUT}
* @param connectionFactory a function that, given a {@link URI} will create an {@link HttpURLConnection}
* @return an {@link UrlConnectionHttpClient}
*/
public static SdkHttpClient create(UrlConnectionFactory connectionFactory) {
return new UrlConnectionHttpClient(AttributeMap.empty(), connectionFactory);
}
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
HttpURLConnection connection = createAndConfigureConnection(request);
return new RequestCallable(connection, request);
}
@Override
public void close() {
// Nothing to close. The connections will be closed by closing the InputStreams.
}
@Override
public String clientName() {
return CLIENT_NAME;
}
private HttpURLConnection createAndConfigureConnection(HttpExecuteRequest request) {
SdkHttpRequest sdkHttpRequest = request.httpRequest();
HttpURLConnection connection = connectionFactory.createConnection(sdkHttpRequest.getUri());
sdkHttpRequest.forEachHeader((key, values) -> values.forEach(value -> connection.setRequestProperty(key, value)));
// connection.setRequestProperty("Transfer-Encoding", "chunked") does not work, i.e., property does not get set
if (sdkHttpRequest.matchingHeaders("Transfer-Encoding").contains("chunked")) {
connection.setChunkedStreamingMode(-1);
}
if (!sdkHttpRequest.firstMatchingHeader(ACCEPT).isPresent()) {
// Override Accept header because the default one in JDK does not comply with RFC 7231
// See: https://bugs.openjdk.org/browse/JDK-8163921
connection.setRequestProperty(ACCEPT, "*/*");
}
invokeSafely(() -> connection.setRequestMethod(sdkHttpRequest.method().name()));
if (request.contentStreamProvider().isPresent()) {
connection.setDoOutput(true);
}
// Disable following redirects since it breaks SDK error handling and matches Apache.
// See: https://github.com/aws/aws-sdk-java-v2/issues/975
connection.setInstanceFollowRedirects(false);
sdkHttpRequest.firstMatchingHeader(CONTENT_LENGTH).map(Long::parseLong)
.ifPresent(connection::setFixedLengthStreamingMode);
return connection;
}
private HttpURLConnection createDefaultConnection(URI uri, SSLSocketFactory socketFactory) {
Optional<Proxy> proxy = determineProxy(uri);
HttpURLConnection connection = !proxy.isPresent() ?
invokeSafely(() -> (HttpURLConnection) uri.toURL().openConnection())
:
invokeSafely(() -> (HttpURLConnection) uri.toURL().openConnection(proxy.get()));
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
if (options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
httpsConnection.setHostnameVerifier(NoOpHostNameVerifier.INSTANCE);
}
httpsConnection.setSSLSocketFactory(socketFactory);
}
if (proxy.isPresent() && shouldProxyAuthorize()) {
connection.addRequestProperty("proxy-authorization", String.format("Basic %s", encodedAuthToken(proxyConfiguration)));
}
connection.setConnectTimeout(saturatedCast(options.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT).toMillis()));
connection.setReadTimeout(saturatedCast(options.get(SdkHttpConfigurationOption.READ_TIMEOUT).toMillis()));
return connection;
}
/**
* If a proxy is configured with username+password, then set the proxy-authorization header to authorize ourselves with the
* proxy
*/
private static String encodedAuthToken(ProxyConfiguration proxyConfiguration) {
String authToken = String.format("%s:%s", proxyConfiguration.username(), proxyConfiguration.password());
return Base64.getEncoder().encodeToString(authToken.getBytes(StandardCharsets.UTF_8));
}
private boolean shouldProxyAuthorize() {
return this.proxyConfiguration != null
&& ! StringUtils.isEmpty(this.proxyConfiguration.username())
&& ! StringUtils.isEmpty(this.proxyConfiguration.password());
}
private Optional<Proxy> determineProxy(URI uri) {
if (isProxyEnabled() && isProxyHostIncluded(uri)) {
return Optional.of(
new Proxy(Proxy.Type.HTTP,
InetSocketAddress.createUnresolved(this.proxyConfiguration.host(), this.proxyConfiguration.port())));
}
return Optional.empty();
}
private boolean isProxyHostIncluded(URI uri) {
return this.proxyConfiguration.nonProxyHosts()
.stream()
.noneMatch(uri.getHost().toLowerCase(Locale.getDefault())::matches);
}
private boolean isProxyEnabled() {
return this.proxyConfiguration != null && this.proxyConfiguration.host() != null;
}
private SSLContext getSslContext(AttributeMap options) {
Validate.isTrue(options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) == null ||
!options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES),
"A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");
TrustManager[] trustManagers = null;
if (options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) != null) {
trustManagers = options.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER).trustManagers();
}
if (options.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
log.warn(() -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
+ "used for testing.");
trustManagers = new TrustManager[] { TrustAllManager.INSTANCE };
}
TlsKeyManagersProvider provider = this.options.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext context;
try {
context = SSLContext.getInstance("TLS");
context.init(keyManagers, trustManagers, null);
return context;
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
private static class RequestCallable implements ExecutableHttpRequest {
private final HttpURLConnection connection;
private final HttpExecuteRequest request;
/**
* Whether we encountered the 'bug' in the way the HttpURLConnection handles 'Expect: 100-continue' cases. See
* {@link #getAndHandle100Bug} for more information.
*/
private boolean expect100BugEncountered = false;
/**
* Result cache for {@link #responseHasNoContent()}.
*/
private Boolean responseHasNoContent;
private RequestCallable(HttpURLConnection connection, HttpExecuteRequest request) {
this.connection = connection;
this.request = request;
}
@Override
public HttpExecuteResponse call() throws IOException {
connection.connect();
Optional<ContentStreamProvider> requestContent = request.contentStreamProvider();
if (requestContent.isPresent()) {
Optional<OutputStream> outputStream = tryGetOutputStream();
if (outputStream.isPresent()) {
IoUtils.copy(requestContent.get().newStream(), outputStream.get());
}
}
int responseCode = getResponseCodeSafely(connection);
boolean isErrorResponse = HttpStatusFamily.of(responseCode).isOneOf(CLIENT_ERROR, SERVER_ERROR);
Optional<InputStream> responseContent = isErrorResponse ? tryGetErrorStream() : tryGetInputStream();
AbortableInputStream responseBody = responseContent.map(AbortableInputStream::create).orElse(null);
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(responseCode)
.statusText(connection.getResponseMessage())
// TODO: Don't ignore abort?
.headers(extractHeaders(connection))
.build())
.responseBody(responseBody)
.build();
}
private Optional<OutputStream> tryGetOutputStream() {
return getAndHandle100Bug(() -> invokeSafely(connection::getOutputStream), false);
}
private Optional<InputStream> tryGetInputStream() {
return responseHasNoContent()
? Optional.empty()
: getAndHandle100Bug(() -> invokeSafely(connection::getInputStream), true);
}
private Optional<InputStream> tryGetErrorStream() {
InputStream result = invokeSafely(connection::getErrorStream);
if (result == null && expect100BugEncountered) {
log.debug(() -> "The response payload has been dropped because of a limitation of the JDK's URL Connection "
+ "HTTP client, resulting in a less descriptive SDK exception error message. Using "
+ "the Apache HTTP client removes this limitation.");
}
return Optional.ofNullable(result);
}
/**
* This handles a bug in {@link HttpURLConnection#getOutputStream()} and {@link HttpURLConnection#getInputStream()}
* where these methods will throw a ProtocolException if we sent an "Expect: 100-continue" header, and the
* service responds with something other than a 100.
*
* HttpUrlConnection still gives us access to the response code and headers when this bug is encountered, so our
* handling of the bug is:
* <ol>
* <li>If the service returned a response status or content length that indicates there was no response payload,
* we ignore that we couldn't read the response payload, and just return the response with what we have.</li>
* <li>If the service returned a payload and we can't read it because of the bug, we throw an exception for
* non-failure cases (2xx, 3xx) or log and return the response without the payload for failure cases (4xx or 5xx)
* .</li>
* </ol>
*/
private <T> Optional<T> getAndHandle100Bug(Supplier<T> supplier, boolean failOn100Bug) {
try {
return Optional.ofNullable(supplier.get());
} catch (RuntimeException e) {
if (!exceptionCausedBy100HandlingBug(e)) {
throw e;
}
if (responseHasNoContent()) {
return Optional.empty();
}
expect100BugEncountered = true;
if (!failOn100Bug) {
return Optional.empty();
}
int responseCode = invokeSafely(connection::getResponseCode);
String message = "Unable to read response payload, because service returned response code "
+ responseCode + " to an Expect: 100-continue request. Using another HTTP client "
+ "implementation (e.g. Apache) removes this limitation.";
throw new UncheckedIOException(new IOException(message, e));
}
}
private boolean exceptionCausedBy100HandlingBug(RuntimeException e) {
return requestWasExpect100Continue() &&
e.getMessage() != null &&
e.getMessage().startsWith("java.net.ProtocolException: Server rejected operation");
}
private Boolean requestWasExpect100Continue() {
return request.httpRequest()
.firstMatchingHeader("Expect")
.map(expect -> expect.equalsIgnoreCase("100-continue"))
.orElse(false);
}
private boolean responseHasNoContent() {
// We cannot account for chunked encoded responses, because we only have access to headers and response code here,
// so we assume chunked encoded responses DO have content.
if (responseHasNoContent == null) {
responseHasNoContent = responseNeverHasPayload(invokeSafely(connection::getResponseCode)) ||
Objects.equals(connection.getHeaderField("Content-Length"), "0") ||
Objects.equals(connection.getRequestMethod(), "HEAD");
}
return responseHasNoContent;
}
private boolean responseNeverHasPayload(int responseCode) {
return responseCode == 204 || responseCode == 304 || (responseCode >= 100 && responseCode < 200);
}
/**
* {@link sun.net.www.protocol.http.HttpURLConnection#getInputStream0()} has been observed to intermittently throw
* {@link NullPointerException}s for reasons that still require further investigation, but are assumed to be due to a
* bug in the JDK. Propagating such NPEs is confusing for users and are not subject to being retried on by the default
* retry policy configuration, so instead we bias towards propagating these as {@link IOException}s.
* <p>
* TODO: Determine precise root cause of intermittent NPEs, submit JDK bug report if applicable, and consider applying
* this behavior only on unpatched JVM runtime versions.
*/
private static int getResponseCodeSafely(HttpURLConnection connection) throws IOException {
Validate.paramNotNull(connection, "connection");
try {
return connection.getResponseCode();
} catch (NullPointerException e) {
throw new IOException("Unexpected NullPointerException when trying to read response from HttpURLConnection", e);
}
}
private Map<String, List<String>> extractHeaders(HttpURLConnection response) {
return response.getHeaderFields().entrySet().stream()
.filter(e -> e.getKey() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Override
public void abort() {
connection.disconnect();
}
}
/**
* A builder for an instance of {@link SdkHttpClient} that uses JDKs build-in {@link java.net.URLConnection} HTTP
* implementation. A builder can be created via {@link #builder()}.
*
* <pre class="brush: java">
* SdkHttpClient httpClient = UrlConnectionHttpClient.builder()
* .socketTimeout(Duration.ofSeconds(10))
* .connectionTimeout(Duration.ofSeconds(1))
* .build();
* </pre>
*/
public interface Builder extends SdkHttpClient.Builder<UrlConnectionHttpClient.Builder> {
/**
* The amount of time to wait for data to be transferred over an established, open connection before the connection is
* timed out. A duration of 0 means infinity, and is not recommended.
*/
Builder socketTimeout(Duration socketTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out. A duration of 0
* means infinity, and is not recommended.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* Configure the {@link TlsKeyManagersProvider} that will provide the {@link javax.net.ssl.KeyManager}s to use
* when constructing the SSL context.
*/
Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider);
/**
* Configure the {@link TlsTrustManagersProvider} that will provide the {@link javax.net.ssl.TrustManager}s to use
* when constructing the SSL context.
*/
Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider);
/**
* Configuration that defines how to communicate via an HTTP proxy.
* @param proxyConfiguration proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Sets the http proxy configuration to use for this client.
*
* @param proxyConfigurationBuilderConsumer The consumer of the proxy configuration builder object.
* @return the builder for method chaining.
*/
Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer);
}
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private ProxyConfiguration proxyConfiguration;
private DefaultBuilder() {
}
/**
* Sets the read timeout to a specified timeout. A timeout of zero is interpreted as an infinite timeout.
*
* @param socketTimeout the timeout as a {@link Duration}
* @return this object for method chaining
*/
@Override
public Builder socketTimeout(Duration socketTimeout) {
standardOptions.put(SdkHttpConfigurationOption.READ_TIMEOUT, socketTimeout);
return this;
}
public void setSocketTimeout(Duration socketTimeout) {
socketTimeout(socketTimeout);
}
/**
* Sets the connect timeout to a specified timeout. A timeout of zero is interpreted as an infinite timeout.
*
* @param connectionTimeout the timeout as a {@link Duration}
* @return this object for method chaining
*/
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
@Override
public Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER, tlsKeyManagersProvider);
return this;
}
public void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
tlsKeyManagersProvider(tlsKeyManagersProvider);
}
@Override
public Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER, tlsTrustManagersProvider);
return this;
}
public void setTlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
tlsTrustManagersProvider(tlsTrustManagersProvider);
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
@Override
public Builder proxyConfiguration(Consumer<ProxyConfiguration.Builder> proxyConfigurationBuilderConsumer) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
proxyConfigurationBuilderConsumer.accept(builder);
return proxyConfiguration(builder.build());
}
public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
proxyConfiguration(proxyConfiguration);
}
/**
* Used by the SDK to create a {@link SdkHttpClient} with service-default values if no other values have been configured
*
* @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in
* {@link SdkHttpConfigurationOption}.
* @return an instance of {@link SdkHttpClient}
*/
@Override
public SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
return new UrlConnectionHttpClient(standardOptions.build()
.merge(serviceDefaults)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS),
null, this);
}
}
private static class NoOpHostNameVerifier implements HostnameVerifier {
static final NoOpHostNameVerifier INSTANCE = new NoOpHostNameVerifier();
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
/**
* Insecure trust manager to trust all certs. Should only be used for testing.
*/
private static class TrustAllManager implements X509TrustManager {
private static final TrustAllManager INSTANCE = new TrustAllManager();
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
log.debug(() -> "Accepting a server certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
| 961 |
0 | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/url-connection-client/src/main/java/software/amazon/awssdk/http/urlconnection/UrlConnectionSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.urlconnection;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpService;
/**
* Service binding for the URL Connection implementation.
*/
@SdkPublicApi
public class UrlConnectionSdkHttpService implements SdkHttpService {
@Override
public SdkHttpClient.Builder createHttpClientBuilder() {
return UrlConnectionHttpClient.builder();
}
}
| 962 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* @see ApacheHttpClientWireMockTest
*/
public class ApacheHttpClientTest {
@AfterEach
public void cleanup() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
}
@Test
public void connectionReaperCanBeManuallyEnabled() {
ApacheHttpClient.builder()
.useIdleConnectionReaper(true)
.build()
.close();
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesEnabled() {
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1234");
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesDisabled() {
System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1234");
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.useSystemPropertyValues(Boolean.FALSE)
.build();
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class))
.build();
}
@Test
public void credentialProviderCantBeUsedWithProxyCredentials() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.username("foo")
.password("bar")
.build();
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void credentialProviderCantBeUsedWithProxyCredentials_SystemProperties() {
System.setProperty("http.proxyUser", "foo");
System.setProperty("http.proxyPassword", "bar");
assertThatThrownBy(() -> {
ApacheHttpClient.builder()
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void credentialProviderCanBeUsedWithProxy() {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.build();
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.credentialsProvider(Mockito.mock(CredentialsProvider.class))
.build();
}
@Test
public void dnsResolverCanBeUsed() {
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("my.host.com")) {
return new InetAddress[] { InetAddress.getByName("127.0.0.1") };
} else {
return super.resolve(host);
}
}
};
ApacheHttpClient.builder()
.dnsResolver(dnsResolver)
.build()
.close();
}
}
| 963 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientTestSuite;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class ApacheHttpClientWireMockTest extends SdkHttpClientTestSuite {
@Rule
public WireMockRule mockProxyServer = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort());
@Mock
private ConnectionManagerAwareHttpClient httpClient;
@Mock
private HttpClientConnectionManager connectionManager;
@Override
protected SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options) {
ApacheHttpClient.Builder builder = ApacheHttpClient.builder();
AttributeMap.Builder attributeMap = AttributeMap.builder();
if (options.tlsTrustManagersProvider() != null) {
builder.tlsTrustManagersProvider(options.tlsTrustManagersProvider());
}
if (options.trustAll()) {
attributeMap.put(TRUST_ALL_CERTIFICATES, options.trustAll());
}
return builder.buildWithDefaults(attributeMap.build());
}
@Test
public void closeClient_shouldCloseUnderlyingResources() {
ApacheHttpClient client = new ApacheHttpClient(httpClient, ApacheHttpRequestConfig.builder().build(), AttributeMap.empty());
when(httpClient.getHttpClientConnectionManager()).thenReturn(connectionManager);
client.close();
verify(connectionManager).shutdown();
}
@Test
public void routePlannerIsInvoked() throws Exception {
mockProxyServer.resetToDefaultMappings();
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.willReturn(aResponse().proxiedFrom("http://localhost:" + mockServer.port()))
.build());
SdkHttpClient client = ApacheHttpClient.builder()
.httpRoutePlanner(
(host, request, context) ->
new HttpRoute(
new HttpHost("localhost", mockProxyServer.httpsPort(), "https")
)
)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
testForResponseCodeUsingHttps(client, HttpURLConnection.HTTP_OK);
mockProxyServer.verify(1, RequestPatternBuilder.allRequests());
}
@Test
public void credentialPlannerIsInvoked() throws Exception {
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.willReturn(aResponse()
.withHeader("WWW-Authenticate", "Basic realm=\"proxy server\"")
.withStatus(401))
.build());
mockProxyServer.addStubMapping(WireMock.any(urlPathEqualTo("/"))
.withBasicAuth("foo", "bar")
.willReturn(aResponse()
.proxiedFrom("http://localhost:" + mockServer.port()))
.build());
SdkHttpClient client = ApacheHttpClient.builder()
.credentialsProvider(new CredentialsProvider() {
@Override
public void setCredentials(AuthScope authScope, Credentials credentials) {
}
@Override
public Credentials getCredentials(AuthScope authScope) {
return new UsernamePasswordCredentials("foo", "bar");
}
@Override
public void clear() {
}
})
.httpRoutePlanner(
(host, request, context) ->
new HttpRoute(
new HttpHost("localhost", mockProxyServer.httpsPort(), "https")
)
)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
testForResponseCodeUsingHttps(client, HttpURLConnection.HTTP_OK);
mockProxyServer.verify(2, RequestPatternBuilder.allRequests());
}
@Test
public void overrideDnsResolver_WithDnsMatchingResolver_successful() throws Exception {
overrideDnsResolver("magic.local.host");
}
@Test(expected = UnknownHostException.class)
public void overrideDnsResolver_WithUnknownHost_throwsException() throws Exception {
overrideDnsResolver("sad.local.host");
}
@Test
public void overrideDnsResolver_WithLocalhost_successful() throws Exception {
overrideDnsResolver("localhost");
}
@Test
public void explicitNullDnsResolver_WithLocalhost_successful() throws Exception {
overrideDnsResolver("localhost", true);
}
private void overrideDnsResolver(String hostName) throws IOException {
overrideDnsResolver(hostName, false);
}
private void overrideDnsResolver(String hostName, boolean nullifyResolver) throws IOException {
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("magic.local.host")) {
return new InetAddress[] { InetAddress.getByName("127.0.0.1") };
} else {
return super.resolve(host);
}
}
};
if (nullifyResolver) {
dnsResolver = null;
}
SdkHttpClient client = ApacheHttpClient.builder()
.dnsResolver(dnsResolver)
.buildWithDefaults(AttributeMap.builder()
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
.build());
mockProxyServer.resetToDefaultMappings();
mockProxyServer.stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK)));
URI uri = URI.create("https://" + hostName + ":" + mockProxyServer.httpsPort());
SdkHttpFullRequest req = SdkHttpFullRequest.builder()
.uri(uri)
.method(SdkHttpMethod.POST)
.putHeader("Host", uri.getHost())
.build();
client.prepareRequest(HttpExecuteRequest.builder()
.request(req)
.contentStreamProvider(req.contentStreamProvider().orElse(null))
.build())
.call();
mockProxyServer.verify(1, RequestPatternBuilder.allRequests());
}
}
| 964 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpProxyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import software.amazon.awssdk.http.HttpProxyTestSuite;
import software.amazon.awssdk.http.proxy.TestProxySetting;
public class ApacheHttpProxyTest extends HttpProxyTestSuite {
@Override
protected void assertProxyConfiguration(TestProxySetting userSetProxySettings,
TestProxySetting expectedProxySettings,
Boolean useSystemProperty,
Boolean useEnvironmentVariable,
String protocol) {
ProxyConfiguration.Builder builder = ProxyConfiguration.builder();
if (userSetProxySettings != null) {
String hostName = userSetProxySettings.getHost();
Integer portNumber = userSetProxySettings.getPort();
String userName = userSetProxySettings.getUserName();
String password = userSetProxySettings.getPassword();
Set<String> nonProxyHosts = userSetProxySettings.getNonProxyHosts();
if (hostName != null && portNumber != null) {
builder.endpoint(URI.create(String.format("%s://%s:%d", protocol, hostName, portNumber)));
}
if (userName != null) {
builder.username(userName);
}
if (password != null) {
builder.password(password);
}
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
builder.nonProxyHosts(nonProxyHosts);
}
}
if (!"http".equals(protocol)) {
builder.scheme(protocol);
}
if (useSystemProperty != null) {
builder.useSystemPropertyValues(useSystemProperty);
}
if (useEnvironmentVariable != null) {
builder.useEnvironmentVariableValues(useEnvironmentVariable);
}
ProxyConfiguration proxyConfiguration = builder.build();
assertThat(proxyConfiguration.host()).isEqualTo(expectedProxySettings.getHost());
assertThat(proxyConfiguration.port()).isEqualTo(expectedProxySettings.getPort());
assertThat(proxyConfiguration.username()).isEqualTo(expectedProxySettings.getUserName());
assertThat(proxyConfiguration.password()).isEqualTo(expectedProxySettings.getPassword());
assertThat(proxyConfiguration.nonProxyHosts()).isEqualTo(expectedProxySettings.getNonProxyHosts());
}
}
| 965 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheMetricsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.HttpMetric.CONCURRENCY_ACQUIRE_DURATION;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
public class ApacheMetricsTest {
private static WireMockServer wireMockServer;
private SdkHttpClient client;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUp() throws IOException {
wireMockServer = new WireMockServer();
wireMockServer.start();
}
@Before
public void methodSetup() {
wireMockServer.stubFor(any(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("{}")));
}
@AfterClass
public static void teardown() throws IOException {
wireMockServer.stop();
}
@After
public void methodTeardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void concurrencyAcquireDurationIsRecorded() throws IOException {
client = ApacheHttpClient.create();
MetricCollector collector = MetricCollector.create("test");
makeRequestWithMetrics(client, collector);
MetricCollection collection = collector.collect();
assertThat(collection.metricValues(CONCURRENCY_ACQUIRE_DURATION)).isNotEmpty();
}
private HttpExecuteResponse makeRequestWithMetrics(SdkHttpClient httpClient, MetricCollector metricCollector) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost:" + wireMockServer.port())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.metricCollector(metricCollector)
.build();
return httpClient.prepareRequest(request).call();
}
}
| 966 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheHttpClientDefaultWireMockTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpClientDefaultTestSuite;
public class ApacheHttpClientDefaultWireMockTest extends SdkHttpClientDefaultTestSuite {
@Override
protected SdkHttpClient createSdkHttpClient() {
return ApacheHttpClient.create();
}
}
| 967 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ClientTlsAuthTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
abstract class ClientTlsAuthTestBase {
protected static final String STORE_PASSWORD = "password";
protected static final String CLIENT_STORE_TYPE = "pkcs12";
protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/apache/server-keystore";
protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/apache/client1.p12";
protected static Path tempDir;
protected static Path serverKeyStore;
protected static Path clientKeyStore;
@BeforeAll
public static void setUp() throws IOException {
tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName());
copyCertsToTmpDir();
}
@AfterAll
public static void teardown() throws IOException {
Files.deleteIfExists(serverKeyStore);
Files.deleteIfExists(clientKeyStore);
Files.deleteIfExists(tempDir);
}
private static void copyCertsToTmpDir() throws IOException {
InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE);
Path sks = copyToTmpDir(sksStream, "server-keystore");
InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE);
Path cks = copyToTmpDir(cksStream, "client1.p12");
serverKeyStore = sks;
clientKeyStore = cks;
}
private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException {
Path dst = tempDir.resolve(name);
Files.copy(srcStream, dst);
return dst;
}
}
| 968 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/MetricReportingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import java.io.IOException;
import java.time.Duration;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
@RunWith(MockitoJUnitRunner.class)
public class MetricReportingTest {
@Mock
public ConnectionManagerAwareHttpClient mockHttpClient;
@Mock
public PoolingHttpClientConnectionManager cm;
@Before
public void methodSetup() throws IOException {
when(mockHttpClient.execute(any(HttpUriRequest.class), any(HttpContext.class)))
.thenReturn(new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"));
when(mockHttpClient.getHttpClientConnectionManager()).thenReturn(cm);
PoolStats stats = new PoolStats(1, 2, 3, 4);
when(cm.getTotalStats()).thenReturn(stats);
}
@Test
public void prepareRequest_callableCalled_metricsReported() throws IOException {
ApacheHttpClient client = newClient();
MetricCollector collector = MetricCollector.create("test");
HttpExecuteRequest executeRequest = newRequest(collector);
client.prepareRequest(executeRequest).call();
MetricCollection collected = collector.collect();
assertThat(collected.metricValues(HTTP_CLIENT_NAME)).containsExactly("Apache");
assertThat(collected.metricValues(LEASED_CONCURRENCY)).containsExactly(1);
assertThat(collected.metricValues(PENDING_CONCURRENCY_ACQUIRES)).containsExactly(2);
assertThat(collected.metricValues(AVAILABLE_CONCURRENCY)).containsExactly(3);
assertThat(collected.metricValues(MAX_CONCURRENCY)).containsExactly(4);
}
@Test
public void prepareRequest_connectionManagerNotPooling_callableCalled_metricsReported() throws IOException {
ApacheHttpClient client = newClient();
when(mockHttpClient.getHttpClientConnectionManager()).thenReturn(mock(HttpClientConnectionManager.class));
MetricCollector collector = MetricCollector.create("test");
HttpExecuteRequest executeRequest = newRequest(collector);
client.prepareRequest(executeRequest).call();
MetricCollection collected = collector.collect();
assertThat(collected.metricValues(HTTP_CLIENT_NAME)).containsExactly("Apache");
assertThat(collected.metricValues(LEASED_CONCURRENCY)).isEmpty();
assertThat(collected.metricValues(PENDING_CONCURRENCY_ACQUIRES)).isEmpty();
assertThat(collected.metricValues(AVAILABLE_CONCURRENCY)).isEmpty();
assertThat(collected.metricValues(MAX_CONCURRENCY)).isEmpty();
}
private ApacheHttpClient newClient() {
ApacheHttpRequestConfig config = ApacheHttpRequestConfig.builder()
.connectionAcquireTimeout(Duration.ofDays(1))
.connectionTimeout(Duration.ofDays(1))
.socketTimeout(Duration.ofDays(1))
.proxyConfiguration(ProxyConfiguration.builder().build())
.build();
return new ApacheHttpClient(mockHttpClient, config, AttributeMap.empty());
}
private HttpExecuteRequest newRequest(MetricCollector collector) {
final SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.HEAD)
.host("amazonaws.com")
.protocol("https")
.build();
HttpExecuteRequest executeRequest = HttpExecuteRequest.builder()
.request(sdkRequest)
.metricCollector(collector)
.build();
return executeRequest;
}
}
| 969 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class ProxyConfigurationTest {
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@BeforeEach
public void setup() {
clearProxyProperties();
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@AfterAll
public static void cleanup() {
clearProxyProperties();
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@Test
void testEndpointValues_Http_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", Integer.toString(port));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", "http://UserOne:passwordSecret@bar.com:555/");
ProxyConfiguration config = ProxyConfiguration.builder().useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_Http_EnvironmentVariableEnabled() {
String host = "bar.com";
int port = 7777;
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", Integer.toString(8888));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", String.format("http://%s:%d/", host, port));
ProxyConfiguration config =
ProxyConfiguration.builder().useSystemPropertyValues(false).useEnvironmentVariableValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testEndpointValues_Https_SystemPropertyEnabled() {
String host = "foo.com";
int port = 7777;
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", Integer.toString(port));
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("https://foo.com:7777"))
.useSystemPropertyValues(true).build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void testEndpointValues_Https_EnvironmentVariableEnabled() {
String host = "bar.com";
int port = 7777;
System.setProperty("https.proxyHost", "foo.com");
System.setProperty("https.proxyPort", Integer.toString(8888));
ENVIRONMENT_VARIABLE_HELPER.set("http_proxy", String.format("http://%s:%d/", "foo.com", 8888));
ENVIRONMENT_VARIABLE_HELPER.set("https_proxy", String.format("http://%s:%d/", host, port));
ProxyConfiguration config =
ProxyConfiguration.builder()
.scheme("https")
.useSystemPropertyValues(false)
.useEnvironmentVariableValues(true)
.build();
assertThat(config.host()).isEqualTo(host);
assertThat(config.port()).isEqualTo(port);
assertThat(config.scheme()).isEqualTo("https");
}
@Test
void testEndpointValues_SystemPropertyDisabled() {
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.scheme()).isEqualTo("http");
}
@Test
void testProxyConfigurationWithSystemPropertyDisabled() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:1234"))
.nonProxyHosts(nonProxyHosts)
.useSystemPropertyValues(Boolean.FALSE)
.build();
assertThat(config.host()).isEqualTo("localhost");
assertThat(config.port()).isEqualTo(1234);
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.username()).isNull();
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled_Http() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("http.proxyHost", "foo.com");
System.setProperty("http.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("http.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithSystemPropertyEnabled_Https() throws Exception {
Set<String> nonProxyHosts = new HashSet<>();
nonProxyHosts.add("foo.com");
// system property should not be used
System.setProperty("https.proxyHost", "foo.com");
System.setProperty("https.proxyPort", "5555");
System.setProperty("http.nonProxyHosts", "bar.com");
System.setProperty("https.proxyUser", "user");
ProxyConfiguration config = ProxyConfiguration.builder()
.endpoint(URI.create("https://foo.com:1234"))
.nonProxyHosts(nonProxyHosts)
.build();
assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHosts);
assertThat(config.host()).isEqualTo("foo.com");
assertThat(config.username()).isEqualTo("user");
}
@Test
void testProxyConfigurationWithoutNonProxyHosts_toBuilder_shouldNotThrowNPE() {
ProxyConfiguration proxyConfiguration =
ProxyConfiguration.builder()
.endpoint(URI.create("http://localhost:4321"))
.username("username")
.password("password")
.build();
assertThat(proxyConfiguration.toBuilder()).isNotNull();
}
private static void clearProxyProperties() {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("http.nonProxyHosts");
System.clearProperty("http.proxyUser");
System.clearProperty("http.proxyPassword");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
System.clearProperty("https.proxyUser");
System.clearProperty("https.proxyPassword");
}
}
| 970 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/ApacheClientTlsAuthTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.instanceOf;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD;
import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE;
import com.github.tomakehurst.wiremock.WireMockServer;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import org.apache.http.NoHttpResponseException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import software.amazon.awssdk.http.FileStoreTlsKeyManagersProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactory;
import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider;
/**
* Tests to ensure that {@link ApacheHttpClient} can properly support TLS
* client authentication.
*/
public class ApacheClientTlsAuthTest extends ClientTlsAuthTestBase {
private static WireMockServer wireMockServer;
private static TlsKeyManagersProvider keyManagersProvider;
private SdkHttpClient client;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUp() throws IOException {
ClientTlsAuthTestBase.setUp();
// Will be used by both client and server to trust the self-signed
// cert they present to each other
System.setProperty("javax.net.ssl.trustStore", serverKeyStore.toAbsolutePath().toString());
System.setProperty("javax.net.ssl.trustStorePassword", STORE_PASSWORD);
System.setProperty("javax.net.ssl.trustStoreType", "jks");
wireMockServer = new WireMockServer(wireMockConfig()
.dynamicHttpsPort()
.needClientAuth(true)
.keystorePath(serverKeyStore.toAbsolutePath().toString())
.keystorePassword(STORE_PASSWORD)
);
wireMockServer.start();
keyManagersProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD);
}
@Before
public void methodSetup() {
wireMockServer.stubFor(any(urlMatching(".*")).willReturn(aResponse().withStatus(200).withBody("{}")));
}
@AfterClass
public static void teardown() throws IOException {
wireMockServer.stop();
System.clearProperty("javax.net.ssl.trustStore");
System.clearProperty("javax.net.ssl.trustStorePassword");
System.clearProperty("javax.net.ssl.trustStoreType");
ClientTlsAuthTestBase.teardown();
}
@After
public void methodTeardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void canMakeHttpsRequestWhenKeyProviderConfigured() throws IOException {
client = ApacheHttpClient.builder()
.tlsKeyManagersProvider(keyManagersProvider)
.build();
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
assertThat(httpExecuteResponse.httpResponse().isSuccessful()).isTrue();
}
@Test
public void requestFailsWhenKeyProviderNotConfigured() throws IOException {
thrown.expect(anyOf(instanceOf(NoHttpResponseException.class), instanceOf(SSLException.class), instanceOf(SocketException.class)));
client = ApacheHttpClient.builder().tlsKeyManagersProvider(NoneTlsKeyManagersProvider.getInstance()).build();
makeRequestWithHttpClient(client);
}
@Test
public void authenticatesWithTlsProxy() throws IOException {
ProxyConfiguration proxyConfig = ProxyConfiguration.builder()
.endpoint(URI.create("https://localhost:" + wireMockServer.httpsPort()))
.build();
client = ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig)
.tlsKeyManagersProvider(keyManagersProvider)
.build();
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
// WireMock doesn't mock 'CONNECT' methods and will return a 404 for this
assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(404);
}
@Test
public void defaultTlsKeyManagersProviderIsSystemPropertyProvider() throws IOException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
client = ApacheHttpClient.builder().build();
try {
makeRequestWithHttpClient(client);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
}
@Test
public void defaultTlsKeyManagersProviderIsSystemPropertyProvider_explicitlySetToNull() throws IOException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
client = ApacheHttpClient.builder().tlsKeyManagersProvider(null).build();
try {
makeRequestWithHttpClient(client);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
}
@Test
public void build_notSettingSocketFactory_configuresClientWithDefaultSocketFactory() throws IOException,
NoSuchAlgorithmException,
KeyManagementException {
System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString());
System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE);
System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD);
TlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore,
CLIENT_STORE_TYPE,
STORE_PASSWORD);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keyManagers, null, null);
ConnectionSocketFactory socketFactory = new SdkTlsSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
ConnectionSocketFactory socketFactoryMock = Mockito.spy(socketFactory);
client = ApacheHttpClient.builder().build();
try {
HttpExecuteResponse httpExecuteResponse = makeRequestWithHttpClient(client);
assertThat(httpExecuteResponse.httpResponse().statusCode()).isEqualTo(200);
} finally {
System.clearProperty(SSL_KEY_STORE.property());
System.clearProperty(SSL_KEY_STORE_TYPE.property());
System.clearProperty(SSL_KEY_STORE_PASSWORD.property());
}
Mockito.verifyNoInteractions(socketFactoryMock);
}
@Test
public void build_settingCustomSocketFactory_configuresClientWithGivenSocketFactory() throws IOException,
NoSuchAlgorithmException,
KeyManagementException {
TlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore,
CLIENT_STORE_TYPE,
STORE_PASSWORD);
KeyManager[] keyManagers = provider.keyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keyManagers, null, null);
ConnectionSocketFactory socketFactory = new SdkTlsSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
ConnectionSocketFactory socketFactoryMock = Mockito.spy(socketFactory);
client = ApacheHttpClient.builder()
.socketFactory(socketFactoryMock)
.build();
makeRequestWithHttpClient(client);
Mockito.verify(socketFactoryMock).createSocket(Mockito.any());
}
private HttpExecuteResponse makeRequestWithHttpClient(SdkHttpClient httpClient) throws IOException {
SdkHttpRequest httpRequest = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost:" + wireMockServer.httpsPort())
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(httpRequest)
.build();
return httpClient.prepareRequest(request).call();
}
}
| 971 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/SdkProxyRoutePlannerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link SdkProxyRoutePlanner}.
*/
public class SdkProxyRoutePlannerTest {
private static final HttpHost S3_HOST = new HttpHost("s3.us-west-2.amazonaws.com", 443, "https");
private static final HttpGet S3_REQUEST = new HttpGet("/my-bucket/my-object");
private static final HttpClientContext CONTEXT = new HttpClientContext();
@Test
public void testSetsCorrectSchemeBasedOnProcotol_HTTPS() throws HttpException {
SdkProxyRoutePlanner planner = new SdkProxyRoutePlanner("localhost", 1234, "https", Collections.emptySet());
HttpHost proxyHost = planner.determineRoute(S3_HOST, S3_REQUEST, CONTEXT).getProxyHost();
assertEquals("localhost", proxyHost.getHostName());
assertEquals("https", proxyHost.getSchemeName());
}
@Test
public void testSetsCorrectSchemeBasedOnProcotol_HTTP() throws HttpException {
SdkProxyRoutePlanner planner = new SdkProxyRoutePlanner("localhost", 1234, "http", Collections.emptySet());
HttpHost proxyHost = planner.determineRoute(S3_HOST, S3_REQUEST, CONTEXT).getProxyHost();
assertEquals("localhost", proxyHost.getHostName());
assertEquals("http", proxyHost.getSchemeName());
}
}
| 972 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/impl/ApacheHttpRequestFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.BufferedHttpEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.RepeatableInputStreamRequestEntity;
public class ApacheHttpRequestFactoryTest {
private ApacheHttpRequestConfig requestConfig;
private ApacheHttpRequestFactory instance;
@BeforeEach
public void setup() {
instance = new ApacheHttpRequestFactory();
requestConfig = ApacheHttpRequestConfig.builder()
.connectionAcquireTimeout(Duration.ZERO)
.connectionTimeout(Duration.ZERO)
.localAddress(InetAddress.getLoopbackAddress())
.socketTimeout(Duration.ZERO)
.build();
}
@Test
public void createSetsHostHeaderByDefault() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost:12345", hostHeaders[0].getValue());
}
@Test
public void putRequest_withTransferEncodingChunked_isChunkedAndDoesNotIncludeHeader() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.PUT)
.putHeader("Transfer-Encoding", "chunked")
.build();
InputStream inputStream = new ByteArrayInputStream("TestStream".getBytes(StandardCharsets.UTF_8));
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.contentStreamProvider(() -> inputStream)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] transferEncodingHeaders = result.getHeaders("Transfer-Encoding");
assertThat(transferEncodingHeaders).isEmpty();
HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) result;
HttpEntity httpEntity = enclosingRequest.getEntity();
assertThat(httpEntity.isChunked()).isTrue();
assertThat(httpEntity).isNotInstanceOf(BufferedHttpEntity.class);
assertThat(httpEntity).isInstanceOf(RepeatableInputStreamRequestEntity.class);
}
@Test
public void defaultHttpPortsAreNotInDefaultHostHeader() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:80/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost", hostHeaders[0].getValue());
sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("https://localhost:443/"))
.method(SdkHttpMethod.HEAD)
.build();
request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
result = instance.create(request, requestConfig);
hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost", hostHeaders[0].getValue());
}
@Test
public void pathWithLeadingSlash_shouldEncode() {
assertThat(sanitizedUri("/foobar")).isEqualTo("http://localhost/%2Ffoobar");
}
@Test
public void pathWithOnlySlash_shouldEncode() {
assertThat(sanitizedUri("/")).isEqualTo("http://localhost/%2F");
}
@Test
public void pathWithoutSlash_shouldReturnSameUri() {
assertThat(sanitizedUri("path")).isEqualTo("http://localhost/path");
}
@Test
public void pathWithSpecialChars_shouldPreserveEncoding() {
assertThat(sanitizedUri("/special-chars-%40%24%25")).isEqualTo("http://localhost/%2Fspecial-chars-%40%24%25");
}
private String sanitizedUri(String path) {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:80"))
.encodedPath("/" + path)
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
return instance.create(request, requestConfig).getURI().toString();
}
}
| 973 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/IdleConnectionReaperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.apache.http.conn.HttpClientConnectionManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Tests for {@link IdleConnectionReaper}.
*/
@RunWith(MockitoJUnitRunner.class)
public class IdleConnectionReaperTest {
private static final long SLEEP_PERIOD = 250;
private final Map<HttpClientConnectionManager, Long> connectionManagers = new HashMap<>();
@Mock
public ExecutorService executorService;
@Mock
public HttpClientConnectionManager connectionManager;
private IdleConnectionReaper idleConnectionReaper;
@Before
public void methodSetup() {
this.connectionManagers.clear();
idleConnectionReaper = new IdleConnectionReaper(connectionManagers, () -> executorService, SLEEP_PERIOD);
}
@Test
public void setsUpExecutorIfManagerNotPreviouslyRegistered() {
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
verify(executorService).execute(any(Runnable.class));
}
@Test
public void shutsDownExecutorIfMapEmptied() {
// use register method so it sets up the executor
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
idleConnectionReaper.deregisterConnectionManager(connectionManager);
verify(executorService).shutdownNow();
}
@Test
public void doesNotShutDownExecutorIfNoManagerRemoved() {
idleConnectionReaper.registerConnectionManager(connectionManager, 1L);
HttpClientConnectionManager someOtherConnectionManager = mock(HttpClientConnectionManager.class);
idleConnectionReaper.deregisterConnectionManager(someOtherConnectionManager);
verify(executorService, times(0)).shutdownNow();
}
@Test(timeout = 1000L)
public void testReapsConnections() throws InterruptedException {
IdleConnectionReaper reaper = new IdleConnectionReaper(new HashMap<>(),
Executors::newSingleThreadExecutor,
SLEEP_PERIOD);
final long idleTime = 1L;
reaper.registerConnectionManager(connectionManager, idleTime);
try {
Thread.sleep(SLEEP_PERIOD * 2);
verify(connectionManager, atLeastOnce()).closeIdleConnections(eq(idleTime), eq(TimeUnit.MILLISECONDS));
} finally {
reaper.deregisterConnectionManager(connectionManager);
}
}
}
| 974 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionManagerFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
public class ClientConnectionManagerFactoryTest {
HttpClientConnectionManager noop = new HttpClientConnectionManager() {
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws
IOException {
}
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
}
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
}
@Override
public ConnectionRequest requestConnection(HttpRoute route,
Object state) {
return null;
}
@Override
public void releaseConnection(HttpClientConnection conn,
Object newState,
long validDuration,
TimeUnit timeUnit) {
}
@Override
public void closeIdleConnections(long idletime, TimeUnit tunit) {
}
@Override
public void closeExpiredConnections() {
}
@Override
public void shutdown() {
}
};
@Test
public void wrapOnce() {
ClientConnectionManagerFactory.wrap(noop);
}
@Test(expected = IllegalArgumentException.class)
public void wrapTwice() {
HttpClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop);
ClientConnectionManagerFactory.wrap(wrapped);
}
}
| 975 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/test/java/software/amazon/awssdk/http/apache/internal/conn/SdkTlsSocketFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class SdkTlsSocketFactoryTest {
SdkTlsSocketFactory factory;
SSLSocket socket;
@BeforeEach
public void before() throws Exception {
factory = new SdkTlsSocketFactory(SSLContext.getDefault(), null);
socket = Mockito.mock(SSLSocket.class);
}
@Test
void nullProtocols() {
when(socket.getSupportedProtocols()).thenReturn(null);
when(socket.getEnabledProtocols()).thenReturn(null);
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_8_0_292_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.2", "TLSv1.1", "TLSv1"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_11_0_08_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
@Test
void amazonCorretto_17_0_1_defaultEnabledProtocols() {
when(socket.getSupportedProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello"
});
when(socket.getEnabledProtocols()).thenReturn(new String[] {
"TLSv1.3", "TLSv1.2"
});
factory.prepareSocket(socket);
verify(socket, never()).setEnabledProtocols(any());
}
}
| 976 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static software.amazon.awssdk.utils.ProxyConfigProvider.fromSystemEnvironmentSettings;
import static software.amazon.awssdk.utils.StringUtils.isEmpty;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration that defines how to communicate via an HTTP or HTTPS proxy.
*/
@SdkPublicApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final URI endpoint;
private final String username;
private final String password;
private final String ntlmDomain;
private final String ntlmWorkstation;
private final Set<String> nonProxyHosts;
private final Boolean preemptiveBasicAuthenticationEnabled;
private final Boolean useSystemPropertyValues;
private final String host;
private final int port;
private final String scheme;
private final Boolean useEnvironmentVariablesValues;
/**
* Initialize this configuration. Private to require use of {@link #builder()}.
*/
private ProxyConfiguration(DefaultClientProxyConfigurationBuilder builder) {
this.endpoint = builder.endpoint;
String resolvedScheme = getResolvedScheme(builder);
this.scheme = resolvedScheme;
ProxyConfigProvider proxyConfiguration = fromSystemEnvironmentSettings(builder.useSystemPropertyValues,
builder.useEnvironmentVariableValues,
resolvedScheme);
this.username = resolveUsername(builder, proxyConfiguration);
this.password = resolvePassword(builder, proxyConfiguration);
this.ntlmDomain = builder.ntlmDomain;
this.ntlmWorkstation = builder.ntlmWorkstation;
this.nonProxyHosts = resolveNonProxyHosts(builder, proxyConfiguration);
this.preemptiveBasicAuthenticationEnabled = builder.preemptiveBasicAuthenticationEnabled == null ? Boolean.FALSE :
builder.preemptiveBasicAuthenticationEnabled;
this.useSystemPropertyValues = builder.useSystemPropertyValues;
this.useEnvironmentVariablesValues = builder.useEnvironmentVariableValues;
if (this.endpoint != null) {
this.host = endpoint.getHost();
this.port = endpoint.getPort();
} else {
this.host = proxyConfiguration != null ? proxyConfiguration.host() : null;
this.port = proxyConfiguration != null ? proxyConfiguration.port() : 0;
}
}
private static String resolvePassword(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
return !isEmpty(builder.password) || proxyConfiguration == null ? builder.password :
proxyConfiguration.password().orElseGet(() -> builder.password);
}
private static String resolveUsername(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
return !isEmpty(builder.username) || proxyConfiguration == null ? builder.username :
proxyConfiguration.userName().orElseGet(() -> builder.username);
}
private static Set<String> resolveNonProxyHosts(DefaultClientProxyConfigurationBuilder builder,
ProxyConfigProvider proxyConfiguration) {
if (builder.nonProxyHosts != null || proxyConfiguration == null) {
return builder.nonProxyHosts;
}
return proxyConfiguration.nonProxyHosts();
}
private String getResolvedScheme(DefaultClientProxyConfigurationBuilder builder) {
return endpoint != null ? endpoint.getScheme() : builder.scheme;
}
/**
* Returns the proxy host name from the configured endpoint if set, else from the "https.proxyHost" or "http.proxyHost" system
* property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
*/
public String host() {
return host;
}
/**
* Returns the proxy port from the configured endpoint if set, else from the "https.proxyPort" or "http.proxyPort" system
* property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true.
* If no value is found in none of the above options, the default value of 0 is returned.
*/
public int port() {
return port;
}
/**
* Returns the {@link URI#scheme} from the configured endpoint. Otherwise return null.
*/
public String scheme() {
return scheme;
}
/**
* The username to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String username() {
return username;
}
/**
* The password to use when connecting through a proxy.
*
* @see Builder#password(String)
*/
public String password() {
return password;
}
/**
* For NTLM proxies: The Windows domain name to use when authenticating with the proxy.
*
* @see Builder#ntlmDomain(String)
*/
public String ntlmDomain() {
return ntlmDomain;
}
/**
* For NTLM proxies: The Windows workstation name to use when authenticating with the proxy.
*
* @see Builder#ntlmWorkstation(String)
*/
public String ntlmWorkstation() {
return ntlmWorkstation;
}
/**
* The hosts that the client is allowed to access without going through the proxy.
* If the value is not set on the object, the value represent by "http.nonProxyHosts" system property is returned.
* If system property is also not set, an unmodifiable empty set is returned.
*
* @see Builder#nonProxyHosts(Set)
*/
public Set<String> nonProxyHosts() {
return Collections.unmodifiableSet(nonProxyHosts != null ? nonProxyHosts : Collections.emptySet());
}
/**
* Whether to attempt to authenticate preemptively against the proxy server using basic authentication.
*
* @see Builder#preemptiveBasicAuthenticationEnabled(Boolean)
*/
public Boolean preemptiveBasicAuthenticationEnabled() {
return preemptiveBasicAuthenticationEnabled;
}
@Override
public Builder toBuilder() {
return builder()
.endpoint(endpoint)
.username(username)
.password(password)
.ntlmDomain(ntlmDomain)
.ntlmWorkstation(ntlmWorkstation)
.nonProxyHosts(nonProxyHosts)
.preemptiveBasicAuthenticationEnabled(preemptiveBasicAuthenticationEnabled)
.useSystemPropertyValues(useSystemPropertyValues)
.scheme(scheme)
.useEnvironmentVariableValues(useEnvironmentVariablesValues);
}
/**
* Create a {@link Builder}, used to create a {@link ProxyConfiguration}.
*/
public static Builder builder() {
return new DefaultClientProxyConfigurationBuilder();
}
@Override
public String toString() {
return ToString.builder("ProxyConfiguration")
.add("endpoint", endpoint)
.add("username", username)
.add("ntlmDomain", ntlmDomain)
.add("ntlmWorkstation", ntlmWorkstation)
.add("nonProxyHosts", nonProxyHosts)
.add("preemptiveBasicAuthenticationEnabled", preemptiveBasicAuthenticationEnabled)
.add("useSystemPropertyValues", useSystemPropertyValues)
.add("useEnvironmentVariablesValues", useEnvironmentVariablesValues)
.add("scheme", scheme)
.build();
}
public String resolveScheme() {
return endpoint != null ? endpoint.getScheme() : scheme;
}
/**
* A builder for {@link ProxyConfiguration}.
*
* <p>All implementations of this interface are mutable and not thread safe.</p>
*/
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Configure the endpoint of the proxy server that the SDK should connect through. Currently, the endpoint is limited to
* a host and port. Any other URI components will result in an exception being raised.
*/
Builder endpoint(URI endpoint);
/**
* Configure the username to use when connecting through a proxy.
*/
Builder username(String username);
/**
* Configure the password to use when connecting through a proxy.
*/
Builder password(String password);
/**
* For NTLM proxies: Configure the Windows domain name to use when authenticating with the proxy.
*/
Builder ntlmDomain(String proxyDomain);
/**
* For NTLM proxies: Configure the Windows workstation name to use when authenticating with the proxy.
*/
Builder ntlmWorkstation(String proxyWorkstation);
/**
* Configure the hosts that the client is allowed to access without going through the proxy.
*/
Builder nonProxyHosts(Set<String> nonProxyHosts);
/**
* Add a host that the client is allowed to access without going through the proxy.
*
* @see ProxyConfiguration#nonProxyHosts()
*/
Builder addNonProxyHost(String nonProxyHost);
/**
* Configure whether to attempt to authenticate pre-emptively against the proxy server using basic authentication.
*/
Builder preemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled);
/**
* Option whether to use system property values from {@link ProxySystemSetting} if any of the config options are missing.
* <p>
* This value is set to "true" by default which means SDK will automatically use system property values for options that
* are not provided during building the {@link ProxyConfiguration} object. To disable this behavior, set this value to
* "false".It is important to note that when this property is set to "true," all proxy settings will exclusively originate
* from system properties, and no partial settings will be obtained from EnvironmentVariableValues.
*/
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
/**
* Option whether to use environment variable values for proxy configuration if any of the config options are missing.
* <p>
* This value is set to "true" by default, which means the SDK will automatically use environment variable values for
* proxy configuration options that are not provided during the building of the {@link ProxyConfiguration} object. To
* disable this behavior, set this value to "false". It is important to note that when this property is set to "true," all
* proxy settings will exclusively originate from environment variableValues, and no partial settings will be obtained
* from SystemPropertyValues.
*
* @param useEnvironmentVariableValues The option whether to use environment variable values.
* @return This object for method chaining.
*/
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
Builder scheme(String scheme);
}
/**
* An SDK-internal implementation of {@link Builder}.
*/
private static final class DefaultClientProxyConfigurationBuilder implements Builder {
private URI endpoint;
private String username;
private String password;
private String ntlmDomain;
private String ntlmWorkstation;
private Set<String> nonProxyHosts;
private Boolean preemptiveBasicAuthenticationEnabled;
private Boolean useSystemPropertyValues = Boolean.TRUE;
private Boolean useEnvironmentVariableValues = Boolean.TRUE;
private String scheme = "http";
@Override
public Builder endpoint(URI endpoint) {
if (endpoint != null) {
Validate.isTrue(isEmpty(endpoint.getUserInfo()), "Proxy endpoint user info is not supported.");
Validate.isTrue(isEmpty(endpoint.getPath()), "Proxy endpoint path is not supported.");
Validate.isTrue(isEmpty(endpoint.getQuery()), "Proxy endpoint query is not supported.");
Validate.isTrue(isEmpty(endpoint.getFragment()), "Proxy endpoint fragment is not supported.");
}
this.endpoint = endpoint;
return this;
}
public void setEndpoint(URI endpoint) {
endpoint(endpoint);
}
@Override
public Builder username(String username) {
this.username = username;
return this;
}
public void setUsername(String username) {
username(username);
}
@Override
public Builder password(String password) {
this.password = password;
return this;
}
public void setPassword(String password) {
password(password);
}
@Override
public Builder ntlmDomain(String proxyDomain) {
this.ntlmDomain = proxyDomain;
return this;
}
public void setNtlmDomain(String ntlmDomain) {
ntlmDomain(ntlmDomain);
}
@Override
public Builder ntlmWorkstation(String proxyWorkstation) {
this.ntlmWorkstation = proxyWorkstation;
return this;
}
public void setNtlmWorkstation(String ntlmWorkstation) {
ntlmWorkstation(ntlmWorkstation);
}
@Override
public Builder nonProxyHosts(Set<String> nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts != null ? new HashSet<>(nonProxyHosts) : null;
return this;
}
@Override
public Builder addNonProxyHost(String nonProxyHost) {
if (this.nonProxyHosts == null) {
this.nonProxyHosts = new HashSet<>();
}
this.nonProxyHosts.add(nonProxyHost);
return this;
}
public void setNonProxyHosts(Set<String> nonProxyHosts) {
nonProxyHosts(nonProxyHosts);
}
@Override
public Builder preemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled) {
this.preemptiveBasicAuthenticationEnabled = preemptiveBasicAuthenticationEnabled;
return this;
}
public void setPreemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled) {
preemptiveBasicAuthenticationEnabled(preemptiveBasicAuthenticationEnabled);
}
@Override
public Builder useSystemPropertyValues(Boolean useSystemPropertyValues) {
this.useSystemPropertyValues = useSystemPropertyValues;
return this;
}
public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) {
useSystemPropertyValues(useSystemPropertyValues);
}
@Override
public Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues) {
this.useEnvironmentVariableValues = useEnvironmentVariableValues;
return this;
}
@Override
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
public void setuseEnvironmentVariableValues(Boolean useEnvironmentVariableValues) {
useEnvironmentVariableValues(useEnvironmentVariableValues);
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
}
| 977 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ApacheSdkHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpService;
/**
* Service binding for the Apache implementation.
*/
@SdkPublicApi
public class ApacheSdkHttpService implements SdkHttpService {
@Override
public SdkHttpClient.Builder createHttpClientBuilder() {
return ApacheHttpClient.builder();
}
}
| 978 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/ApacheHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache;
import static software.amazon.awssdk.http.HttpMetric.AVAILABLE_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.HttpMetric.LEASED_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.MAX_CONCURRENCY;
import static software.amazon.awssdk.http.HttpMetric.PENDING_CONCURRENCY_ACQUIRES;
import static software.amazon.awssdk.http.apache.internal.conn.ClientConnectionRequestFactory.THREAD_LOCAL_REQUEST_METRIC_COLLECTOR;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLInitializationException;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.HttpRequestExecutor;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.SystemPropertyTlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.DefaultConfiguration;
import software.amazon.awssdk.http.apache.internal.SdkConnectionReuseStrategy;
import software.amazon.awssdk.http.apache.internal.SdkProxyRoutePlanner;
import software.amazon.awssdk.http.apache.internal.conn.ClientConnectionManagerFactory;
import software.amazon.awssdk.http.apache.internal.conn.IdleConnectionReaper;
import software.amazon.awssdk.http.apache.internal.conn.SdkConnectionKeepAliveStrategy;
import software.amazon.awssdk.http.apache.internal.conn.SdkTlsSocketFactory;
import software.amazon.awssdk.http.apache.internal.impl.ApacheHttpRequestFactory;
import software.amazon.awssdk.http.apache.internal.impl.ApacheSdkHttpClient;
import software.amazon.awssdk.http.apache.internal.impl.ConnectionManagerAwareHttpClient;
import software.amazon.awssdk.http.apache.internal.utils.ApacheUtils;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkHttpClient} that uses Apache HTTP client to communicate with the service. This is the most
* powerful synchronous client that adds an extra dependency and additional startup latency in exchange for more functionality,
* like support for HTTP proxies.
*
* <p>See software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient for an alternative implementation.</p>
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class ApacheHttpClient implements SdkHttpClient {
public static final String CLIENT_NAME = "Apache";
private static final Logger log = Logger.loggerFor(ApacheHttpClient.class);
private final ApacheHttpRequestFactory apacheHttpRequestFactory = new ApacheHttpRequestFactory();
private final ConnectionManagerAwareHttpClient httpClient;
private final ApacheHttpRequestConfig requestConfig;
private final AttributeMap resolvedOptions;
@SdkTestInternalApi
ApacheHttpClient(ConnectionManagerAwareHttpClient httpClient,
ApacheHttpRequestConfig requestConfig,
AttributeMap resolvedOptions) {
this.httpClient = httpClient;
this.requestConfig = requestConfig;
this.resolvedOptions = resolvedOptions;
}
private ApacheHttpClient(DefaultBuilder builder, AttributeMap resolvedOptions) {
this.httpClient = createClient(builder, resolvedOptions);
this.requestConfig = createRequestConfig(builder, resolvedOptions);
this.resolvedOptions = resolvedOptions;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link ApacheHttpClient} with the default properties
*
* @return an {@link ApacheHttpClient}
*/
public static SdkHttpClient create() {
return new DefaultBuilder().build();
}
private ConnectionManagerAwareHttpClient createClient(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
ApacheConnectionManagerFactory cmFactory = new ApacheConnectionManagerFactory();
HttpClientBuilder builder = HttpClients.custom();
// Note that it is important we register the original connection manager with the
// IdleConnectionReaper as it's required for the successful deregistration of managers
// from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
HttpClientConnectionManager cm = cmFactory.create(configuration, standardOptions);
builder.setRequestExecutor(new HttpRequestExecutor())
// SDK handles decompression
.disableContentCompression()
.setKeepAliveStrategy(buildKeepAliveStrategy(standardOptions))
.disableRedirectHandling()
.disableAutomaticRetries()
.setUserAgent("") // SDK will set the user agent header in the pipeline. Don't let Apache waste time
.setConnectionReuseStrategy(new SdkConnectionReuseStrategy())
.setConnectionManager(ClientConnectionManagerFactory.wrap(cm));
addProxyConfig(builder, configuration);
if (useIdleConnectionReaper(standardOptions)) {
IdleConnectionReaper.getInstance().registerConnectionManager(
cm, standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis());
}
return new ApacheSdkHttpClient(builder.build(), cm);
}
private void addProxyConfig(HttpClientBuilder builder,
DefaultBuilder configuration) {
ProxyConfiguration proxyConfiguration = configuration.proxyConfiguration;
Validate.isTrue(configuration.httpRoutePlanner == null || !isProxyEnabled(proxyConfiguration),
"The httpRoutePlanner and proxyConfiguration can't both be configured.");
Validate.isTrue(configuration.credentialsProvider == null || !isAuthenticatedProxy(proxyConfiguration),
"The credentialsProvider and proxyConfiguration username/password can't both be configured.");
HttpRoutePlanner routePlanner = configuration.httpRoutePlanner;
if (isProxyEnabled(proxyConfiguration)) {
log.debug(() -> "Configuring Proxy. Proxy Host: " + proxyConfiguration.host());
routePlanner = new SdkProxyRoutePlanner(proxyConfiguration.host(),
proxyConfiguration.port(),
proxyConfiguration.scheme(),
proxyConfiguration.nonProxyHosts());
}
CredentialsProvider credentialsProvider = configuration.credentialsProvider;
if (isAuthenticatedProxy(proxyConfiguration)) {
credentialsProvider = ApacheUtils.newProxyCredentialsProvider(proxyConfiguration);
}
if (routePlanner != null) {
builder.setRoutePlanner(routePlanner);
}
if (credentialsProvider != null) {
builder.setDefaultCredentialsProvider(credentialsProvider);
}
}
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(AttributeMap standardOptions) {
long maxIdle = standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis();
return maxIdle > 0 ? new SdkConnectionKeepAliveStrategy(maxIdle) : null;
}
private boolean useIdleConnectionReaper(AttributeMap standardOptions) {
return Boolean.TRUE.equals(standardOptions.get(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS));
}
private boolean isAuthenticatedProxy(ProxyConfiguration proxyConfiguration) {
return proxyConfiguration.username() != null && proxyConfiguration.password() != null;
}
private boolean isProxyEnabled(ProxyConfiguration proxyConfiguration) {
return proxyConfiguration.host() != null
&& proxyConfiguration.port() > 0;
}
@Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
MetricCollector metricCollector = request.metricCollector().orElseGet(NoOpMetricCollector::create);
metricCollector.reportMetric(HTTP_CLIENT_NAME, clientName());
HttpRequestBase apacheRequest = toApacheRequest(request);
return new ExecutableHttpRequest() {
@Override
public HttpExecuteResponse call() throws IOException {
HttpExecuteResponse executeResponse = execute(apacheRequest, metricCollector);
collectPoolMetric(metricCollector);
return executeResponse;
}
@Override
public void abort() {
apacheRequest.abort();
}
};
}
@Override
public void close() {
HttpClientConnectionManager cm = httpClient.getHttpClientConnectionManager();
IdleConnectionReaper.getInstance().deregisterConnectionManager(cm);
cm.shutdown();
}
private HttpExecuteResponse execute(HttpRequestBase apacheRequest, MetricCollector metricCollector) throws IOException {
HttpClientContext localRequestContext = ApacheUtils.newClientContext(requestConfig.proxyConfiguration());
THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.set(metricCollector);
try {
HttpResponse httpResponse = httpClient.execute(apacheRequest, localRequestContext);
return createResponse(httpResponse, apacheRequest);
} finally {
THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.remove();
}
}
private HttpRequestBase toApacheRequest(HttpExecuteRequest request) {
return apacheHttpRequestFactory.create(request, requestConfig);
}
/**
* Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
* handler object.
*
* @return The new, initialized HttpResponse object ready to be passed to an HTTP response handler object.
* @throws IOException If there were any problems getting any response information from the
* HttpClient method object.
*/
private HttpExecuteResponse createResponse(org.apache.http.HttpResponse apacheHttpResponse,
HttpRequestBase apacheRequest) throws IOException {
SdkHttpResponse.Builder responseBuilder =
SdkHttpResponse.builder()
.statusCode(apacheHttpResponse.getStatusLine().getStatusCode())
.statusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
HeaderIterator headerIterator = apacheHttpResponse.headerIterator();
while (headerIterator.hasNext()) {
Header header = headerIterator.nextHeader();
responseBuilder.appendHeader(header.getName(), header.getValue());
}
AbortableInputStream responseBody = apacheHttpResponse.getEntity() != null ?
toAbortableInputStream(apacheHttpResponse, apacheRequest) : null;
return HttpExecuteResponse.builder().response(responseBuilder.build()).responseBody(responseBody).build();
}
private AbortableInputStream toAbortableInputStream(HttpResponse apacheHttpResponse, HttpRequestBase apacheRequest)
throws IOException {
return AbortableInputStream.create(apacheHttpResponse.getEntity().getContent(), apacheRequest::abort);
}
private ApacheHttpRequestConfig createRequestConfig(DefaultBuilder builder,
AttributeMap resolvedOptions) {
return ApacheHttpRequestConfig.builder()
.socketTimeout(resolvedOptions.get(SdkHttpConfigurationOption.READ_TIMEOUT))
.connectionTimeout(resolvedOptions.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT))
.connectionAcquireTimeout(
resolvedOptions.get(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT))
.proxyConfiguration(builder.proxyConfiguration)
.localAddress(Optional.ofNullable(builder.localAddress).orElse(null))
.expectContinueEnabled(Optional.ofNullable(builder.expectContinueEnabled)
.orElse(DefaultConfiguration.EXPECT_CONTINUE_ENABLED))
.build();
}
private void collectPoolMetric(MetricCollector metricCollector) {
HttpClientConnectionManager cm = httpClient.getHttpClientConnectionManager();
if (cm instanceof PoolingHttpClientConnectionManager && !(metricCollector instanceof NoOpMetricCollector)) {
PoolingHttpClientConnectionManager poolingCm = (PoolingHttpClientConnectionManager) cm;
PoolStats totalStats = poolingCm.getTotalStats();
metricCollector.reportMetric(MAX_CONCURRENCY, totalStats.getMax());
metricCollector.reportMetric(AVAILABLE_CONCURRENCY, totalStats.getAvailable());
metricCollector.reportMetric(LEASED_CONCURRENCY, totalStats.getLeased());
metricCollector.reportMetric(PENDING_CONCURRENCY_ACQUIRES, totalStats.getPending());
}
}
@Override
public String clientName() {
return CLIENT_NAME;
}
/**
* Builder for creating an instance of {@link SdkHttpClient}. The factory can be configured through the builder {@link
* #builder()}, once built it can create a {@link SdkHttpClient} via {@link #build()} or can be passed to the SDK
* client builders directly to have the SDK create and manage the HTTP client. See documentation on the service's respective
* client builder for more information on configuring the HTTP layer.
*
* <pre class="brush: java">
* SdkHttpClient httpClient =
* ApacheHttpClient.builder()
* .socketTimeout(Duration.ofSeconds(10))
* .build();
* </pre>
*/
public interface Builder extends SdkHttpClient.Builder<ApacheHttpClient.Builder> {
/**
* The amount of time to wait for data to be transferred over an established, open connection before the connection is
* timed out. A duration of 0 means infinity, and is not recommended.
*/
Builder socketTimeout(Duration socketTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out. A duration of 0
* means infinity, and is not recommended.
*/
Builder connectionTimeout(Duration connectionTimeout);
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout);
/**
* The maximum number of connections allowed in the connection pool. Each built HTTP client has its own private
* connection pool.
*/
Builder maxConnections(Integer maxConnections);
/**
* Configuration that defines how to communicate via an HTTP proxy.
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Configure the local address that the HTTP client should use for communication.
*/
Builder localAddress(InetAddress localAddress);
/**
* Configure whether the client should send an HTTP expect-continue handshake before each request.
*/
Builder expectContinueEnabled(Boolean expectContinueEnabled);
/**
* The maximum amount of time that a connection should be allowed to remain open, regardless of usage frequency.
*/
Builder connectionTimeToLive(Duration connectionTimeToLive);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle.
*/
Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout);
/**
* Configure whether the idle connections in the connection pool should be closed asynchronously.
* <p>
* When enabled, connections left idling for longer than {@link #connectionMaxIdleTime(Duration)} will be
* closed. This will not close connections currently in use. By default, this is enabled.
*/
Builder useIdleConnectionReaper(Boolean useConnectionReaper);
/**
* Configuration that defines a DNS resolver. If no matches are found, the default resolver is used.
*/
Builder dnsResolver(DnsResolver dnsResolver);
/**
* Configuration that defines a custom Socket factory. If set to a null value, a default factory is used.
* <p>
* When set to a non-null value, the use of a custom factory implies the configuration options TRUST_ALL_CERTIFICATES,
* TLS_TRUST_MANAGERS_PROVIDER, and TLS_KEY_MANAGERS_PROVIDER are ignored.
*/
Builder socketFactory(ConnectionSocketFactory socketFactory);
/**
* Configuration that defines an HTTP route planner that computes the route an HTTP request should take.
* May not be used in conjunction with {@link #proxyConfiguration(ProxyConfiguration)}.
*/
Builder httpRoutePlanner(HttpRoutePlanner proxyConfiguration);
/**
* Configuration that defines a custom credential provider for HTTP requests.
* May not be used in conjunction with {@link ProxyConfiguration#username()} and {@link ProxyConfiguration#password()}.
*/
Builder credentialsProvider(CredentialsProvider credentialsProvider);
/**
* Configure whether to enable or disable TCP KeepAlive.
* The configuration will be passed to the socket option {@link java.net.SocketOptions#SO_KEEPALIVE}.
* <p>
* By default, this is disabled.
* <p>
* When enabled, the actual KeepAlive mechanism is dependent on the Operating System and therefore additional TCP
* KeepAlive values (like timeout, number of packets, etc) must be configured via the Operating System (sysctl on
* Linux/Mac, and Registry values on Windows).
*/
Builder tcpKeepAlive(Boolean keepConnectionAlive);
/**
* Configure the {@link TlsKeyManagersProvider} that will provide the {@link javax.net.ssl.KeyManager}s to use
* when constructing the SSL context.
* <p>
* The default used by the client will be {@link SystemPropertyTlsKeyManagersProvider}. Configure an instance of
* {@link software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider} or another implementation of
* {@link TlsKeyManagersProvider} to override it.
*/
Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider);
/**
* Configure the {@link TlsTrustManagersProvider} that will provide the {@link javax.net.ssl.TrustManager}s to use
* when constructing the SSL context.
*/
Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider);
}
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder().build();
private InetAddress localAddress;
private Boolean expectContinueEnabled;
private HttpRoutePlanner httpRoutePlanner;
private CredentialsProvider credentialsProvider;
private DnsResolver dnsResolver;
private ConnectionSocketFactory socketFactory;
private DefaultBuilder() {
}
@Override
public Builder socketTimeout(Duration socketTimeout) {
standardOptions.put(SdkHttpConfigurationOption.READ_TIMEOUT, socketTimeout);
return this;
}
public void setSocketTimeout(Duration socketTimeout) {
socketTimeout(socketTimeout);
}
@Override
public Builder connectionTimeout(Duration connectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, connectionTimeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
@Override
public Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
Validate.isPositive(connectionAcquisitionTimeout, "connectionAcquisitionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT, connectionAcquisitionTimeout);
return this;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
connectionAcquisitionTimeout(connectionAcquisitionTimeout);
}
@Override
public Builder maxConnections(Integer maxConnections) {
standardOptions.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, maxConnections);
return this;
}
public void setMaxConnections(Integer maxConnections) {
maxConnections(maxConnections);
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
proxyConfiguration(proxyConfiguration);
}
@Override
public Builder localAddress(InetAddress localAddress) {
this.localAddress = localAddress;
return this;
}
public void setLocalAddress(InetAddress localAddress) {
localAddress(localAddress);
}
@Override
public Builder expectContinueEnabled(Boolean expectContinueEnabled) {
this.expectContinueEnabled = expectContinueEnabled;
return this;
}
public void setExpectContinueEnabled(Boolean useExpectContinue) {
this.expectContinueEnabled = useExpectContinue;
}
@Override
public Builder connectionTimeToLive(Duration connectionTimeToLive) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE, connectionTimeToLive);
return this;
}
public void setConnectionTimeToLive(Duration connectionTimeToLive) {
connectionTimeToLive(connectionTimeToLive);
}
@Override
public Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout) {
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, maxIdleConnectionTimeout);
return this;
}
public void setConnectionMaxIdleTime(Duration connectionMaxIdleTime) {
connectionMaxIdleTime(connectionMaxIdleTime);
}
@Override
public Builder useIdleConnectionReaper(Boolean useIdleConnectionReaper) {
standardOptions.put(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS, useIdleConnectionReaper);
return this;
}
public void setUseIdleConnectionReaper(Boolean useIdleConnectionReaper) {
useIdleConnectionReaper(useIdleConnectionReaper);
}
@Override
public Builder dnsResolver(DnsResolver dnsResolver) {
this.dnsResolver = dnsResolver;
return this;
}
public void setDnsResolver(DnsResolver dnsResolver) {
dnsResolver(dnsResolver);
}
@Override
public Builder socketFactory(ConnectionSocketFactory socketFactory) {
this.socketFactory = socketFactory;
return this;
}
public void setSocketFactory(ConnectionSocketFactory socketFactory) {
socketFactory(socketFactory);
}
@Override
public Builder httpRoutePlanner(HttpRoutePlanner httpRoutePlanner) {
this.httpRoutePlanner = httpRoutePlanner;
return this;
}
public void setHttpRoutePlanner(HttpRoutePlanner httpRoutePlanner) {
httpRoutePlanner(httpRoutePlanner);
}
@Override
public Builder credentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
credentialsProvider(credentialsProvider);
}
@Override
public Builder tcpKeepAlive(Boolean keepConnectionAlive) {
standardOptions.put(SdkHttpConfigurationOption.TCP_KEEPALIVE, keepConnectionAlive);
return this;
}
public void setTcpKeepAlive(Boolean keepConnectionAlive) {
tcpKeepAlive(keepConnectionAlive);
}
@Override
public Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER, tlsKeyManagersProvider);
return this;
}
public void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
tlsKeyManagersProvider(tlsKeyManagersProvider);
}
@Override
public Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER, tlsTrustManagersProvider);
return this;
}
public void setTlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
tlsTrustManagersProvider(tlsTrustManagersProvider);
}
@Override
public SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
AttributeMap resolvedOptions = standardOptions.build().merge(serviceDefaults).merge(
SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS);
return new ApacheHttpClient(this, resolvedOptions);
}
}
private static class ApacheConnectionManagerFactory {
public HttpClientConnectionManager create(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
ConnectionSocketFactory sslsf = getPreferredSocketFactory(configuration, standardOptions);
PoolingHttpClientConnectionManager cm = new
PoolingHttpClientConnectionManager(
createSocketFactoryRegistry(sslsf),
null,
DefaultSchemePortResolver.INSTANCE,
configuration.dnsResolver,
standardOptions.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE).toMillis(),
TimeUnit.MILLISECONDS);
cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
cm.setDefaultSocketConfig(buildSocketConfig(standardOptions));
return cm;
}
private ConnectionSocketFactory getPreferredSocketFactory(ApacheHttpClient.DefaultBuilder configuration,
AttributeMap standardOptions) {
return Optional.ofNullable(configuration.socketFactory)
.orElseGet(() -> new SdkTlsSocketFactory(getSslContext(standardOptions),
getHostNameVerifier(standardOptions)));
}
private HostnameVerifier getHostNameVerifier(AttributeMap standardOptions) {
return standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)
? NoopHostnameVerifier.INSTANCE
: SSLConnectionSocketFactory.getDefaultHostnameVerifier();
}
private SSLContext getSslContext(AttributeMap standardOptions) {
Validate.isTrue(standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) == null ||
!standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES),
"A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");
TrustManager[] trustManagers = null;
if (standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) != null) {
trustManagers = standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER).trustManagers();
}
if (standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
log.warn(() -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
+ "used for testing.");
trustManagers = trustAllTrustManager();
}
TlsKeyManagersProvider provider = standardOptions.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
KeyManager[] keyManagers = provider.keyManagers();
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
// http://download.java.net/jdk9/docs/technotes/guides/security/jsse/JSSERefGuide.html
sslcontext.init(keyManagers, trustManagers, null);
return sslcontext;
} catch (final NoSuchAlgorithmException | KeyManagementException ex) {
throw new SSLInitializationException(ex.getMessage(), ex);
}
}
/**
* Insecure trust manager to trust all certs. Should only be used for testing.
*/
private static TrustManager[] trustAllTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
log.debug(() -> "Accepting a client certificate: " + x509Certificates[0].getSubjectDN());
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
}
private SocketConfig buildSocketConfig(AttributeMap standardOptions) {
return SocketConfig.custom()
.setSoKeepAlive(standardOptions.get(SdkHttpConfigurationOption.TCP_KEEPALIVE))
.setSoTimeout(
saturatedCast(standardOptions.get(SdkHttpConfigurationOption.READ_TIMEOUT)
.toMillis()))
.setTcpNoDelay(true)
.build();
}
private Registry<ConnectionSocketFactory> createSocketFactoryRegistry(ConnectionSocketFactory sslSocketFactory) {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
}
}
| 979 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/ApacheHttpRequestConfig.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import java.net.InetAddress;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.ProxyConfiguration;
/**
* Configuration needed when building an Apache request. Note that at this time, we only support client level configuration so
* all of these settings are supplied when creating the client.
*/
@SdkInternalApi
public final class ApacheHttpRequestConfig {
private final Duration socketTimeout;
private final Duration connectionTimeout;
private final Duration connectionAcquireTimeout;
private final InetAddress localAddress;
private final boolean expectContinueEnabled;
private final ProxyConfiguration proxyConfiguration;
private ApacheHttpRequestConfig(Builder builder) {
this.socketTimeout = builder.socketTimeout;
this.connectionTimeout = builder.connectionTimeout;
this.connectionAcquireTimeout = builder.connectionAcquireTimeout;
this.localAddress = builder.localAddress;
this.expectContinueEnabled = builder.expectContinueEnabled;
this.proxyConfiguration = builder.proxyConfiguration;
}
public Duration socketTimeout() {
return socketTimeout;
}
public Duration connectionTimeout() {
return connectionTimeout;
}
public Duration connectionAcquireTimeout() {
return connectionAcquireTimeout;
}
public InetAddress localAddress() {
return localAddress;
}
public boolean expectContinueEnabled() {
return expectContinueEnabled;
}
public ProxyConfiguration proxyConfiguration() {
return proxyConfiguration;
}
/**
* @return Builder instance to construct a {@link ApacheHttpRequestConfig}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link ApacheHttpRequestConfig}.
*/
public static final class Builder {
private Duration socketTimeout;
private Duration connectionTimeout;
private Duration connectionAcquireTimeout;
private InetAddress localAddress;
private boolean expectContinueEnabled;
private ProxyConfiguration proxyConfiguration;
private Builder() {
}
public Builder socketTimeout(Duration socketTimeout) {
this.socketTimeout = socketTimeout;
return this;
}
public Builder connectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public Builder connectionAcquireTimeout(Duration connectionAcquireTimeout) {
this.connectionAcquireTimeout = connectionAcquireTimeout;
return this;
}
public Builder localAddress(InetAddress localAddress) {
this.localAddress = localAddress;
return this;
}
public Builder expectContinueEnabled(boolean expectContinueEnabled) {
this.expectContinueEnabled = expectContinueEnabled;
return this;
}
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
/**
* @return An immutable {@link ApacheHttpRequestConfig} object.
*/
public ApacheHttpRequestConfig build() {
return new ApacheHttpRequestConfig(this);
}
}
}
| 980 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/RepeatableInputStreamRequestEntity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static software.amazon.awssdk.http.Header.CHUNKED;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Optional;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
/**
* Custom implementation of {@link org.apache.http.HttpEntity} that delegates to an
* {@link RepeatableInputStreamRequestEntity}, with the one notable difference, that if
* the underlying InputStream supports being reset, this RequestEntity will
* report that it is repeatable and will reset the stream on all subsequent
* attempts to write out the request.
*/
@SdkInternalApi
public class RepeatableInputStreamRequestEntity extends BasicHttpEntity {
private static final Logger log = LoggerFactory.getLogger(RepeatableInputStreamRequestEntity.class);
/**
* True if the request entity hasn't been written out yet
*/
private boolean firstAttempt = true;
/**
* True if the "Transfer-Encoding:chunked" header is present
*/
private boolean isChunked;
/**
* The underlying InputStreamEntity being delegated to
*/
private InputStreamEntity inputStreamRequestEntity;
/**
* The InputStream containing the content to write out
*/
private InputStream content;
/**
* Record the original exception if we do attempt a retry, so that if the
* retry fails, we can report the original exception. Otherwise, we're most
* likely masking the real exception with an error about not being able to
* reset far enough back in the input stream.
*/
private IOException originalException;
/**
* Creates a new RepeatableInputStreamRequestEntity using the information
* from the specified request. If the input stream containing the request's
* contents is repeatable, then this RequestEntity will report as being
* repeatable.
*
* @param request The details of the request being written out (content type,
* content length, and content).
*/
public RepeatableInputStreamRequestEntity(final HttpExecuteRequest request) {
isChunked = request.httpRequest().matchingHeaders(TRANSFER_ENCODING).contains(CHUNKED);
setChunked(isChunked);
/*
* If we don't specify a content length when we instantiate our
* InputStreamRequestEntity, then HttpClient will attempt to
* buffer the entire stream contents into memory to determine
* the content length.
*/
long contentLength = request.httpRequest().firstMatchingHeader("Content-Length")
.map(this::parseContentLength)
.orElse(-1L);
content = getContent(request.contentStreamProvider());
// TODO v2 MetricInputStreamEntity
inputStreamRequestEntity = new InputStreamEntity(content, contentLength);
setContent(content);
setContentLength(contentLength);
request.httpRequest().firstMatchingHeader("Content-Type").ifPresent(contentType -> {
inputStreamRequestEntity.setContentType(contentType);
setContentType(contentType);
});
}
private long parseContentLength(String contentLength) {
try {
return Long.parseLong(contentLength);
} catch (NumberFormatException nfe) {
log.warn("Unable to parse content length from request. Buffering contents in memory.");
return -1;
}
}
/**
* @return The request content input stream or an empty input stream if there is no content.
*/
private InputStream getContent(Optional<ContentStreamProvider> contentStreamProvider) {
return contentStreamProvider.map(ContentStreamProvider::newStream).orElseGet(() -> new ByteArrayInputStream(new byte[0]));
}
@Override
public boolean isChunked() {
return isChunked;
}
/**
* Returns true if the underlying InputStream supports marking/reseting or
* if the underlying InputStreamRequestEntity is repeatable.
*/
@Override
public boolean isRepeatable() {
return content.markSupported() || inputStreamRequestEntity.isRepeatable();
}
/**
* Resets the underlying InputStream if this isn't the first attempt to
* write out the request, otherwise simply delegates to
* InputStreamRequestEntity to write out the data.
* <p>
* If an error is encountered the first time we try to write the request
* entity, we remember the original exception, and report that as the root
* cause if we continue to encounter errors, rather than masking the
* original error.
*/
@Override
public void writeTo(OutputStream output) throws IOException {
try {
if (!firstAttempt && isRepeatable()) {
content.reset();
}
firstAttempt = false;
inputStreamRequestEntity.writeTo(output);
} catch (IOException ioe) {
if (originalException == null) {
originalException = ioe;
}
throw originalException;
}
}
}
| 981 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/SdkProxyRoutePlanner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.util.Set;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* SdkProxyRoutePlanner delegates a Proxy Route Planner from the settings instead of the
* system properties. It will use the proxy created from proxyHost and proxyPort and
* filter the hosts who matches nonProxyHosts pattern.
*/
@SdkInternalApi
public class SdkProxyRoutePlanner extends DefaultRoutePlanner {
private HttpHost proxy;
private Set<String> hostPatterns;
public SdkProxyRoutePlanner(String proxyHost, int proxyPort, String proxyProtocol, Set<String> nonProxyHosts) {
super(DefaultSchemePortResolver.INSTANCE);
proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
this.hostPatterns = nonProxyHosts;
}
private boolean doesTargetMatchNonProxyHosts(HttpHost target) {
if (hostPatterns == null) {
return false;
}
String targetHost = lowerCase(target.getHostName());
for (String pattern : hostPatterns) {
if (targetHost.matches(pattern)) {
return true;
}
}
return false;
}
@Override
protected HttpHost determineProxy(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws HttpException {
return doesTargetMatchNonProxyHosts(target) ? null : proxy;
}
}
| 982 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/DefaultConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Default configuration values.
*/
@SdkInternalApi
public final class DefaultConfiguration {
public static final Boolean EXPECT_CONTINUE_ENABLED = Boolean.TRUE;
private DefaultConfiguration() {
}
}
| 983 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/SdkConnectionReuseStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Do not reuse connections that returned a 5xx error.
*
* <p>This is not strictly the behavior we would want in an AWS client, because sometimes we might want to keep a connection open
* (e.g. an undocumented service's 503 'SlowDown') and sometimes we might want to close the connection (e.g. S3's 400
* RequestTimeout or Glacier's 408 RequestTimeoutException), but this is good enough for the majority of services, and the ones
* for which it is not should not be impacted too harshly.
*/
@SdkInternalApi
public class SdkConnectionReuseStrategy extends DefaultClientConnectionReuseStrategy {
@Override
public boolean keepAlive(HttpResponse response, HttpContext context) {
if (!super.keepAlive(response, context)) {
return false;
}
if (response == null || response.getStatusLine() == null) {
return false;
}
return !is500(response);
}
private boolean is500(HttpResponse httpResponse) {
return httpResponse.getStatusLine().getStatusCode() / 100 == 5;
}
}
| 984 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ApacheHttpRequestFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.internal.ApacheHttpRequestConfig;
import software.amazon.awssdk.http.apache.internal.RepeatableInputStreamRequestEntity;
import software.amazon.awssdk.http.apache.internal.utils.ApacheUtils;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Responsible for creating Apache HttpClient 4 request objects.
*/
@SdkInternalApi
public class ApacheHttpRequestFactory {
private static final List<String> IGNORE_HEADERS = Arrays.asList(HttpHeaders.CONTENT_LENGTH, HttpHeaders.HOST,
HttpHeaders.TRANSFER_ENCODING);
public HttpRequestBase create(final HttpExecuteRequest request, final ApacheHttpRequestConfig requestConfig) {
HttpRequestBase base = createApacheRequest(request, sanitizeUri(request.httpRequest()));
addHeadersToRequest(base, request.httpRequest());
addRequestConfig(base, request.httpRequest(), requestConfig);
return base;
}
/**
* The Apache HTTP client doesn't allow consecutive slashes in the URI. For S3
* and other AWS services, this is allowed and required. This methods replaces
* any occurrence of "//" in the URI path with "/%2F".
*
* @see SdkHttpRequest#getUri()
* @param request The existing request
* @return a new String containing the modified URI
*/
private URI sanitizeUri(SdkHttpRequest request) {
String path = request.encodedPath();
if (path.contains("//")) {
int port = request.port();
String protocol = request.protocol();
String newPath = StringUtils.replace(path, "//", "/%2F");
String encodedQueryString = request.encodedQueryParameters().map(value -> "?" + value).orElse("");
// Do not include the port in the URI when using the default port for the protocol.
String portString = SdkHttpUtils.isUsingStandardPort(protocol, port) ?
"" : ":" + port;
return URI.create(protocol + "://" + request.host() + portString + newPath + encodedQueryString);
}
return request.getUri();
}
private void addRequestConfig(final HttpRequestBase base,
final SdkHttpRequest request,
final ApacheHttpRequestConfig requestConfig) {
int connectTimeout = saturatedCast(requestConfig.connectionTimeout().toMillis());
int connectAcquireTimeout = saturatedCast(requestConfig.connectionAcquireTimeout().toMillis());
RequestConfig.Builder requestConfigBuilder = RequestConfig
.custom()
.setConnectionRequestTimeout(connectAcquireTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(saturatedCast(requestConfig.socketTimeout().toMillis()))
.setLocalAddress(requestConfig.localAddress());
ApacheUtils.disableNormalizeUri(requestConfigBuilder);
/*
* Enable 100-continue support for PUT operations, since this is
* where we're potentially uploading large amounts of data and want
* to find out as early as possible if an operation will fail. We
* don't want to do this for all operations since it will cause
* extra latency in the network interaction.
*/
if (SdkHttpMethod.PUT == request.method() && requestConfig.expectContinueEnabled()) {
requestConfigBuilder.setExpectContinueEnabled(true);
}
base.setConfig(requestConfigBuilder.build());
}
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, URI uri) {
switch (request.httpRequest().method()) {
case HEAD:
return new HttpHead(uri);
case GET:
return new HttpGet(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case PATCH:
return wrapEntity(request, new HttpPatch(uri));
case POST:
return wrapEntity(request, new HttpPost(uri));
case PUT:
return wrapEntity(request, new HttpPut(uri));
default:
throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
}
}
private HttpRequestBase wrapEntity(HttpExecuteRequest request,
HttpEntityEnclosingRequestBase entityEnclosingRequest) {
/*
* We should never reuse the entity of the previous request, since
* reading from the buffered entity will bypass reading from the
* original request content. And if the content contains InputStream
* wrappers that were added for validation-purpose (e.g.
* Md5DigestCalculationInputStream), these wrappers would never be
* read and updated again after AmazonHttpClient resets it in
* preparation for the retry. Eventually, these wrappers would
* return incorrect validation result.
*/
if (request.contentStreamProvider().isPresent()) {
HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
if (!request.httpRequest().firstMatchingHeader(HttpHeaders.CONTENT_LENGTH).isPresent() && !entity.isChunked()) {
entity = ApacheUtils.newBufferedHttpEntity(entity);
}
entityEnclosingRequest.setEntity(entity);
}
return entityEnclosingRequest;
}
/**
* Configures the headers in the specified Apache HTTP request.
*/
private void addHeadersToRequest(HttpRequestBase httpRequest, SdkHttpRequest request) {
httpRequest.addHeader(HttpHeaders.HOST, getHostHeaderValue(request));
// Copy over any other headers already in our request
request.forEachHeader((name, value) -> {
// HttpClient4 fills in the Content-Length header and complains if
// it's already present, so we skip it here. We also skip the Host
// header to avoid sending it twice, which will interfere with some
// signing schemes.
if (!IGNORE_HEADERS.contains(name)) {
for (String headerValue : value) {
httpRequest.addHeader(name, headerValue);
}
}
});
}
private String getHostHeaderValue(SdkHttpRequest request) {
// Apache doesn't allow us to include the port in the host header if it's a standard port for that protocol. For that
// reason, we don't include the port when we sign the message. See {@link SdkHttpRequest#port()}.
return !SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port())
? request.host() + ":" + request.port()
: request.host();
}
}
| 985 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ApacheSdkHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An instance of {@link ConnectionManagerAwareHttpClient} that delegates all the requests to the given http client.
*/
@SdkInternalApi
public class ApacheSdkHttpClient implements ConnectionManagerAwareHttpClient {
private final HttpClient delegate;
private final HttpClientConnectionManager cm;
public ApacheSdkHttpClient(final HttpClient delegate,
final HttpClientConnectionManager cm) {
if (delegate == null) {
throw new IllegalArgumentException("delegate " +
"cannot be null");
}
if (cm == null) {
throw new IllegalArgumentException("connection manager " +
"cannot be null");
}
this.delegate = delegate;
this.cm = cm;
}
@Override
public HttpParams getParams() {
return delegate.getParams();
}
@Override
public ClientConnectionManager getConnectionManager() {
return delegate.getConnectionManager();
}
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException {
return delegate.execute(request);
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
return delegate.execute(request, context);
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
return delegate.execute(target, request);
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
return delegate.execute(target, request, context);
}
@Override
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
return delegate.execute(request, responseHandler);
}
@Override
public <T> T execute(HttpUriRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
return delegate.execute(request, responseHandler, context);
}
@Override
public <T> T execute(HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler) throws IOException {
return delegate.execute(target, request, responseHandler);
}
@Override
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler,
HttpContext context) throws IOException {
return delegate.execute(target, request, responseHandler, context);
}
@Override
public HttpClientConnectionManager getHttpClientConnectionManager() {
return cm;
}
}
| 986 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/impl/ConnectionManagerAwareHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.impl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.HttpClientConnectionManager;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An extension of Apache's HttpClient that expose the connection manager
* associated with the client.
*/
@SdkInternalApi
public interface ConnectionManagerAwareHttpClient extends HttpClient {
/**
* Returns the {@link HttpClientConnectionManager} associated with the
* http client.
*/
HttpClientConnectionManager getHttpClientConnectionManager();
}
| 987 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/DelegateSslSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public class DelegateSslSocket extends SSLSocket {
protected final SSLSocket sock;
public DelegateSslSocket(SSLSocket sock) {
this.sock = sock;
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
sock.connect(endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
sock.connect(endpoint, timeout);
}
@Override
public void bind(SocketAddress bindpoint) throws IOException {
sock.bind(bindpoint);
}
@Override
public InetAddress getInetAddress() {
return sock.getInetAddress();
}
@Override
public InetAddress getLocalAddress() {
return sock.getLocalAddress();
}
@Override
public int getPort() {
return sock.getPort();
}
@Override
public int getLocalPort() {
return sock.getLocalPort();
}
@Override
public SocketAddress getRemoteSocketAddress() {
return sock.getRemoteSocketAddress();
}
@Override
public SocketAddress getLocalSocketAddress() {
return sock.getLocalSocketAddress();
}
@Override
public SocketChannel getChannel() {
return sock.getChannel();
}
@Override
public InputStream getInputStream() throws IOException {
return sock.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return sock.getOutputStream();
}
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
sock.setTcpNoDelay(on);
}
@Override
public boolean getTcpNoDelay() throws SocketException {
return sock.getTcpNoDelay();
}
@Override
public void setSoLinger(boolean on, int linger) throws SocketException {
sock.setSoLinger(on, linger);
}
@Override
public int getSoLinger() throws SocketException {
return sock.getSoLinger();
}
@Override
public void sendUrgentData(int data) throws IOException {
sock.sendUrgentData(data);
}
@Override
public void setOOBInline(boolean on) throws SocketException {
sock.setOOBInline(on);
}
@Override
public boolean getOOBInline() throws SocketException {
return sock.getOOBInline();
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
sock.setSoTimeout(timeout);
}
@Override
public int getSoTimeout() throws SocketException {
return sock.getSoTimeout();
}
@Override
public void setSendBufferSize(int size) throws SocketException {
sock.setSendBufferSize(size);
}
@Override
public int getSendBufferSize() throws SocketException {
return sock.getSendBufferSize();
}
@Override
public void setReceiveBufferSize(int size) throws SocketException {
sock.setReceiveBufferSize(size);
}
@Override
public int getReceiveBufferSize() throws SocketException {
return sock.getReceiveBufferSize();
}
@Override
public void setKeepAlive(boolean on) throws SocketException {
sock.setKeepAlive(on);
}
@Override
public boolean getKeepAlive() throws SocketException {
return sock.getKeepAlive();
}
@Override
public void setTrafficClass(int tc) throws SocketException {
sock.setTrafficClass(tc);
}
@Override
public int getTrafficClass() throws SocketException {
return sock.getTrafficClass();
}
@Override
public void setReuseAddress(boolean on) throws SocketException {
sock.setReuseAddress(on);
}
@Override
public boolean getReuseAddress() throws SocketException {
return sock.getReuseAddress();
}
@Override
public void close() throws IOException {
sock.close();
}
@Override
public void shutdownInput() throws IOException {
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
sock.shutdownOutput();
}
@Override
public String toString() {
return sock.toString();
}
@Override
public boolean isConnected() {
return sock.isConnected();
}
@Override
public boolean isBound() {
return sock.isBound();
}
@Override
public boolean isClosed() {
return sock.isClosed();
}
@Override
public boolean isInputShutdown() {
return sock.isInputShutdown();
}
@Override
public boolean isOutputShutdown() {
return sock.isOutputShutdown();
}
@Override
public void setPerformancePreferences(int connectionTime, int latency,
int bandwidth) {
sock.setPerformancePreferences(connectionTime, latency, bandwidth);
}
@Override
public String[] getSupportedCipherSuites() {
return sock.getSupportedCipherSuites();
}
@Override
public String[] getEnabledCipherSuites() {
return sock.getEnabledCipherSuites();
}
@Override
public void setEnabledCipherSuites(String[] suites) {
sock.setEnabledCipherSuites(suites);
}
@Override
public String[] getSupportedProtocols() {
return sock.getSupportedProtocols();
}
@Override
public String[] getEnabledProtocols() {
return sock.getEnabledProtocols();
}
@Override
public void setEnabledProtocols(String[] protocols) {
sock.setEnabledProtocols(protocols);
}
@Override
public SSLSession getSession() {
return sock.getSession();
}
@Override
public void addHandshakeCompletedListener(
HandshakeCompletedListener listener) {
sock.addHandshakeCompletedListener(listener);
}
@Override
public void removeHandshakeCompletedListener(
HandshakeCompletedListener listener) {
sock.removeHandshakeCompletedListener(listener);
}
@Override
public void startHandshake() throws IOException {
sock.startHandshake();
}
@Override
public void setUseClientMode(boolean mode) {
sock.setUseClientMode(mode);
}
@Override
public boolean getUseClientMode() {
return sock.getUseClientMode();
}
@Override
public void setNeedClientAuth(boolean need) {
sock.setNeedClientAuth(need);
}
@Override
public boolean getNeedClientAuth() {
return sock.getNeedClientAuth();
}
@Override
public void setWantClientAuth(boolean want) {
sock.setWantClientAuth(want);
}
@Override
public boolean getWantClientAuth() {
return sock.getWantClientAuth();
}
@Override
public void setEnableSessionCreation(boolean flag) {
sock.setEnableSessionCreation(flag);
}
@Override
public boolean getEnableSessionCreation() {
return sock.getEnableSessionCreation();
}
}
| 988 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/SdkSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkSocket extends DelegateSocket {
private static final Logger log = Logger.loggerFor(SdkSocket.class);
public SdkSocket(Socket sock) {
super(sock);
log.debug(() -> "created: " + endpoint());
}
/**
* Returns the endpoint in the format of "address:port"
*/
private String endpoint() {
return sock.getInetAddress() + ":" + sock.getPort();
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint, timeout);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void close() throws IOException {
log.debug(() -> "closing " + endpoint());
sock.close();
}
@Override
public void shutdownInput() throws IOException {
log.debug(() -> "shutting down input of " + endpoint());
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
log.debug(() -> "shutting down output of " + endpoint());
sock.shutdownOutput();
}
}
| 989 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/DelegateSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Socket delegate class. Subclasses could extend this class, so that
* they only need to override methods they are interested in enhancing.
*/
@SdkInternalApi
public class DelegateSocket extends Socket {
protected final Socket sock;
public DelegateSocket(Socket sock) {
this.sock = sock;
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
sock.connect(endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
sock.connect(endpoint, timeout);
}
@Override
public void bind(SocketAddress bindpoint) throws IOException {
sock.bind(bindpoint);
}
@Override
public InetAddress getInetAddress() {
return sock.getInetAddress();
}
@Override
public InetAddress getLocalAddress() {
return sock.getLocalAddress();
}
@Override
public int getPort() {
return sock.getPort();
}
@Override
public int getLocalPort() {
return sock.getLocalPort();
}
@Override
public SocketAddress getRemoteSocketAddress() {
return sock.getRemoteSocketAddress();
}
@Override
public SocketAddress getLocalSocketAddress() {
return sock.getLocalSocketAddress();
}
@Override
public SocketChannel getChannel() {
return sock.getChannel();
}
@Override
public InputStream getInputStream() throws IOException {
return sock.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return sock.getOutputStream();
}
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
sock.setTcpNoDelay(on);
}
@Override
public boolean getTcpNoDelay() throws SocketException {
return sock.getTcpNoDelay();
}
@Override
public void setSoLinger(boolean on, int linger) throws SocketException {
sock.setSoLinger(on, linger);
}
@Override
public int getSoLinger() throws SocketException {
return sock.getSoLinger();
}
@Override
public void sendUrgentData(int data) throws IOException {
sock.sendUrgentData(data);
}
@Override
public void setOOBInline(boolean on) throws SocketException {
sock.setOOBInline(on);
}
@Override
public boolean getOOBInline() throws SocketException {
return sock.getOOBInline();
}
@Override
public void setSoTimeout(int timeout) throws SocketException {
sock.setSoTimeout(timeout);
}
@Override
public int getSoTimeout() throws SocketException {
return sock.getSoTimeout();
}
@Override
public void setSendBufferSize(int size) throws SocketException {
sock.setSendBufferSize(size);
}
@Override
public int getSendBufferSize() throws SocketException {
return sock.getSendBufferSize();
}
@Override
public void setReceiveBufferSize(int size) throws SocketException {
sock.setReceiveBufferSize(size);
}
@Override
public int getReceiveBufferSize() throws SocketException {
return sock.getReceiveBufferSize();
}
@Override
public void setKeepAlive(boolean on) throws SocketException {
sock.setKeepAlive(on);
}
@Override
public boolean getKeepAlive() throws SocketException {
return sock.getKeepAlive();
}
@Override
public void setTrafficClass(int tc) throws SocketException {
sock.setTrafficClass(tc);
}
@Override
public int getTrafficClass() throws SocketException {
return sock.getTrafficClass();
}
@Override
public void setReuseAddress(boolean on) throws SocketException {
sock.setReuseAddress(on);
}
@Override
public boolean getReuseAddress() throws SocketException {
return sock.getReuseAddress();
}
@Override
public void close() throws IOException {
sock.close();
}
@Override
public void shutdownInput() throws IOException {
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
sock.shutdownOutput();
}
@Override
public String toString() {
return sock.toString();
}
@Override
public boolean isConnected() {
return sock.isConnected();
}
@Override
public boolean isBound() {
return sock.isBound();
}
@Override
public boolean isClosed() {
return sock.isClosed();
}
@Override
public boolean isInputShutdown() {
return sock.isInputShutdown();
}
@Override
public boolean isOutputShutdown() {
return sock.isOutputShutdown();
}
@Override
public void setPerformancePreferences(int connectionTime, int latency,
int bandwidth) {
sock.setPerformancePreferences(connectionTime, latency, bandwidth);
}
}
| 990 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/net/SdkSslSocket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.net;
import java.io.IOException;
import java.net.SocketAddress;
import javax.net.ssl.SSLSocket;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkSslSocket extends DelegateSslSocket {
private static final Logger log = Logger.loggerFor(SdkSslSocket.class);
public SdkSslSocket(SSLSocket sock) {
super(sock);
log.debug(() -> "created: " + endpoint());
}
/**
* Returns the endpoint in the format of "address:port"
*/
private String endpoint() {
return sock.getInetAddress() + ":" + sock.getPort();
}
@Override
public void connect(SocketAddress endpoint) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
log.trace(() -> "connecting to: " + endpoint);
sock.connect(endpoint, timeout);
log.debug(() -> "connected to: " + endpoint);
}
@Override
public void close() throws IOException {
log.debug(() -> "closing " + endpoint());
sock.close();
}
@Override
public void shutdownInput() throws IOException {
log.debug(() -> "shutting down input of " + endpoint());
sock.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
log.debug(() -> "shutting down output of " + endpoint());
sock.shutdownOutput();
}
}
| 991 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/utils/ApacheUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.utils;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.ProxyConfiguration;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ReflectionMethodInvoker;
@SdkInternalApi
public final class ApacheUtils {
private static final Logger logger = Logger.loggerFor(ApacheUtils.class);
private static final ReflectionMethodInvoker<RequestConfig.Builder, RequestConfig.Builder> NORMALIZE_URI_INVOKER;
static {
// Attempt to initialize the invoker once on class-load. If it fails, it will not be attempted again, but we'll
// use that opportunity to log a warning.
NORMALIZE_URI_INVOKER =
new ReflectionMethodInvoker<>(RequestConfig.Builder.class,
RequestConfig.Builder.class,
"setNormalizeUri",
boolean.class);
try {
NORMALIZE_URI_INVOKER.initialize();
} catch (NoSuchMethodException ignored) {
noSuchMethodThrownByNormalizeUriInvoker();
}
}
private ApacheUtils() {
}
/**
* Utility function for creating a new BufferedEntity and wrapping any errors
* as a SdkClientException.
*
* @param entity The HTTP entity to wrap with a buffered HTTP entity.
* @return A new BufferedHttpEntity wrapping the specified entity.
*/
public static HttpEntity newBufferedHttpEntity(HttpEntity entity) {
try {
return new BufferedHttpEntity(entity);
} catch (IOException e) {
throw new UncheckedIOException("Unable to create HTTP entity: " + e.getMessage(), e);
}
}
/**
* Returns a new HttpClientContext used for request execution.
*/
public static HttpClientContext newClientContext(ProxyConfiguration proxyConfiguration) {
HttpClientContext clientContext = new HttpClientContext();
addPreemptiveAuthenticationProxy(clientContext, proxyConfiguration);
RequestConfig.Builder builder = RequestConfig.custom();
disableNormalizeUri(builder);
clientContext.setRequestConfig(builder.build());
return clientContext;
}
/**
* From Apache v4.5.8, normalization should be disabled or AWS requests with special characters in URI path will fail
* with Signature Errors.
* <p>
* setNormalizeUri is added only in 4.5.8, so customers using the latest version of SDK with old versions (4.5.6 or less)
* of Apache httpclient will see NoSuchMethodError. Hence this method will suppress the error.
*
* Do not use Apache version 4.5.7 as it breaks URI paths with special characters and there is no option
* to disable normalization.
* </p>
*
* For more information, See https://github.com/aws/aws-sdk-java/issues/1919
*/
public static void disableNormalizeUri(RequestConfig.Builder requestConfigBuilder) {
// For efficiency, do not attempt to call the invoker again if it failed to initialize on class-load
if (NORMALIZE_URI_INVOKER.isInitialized()) {
try {
NORMALIZE_URI_INVOKER.invoke(requestConfigBuilder, false);
} catch (NoSuchMethodException ignored) {
noSuchMethodThrownByNormalizeUriInvoker();
}
}
}
/**
* Returns a new Credentials Provider for use with proxy authentication.
*/
public static CredentialsProvider newProxyCredentialsProvider(ProxyConfiguration proxyConfiguration) {
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(newAuthScope(proxyConfiguration), newNtCredentials(proxyConfiguration));
return provider;
}
/**
* Returns a new instance of NTCredentials used for proxy authentication.
*/
private static Credentials newNtCredentials(ProxyConfiguration proxyConfiguration) {
return new NTCredentials(proxyConfiguration.username(),
proxyConfiguration.password(),
proxyConfiguration.ntlmWorkstation(),
proxyConfiguration.ntlmDomain());
}
/**
* Returns a new instance of AuthScope used for proxy authentication.
*/
private static AuthScope newAuthScope(ProxyConfiguration proxyConfiguration) {
return new AuthScope(proxyConfiguration.host(), proxyConfiguration.port());
}
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
ProxyConfiguration proxyConfiguration) {
if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
HttpHost targetHost = new HttpHost(proxyConfiguration.host(), proxyConfiguration.port());
CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
clientContext.setCredentialsProvider(credsProvider);
clientContext.setAuthCache(authCache);
}
}
// Just log and then swallow the exception
private static void noSuchMethodThrownByNormalizeUriInvoker() {
// setNormalizeUri method was added in httpclient 4.5.8
logger.warn(() -> "NoSuchMethodException was thrown when disabling normalizeUri. This indicates you are using "
+ "an old version (< 4.5.8) of Apache http client. It is recommended to use http client "
+ "version >= 4.5.9 to avoid the breaking change introduced in apache client 4.5.7 and "
+ "the latency in exception handling. See https://github.com/aws/aws-sdk-java/issues/1919"
+ " for more information");
}
}
| 992 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/SdkConnectionKeepAliveStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* The AWS SDK for Java's implementation of the
* {@code ConnectionKeepAliveStrategy} interface. Allows a user-configurable
* maximum idle time for connections.
*/
@SdkInternalApi
public class SdkConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
private final long maxIdleTime;
/**
* @param maxIdleTime the maximum time a connection may be idle
*/
public SdkConnectionKeepAliveStrategy(long maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
@Override
public long getKeepAliveDuration(
HttpResponse response,
HttpContext context) {
// If there's a Keep-Alive timeout directive in the response and it's
// shorter than our configured max, honor that. Otherwise go with the
// configured maximum.
long duration = DefaultConnectionKeepAliveStrategy.INSTANCE
.getKeepAliveDuration(response, context);
if (0 < duration && duration < maxIdleTime) {
return duration;
}
return maxIdleTime;
}
}
| 993 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/SdkTlsSocketFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpHost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.apache.internal.net.SdkSocket;
import software.amazon.awssdk.http.apache.internal.net.SdkSslSocket;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public class SdkTlsSocketFactory extends SSLConnectionSocketFactory {
private static final Logger log = Logger.loggerFor(SdkTlsSocketFactory.class);
private final SSLContext sslContext;
public SdkTlsSocketFactory(final SSLContext sslContext, final HostnameVerifier hostnameVerifier) {
super(sslContext, hostnameVerifier);
if (sslContext == null) {
throw new IllegalArgumentException(
"sslContext must not be null. " + "Use SSLContext.getDefault() if you are unsure.");
}
this.sslContext = sslContext;
}
@Override
protected final void prepareSocket(final SSLSocket socket) {
log.debug(() -> String.format("socket.getSupportedProtocols(): %s, socket.getEnabledProtocols(): %s",
Arrays.toString(socket.getSupportedProtocols()),
Arrays.toString(socket.getEnabledProtocols())));
}
@Override
public Socket connectSocket(
final int connectTimeout,
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException {
log.trace(() -> String.format("Connecting to %s:%s", remoteAddress.getAddress(), remoteAddress.getPort()));
Socket connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
if (connectedSocket instanceof SSLSocket) {
return new SdkSslSocket((SSLSocket) connectedSocket);
}
return new SdkSocket(connectedSocket);
}
}
| 994 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/IdleConnectionReaper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
/**
* Manages the reaping of idle connections.
*/
@SdkInternalApi
public final class IdleConnectionReaper {
private static final Logger log = LoggerFactory.getLogger(IdleConnectionReaper.class);
private static final IdleConnectionReaper INSTANCE = new IdleConnectionReaper();
private final Map<HttpClientConnectionManager, Long> connectionManagers;
private final Supplier<ExecutorService> executorServiceSupplier;
private final long sleepPeriod;
private volatile ExecutorService exec;
private volatile ReaperTask reaperTask;
private IdleConnectionReaper() {
this.connectionManagers = Collections.synchronizedMap(new WeakHashMap<>());
this.executorServiceSupplier = () -> {
ExecutorService e = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "idle-connection-reaper");
t.setDaemon(true);
return t;
});
return e;
};
this.sleepPeriod = Duration.ofMinutes(1).toMillis();
}
@SdkTestInternalApi
IdleConnectionReaper(Map<HttpClientConnectionManager, Long> connectionManagers,
Supplier<ExecutorService> executorServiceSupplier,
long sleepPeriod) {
this.connectionManagers = connectionManagers;
this.executorServiceSupplier = executorServiceSupplier;
this.sleepPeriod = sleepPeriod;
}
/**
* Register the connection manager with this reaper.
*
* @param manager The connection manager.
* @param maxIdleTime The maximum time connections in the connection manager are to remain idle before being reaped.
* @return {@code true} If the connection manager was not previously registered with this reaper, {@code false}
* otherwise.
*/
public synchronized boolean registerConnectionManager(HttpClientConnectionManager manager, long maxIdleTime) {
boolean notPreviouslyRegistered = connectionManagers.put(manager, maxIdleTime) == null;
setupExecutorIfNecessary();
return notPreviouslyRegistered;
}
/**
* Deregister this connection manager with this reaper.
*
* @param manager The connection manager.
* @return {@code true} If this connection manager was previously registered with this reaper and it was removed, {@code
* false} otherwise.
*/
public synchronized boolean deregisterConnectionManager(HttpClientConnectionManager manager) {
boolean wasRemoved = connectionManagers.remove(manager) != null;
cleanupExecutorIfNecessary();
return wasRemoved;
}
/**
* @return The singleton instance of this class.
*/
public static IdleConnectionReaper getInstance() {
return INSTANCE;
}
private void setupExecutorIfNecessary() {
if (exec != null) {
return;
}
ExecutorService e = executorServiceSupplier.get();
this.reaperTask = new ReaperTask(connectionManagers, sleepPeriod);
e.execute(this.reaperTask);
exec = e;
}
private void cleanupExecutorIfNecessary() {
if (exec == null || !connectionManagers.isEmpty()) {
return;
}
reaperTask.stop();
reaperTask = null;
exec.shutdownNow();
exec = null;
}
private static final class ReaperTask implements Runnable {
private final Map<HttpClientConnectionManager, Long> connectionManagers;
private final long sleepPeriod;
private volatile boolean stopping = false;
private ReaperTask(Map<HttpClientConnectionManager, Long> connectionManagers,
long sleepPeriod) {
this.connectionManagers = connectionManagers;
this.sleepPeriod = sleepPeriod;
}
@Override
public void run() {
while (!stopping) {
try {
Thread.sleep(sleepPeriod);
for (Map.Entry<HttpClientConnectionManager, Long> entry : connectionManagers.entrySet()) {
try {
entry.getKey().closeIdleConnections(entry.getValue(), TimeUnit.MILLISECONDS);
} catch (Exception t) {
log.warn("Unable to close idle connections", t);
}
}
} catch (Throwable t) {
log.debug("Reaper thread: ", t);
}
}
log.debug("Shutting down reaper thread.");
}
private void stop() {
stopping = true;
}
}
}
| 995 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionRequestFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class ClientConnectionRequestFactory {
/**
* {@link ThreadLocal}, request-level {@link MetricCollector}, set and removed by {@link ApacheHttpClient}.
*/
public static final ThreadLocal<MetricCollector> THREAD_LOCAL_REQUEST_METRIC_COLLECTOR = new ThreadLocal<>();
private ClientConnectionRequestFactory() {
}
/**
* Returns a wrapped instance of {@link ConnectionRequest}
* to capture the necessary performance metrics.
*
* @param orig the target instance to be wrapped
*/
static ConnectionRequest wrap(ConnectionRequest orig) {
if (orig instanceof DelegatingConnectionRequest) {
throw new IllegalArgumentException();
}
return new InstrumentedConnectionRequest(orig);
}
/**
* Measures the latency of {@link ConnectionRequest#get(long, java.util.concurrent.TimeUnit)}.
*/
private static class InstrumentedConnectionRequest extends DelegatingConnectionRequest {
private InstrumentedConnectionRequest(ConnectionRequest delegate) {
super(delegate);
}
@Override
public HttpClientConnection get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException,
ConnectionPoolTimeoutException {
Instant startTime = Instant.now();
try {
return super.get(timeout, timeUnit);
} finally {
Duration elapsed = Duration.between(startTime, Instant.now());
MetricCollector metricCollector = THREAD_LOCAL_REQUEST_METRIC_COLLECTOR.get();
metricCollector.reportMetric(HttpMetric.CONCURRENCY_ACQUIRE_DURATION, elapsed);
}
}
}
/**
* Delegates all methods to {@link ConnectionRequest}. Subclasses can override select methods to change behavior.
*/
private static class DelegatingConnectionRequest implements ConnectionRequest {
private final ConnectionRequest delegate;
private DelegatingConnectionRequest(ConnectionRequest delegate) {
this.delegate = delegate;
}
@Override
public HttpClientConnection get(long timeout, TimeUnit timeUnit)
throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
return delegate.get(timeout, timeUnit);
}
@Override
public boolean cancel() {
return delegate.cancel();
}
}
}
| 996 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/Wrapped.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An internal marker interface to defend against accidental recursive wrappings.
*/
@SdkInternalApi
public interface Wrapped {
}
| 997 |
0 | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal | Create_ds/aws-sdk-java-v2/http-clients/apache-client/src/main/java/software/amazon/awssdk/http/apache/internal/conn/ClientConnectionManagerFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.apache.internal.conn;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpClientConnection;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.protocol.HttpContext;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class ClientConnectionManagerFactory {
private ClientConnectionManagerFactory() {
}
/**
* Returns a wrapped instance of {@link HttpClientConnectionManager}
* to capture the necessary performance metrics.
*
* @param orig the target instance to be wrapped
*/
public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) {
if (orig instanceof DelegatingHttpClientConnectionManager) {
throw new IllegalArgumentException();
}
return new InstrumentedHttpClientConnectionManager(orig);
}
/**
* Further wraps {@link ConnectionRequest} to capture performance metrics.
*/
private static class InstrumentedHttpClientConnectionManager extends DelegatingHttpClientConnectionManager {
private InstrumentedHttpClientConnectionManager(HttpClientConnectionManager delegate) {
super(delegate);
}
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
ConnectionRequest connectionRequest = super.requestConnection(route, state);
return ClientConnectionRequestFactory.wrap(connectionRequest);
}
}
/**
* Delegates all methods to {@link HttpClientConnectionManager}. Subclasses can override select methods to change behavior.
*/
private static class DelegatingHttpClientConnectionManager implements HttpClientConnectionManager {
private final HttpClientConnectionManager delegate;
protected DelegatingHttpClientConnectionManager(HttpClientConnectionManager delegate) {
this.delegate = delegate;
}
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
return delegate.requestConnection(route, state);
}
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
delegate.releaseConnection(conn, newState, validDuration, timeUnit);
}
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context)
throws IOException {
delegate.connect(conn, route, connectTimeout, context);
}
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
delegate.upgrade(conn, route, context);
}
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
delegate.routeComplete(conn, route, context);
}
@Override
public void closeIdleConnections(long idletime, TimeUnit timeUnit) {
delegate.closeIdleConnections(idletime, timeUnit);
}
@Override
public void closeExpiredConnections() {
delegate.closeExpiredConnections();
}
@Override
public void shutdown() {
delegate.shutdown();
}
}
}
| 998 |
0 | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http | Create_ds/aws-sdk-java-v2/http-clients/aws-crt-client/src/test/java/software/amazon/awssdk/http/crt/ConnectionHealthConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class ConnectionHealthConfigurationTest {
@Test
void builder_allPropertiesSet() {
ConnectionHealthConfiguration connectionHealthConfiguration =
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(123l)
.minimumThroughputTimeout(Duration.ofSeconds(1))
.build();
assertThat(connectionHealthConfiguration.minimumThroughputInBps()).isEqualTo(123);
assertThat(connectionHealthConfiguration.minimumThroughputTimeout()).isEqualTo(Duration.ofSeconds(1));
}
@Test
void builder_nullMinimumThroughputInBps_shouldThrowException() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputTimeout(Duration.ofSeconds(1))
.build()).hasMessageContaining("minimumThroughputInBps");
}
@Test
void builder_nullMinimumThroughputTimeout() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(1L)
.build()).hasMessageContaining("minimumThroughputTimeout");
}
@Test
void builder_negativeMinimumThroughputTimeout() {
assertThatThrownBy(() ->
ConnectionHealthConfiguration.builder()
.minimumThroughputInBps(1L)
.minimumThroughputTimeout(Duration.ofSeconds(-1))
.build()).hasMessageContaining("minimumThroughputTimeout");
}
}
| 999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.