Skip to content

Commit

Permalink
feat: 204 as NO_BIDS and custom headers #320 #338
Browse files Browse the repository at this point in the history
  • Loading branch information
ValentinPostindustria committed Mar 1, 2022
1 parent 39e48ec commit 057d3bf
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

public class PrebidMobile {

Expand Down Expand Up @@ -86,23 +83,46 @@ public static boolean isShareGeoLocation() {

private static List<ExternalUserId> externalUserIds = new ArrayList<>();

private static HashMap<String, String> customHeaders = new HashMap<>();

private static boolean assignNativeAssetID = false;

/**
* List containing objects that hold External UserId parameters for the current application user.
*
* @param externalUserIds
*/
public static void setExternalUserIds(List<ExternalUserId> externalUserIds){
public static void setExternalUserIds(List<ExternalUserId> externalUserIds) {
PrebidMobile.externalUserIds = externalUserIds;
}

/**
* Returns the List that hold External UserId parameters for the current application user
*
* @@return externalUserIds as Array.
*/
public static List<ExternalUserId> getExternalUserIds() {
return PrebidMobile.externalUserIds;
}

/**
* HashMap containing a list of custom headers to add to requests
*
* @param customHeaders
*/
public static void setCustomHeaders(HashMap<String, String> customHeaders) {
PrebidMobile.customHeaders = customHeaders;
}

/**
* Returns the HashMap containing a list of custom headers to add to requests
*
* @@return externalUserIds as Array.
*/
public static HashMap<String, String> getCustomHeaders() {
return PrebidMobile.customHeaders;
}

private static WeakReference<Context> applicationContextWeak;

public static void setApplicationContext(Context context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,17 @@ protected TaskResult<JSONObject> makeHttpRequest() {
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
if(canIAccessDeviceData()) {
setCustomHeadersIfAvailable(conn);

if (canIAccessDeviceData()) {
String existingCookie = getExistingCookie();
if (existingCookie != null) {
conn.setRequestProperty(COOKIE_HEADER, existingCookie);
} // todo still pass cookie if limit ad tracking?
}
conn.setRequestMethod("POST");
conn.setConnectTimeout(PrebidMobile.getTimeoutMillis());
conn.setReadTimeout(PrebidMobile.getTimeoutMillis());

// Add post data
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
Expand Down Expand Up @@ -132,6 +135,10 @@ protected TaskResult<JSONObject> makeHttpRequest() {
BidLog.getInstance().setLastEntry(entry);

return new TaskResult<>(response);
} else if (httpResult == HttpURLConnection.HTTP_NO_CONTENT) {
entry.setResponse("");
BidLog.getInstance().setLastEntry(entry);
return new TaskResult<>(new JSONObject());
} else if (httpResult >= HttpURLConnection.HTTP_BAD_REQUEST) {
StringBuilder builder = new StringBuilder();
InputStream is = conn.getErrorStream();
Expand Down Expand Up @@ -185,6 +192,14 @@ protected TaskResult<JSONObject> makeHttpRequest() {
return new TaskResult<>(new RuntimeException("ServerConnector exception"));
}

private void setCustomHeadersIfAvailable(HttpURLConnection conn) {
if (!PrebidMobile.getCustomHeaders().isEmpty()) {
for (Map.Entry<String, String> customHeader : PrebidMobile.getCustomHeaders().entrySet()) {
conn.setRequestProperty(customHeader.getKey(), customHeader.getValue());
}
}
}

private void postResultOnMainThread(final TaskResult<JSONObject> result) {
TasksManager.getInstance().executeOnMainThread(new Runnable() {
@Override
Expand Down
17 changes: 14 additions & 3 deletions PrebidMobile/src/test/java/org/prebid/mobile/PrebidMobileTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;

import static org.junit.Assert.*;

@RunWith(RobolectricTestRunner.class)
@Config(sdk = BaseSetup.testSDK)
Expand All @@ -51,4 +51,15 @@ public void testPrebidMobileSettings() {
PrebidMobile.setPbsDebug(true);
assertTrue(PrebidMobile.getPbsDebug());
}

@Test
public void testSetCustomHeaders() {
HashMap<String, String> customHeaders = new HashMap<>();
customHeaders.put("key1", "value1");
customHeaders.put("key2", "value2");
PrebidMobile.setCustomHeaders(customHeaders);

assertFalse(PrebidMobile.getCustomHeaders().isEmpty());
assertEquals(2, PrebidMobile.getCustomHeaders().size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import android.util.Log;
import androidx.annotation.Nullable;
import com.mopub.mobileads.MoPubView;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
Expand Down Expand Up @@ -342,6 +343,31 @@ public void testNoBidResponse() {
verify(mockListener).onDemandFailed(ResultCode.NO_BIDS, uuid);
}

@Test
public void testBlankResponseReturnsNoBid() {
server.enqueue(new MockResponse().setResponseCode(204).setBody(""));
HttpUrl hostUrl = server.url("/");
Host.CUSTOM.setHostUrl(hostUrl.toString());
PrebidMobile.setPrebidServerHost(Host.CUSTOM);
PrebidMobile.setPrebidServerAccountId("12345");
PrebidMobile.setShareGeoLocation(true);
PrebidMobile.setApplicationContext(activity.getApplicationContext());
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(320, 50));
RequestParams requestParams = new RequestParams("67890", AdType.BANNER, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);

ShadowLooper bgLooper = Shadows.shadowOf(((BackgroundThreadExecutor) TasksManager.getInstance().backgroundThreadExecutor).getBackgroundHandler().getLooper());
bgLooper.runToEndOfTasks();

Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
verify(mockListener).onDemandFailed(ResultCode.NO_BIDS, uuid);
}

@Test
public void testNoBidRubiconResponse() {
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.noBidFromRubicon()));
Expand Down Expand Up @@ -1262,6 +1288,37 @@ public void testStoredExternalUserIdsInPostDataWithEmptyExt() throws Exception {
assertFalse(user.getJSONObject("ext").getJSONArray("eids").getJSONObject(0).getJSONArray("uids").getJSONObject(0).has("ext"));
}

@Test
public void testConnectionHasSetCustomHeaders() throws Exception {
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.oneBidFromAppNexus()));
HttpUrl hostUrl = server.url("/");
Host.CUSTOM.setHostUrl(hostUrl.toString());
PrebidMobile.setPrebidServerHost(Host.CUSTOM);
PrebidMobile.setPrebidServerAccountId("12345");
PrebidMobile.setShareGeoLocation(true);
PrebidMobile.setApplicationContext(activity.getApplicationContext());
HashMap<String, String> customHeaders = new HashMap<>();
customHeaders.put("test-key", "test-value");
PrebidMobile.setCustomHeaders(customHeaders);
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(300, 250));
RequestParams requestParams = new RequestParams("67890", AdType.BANNER, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);

ShadowLooper bgLooper = Shadows.shadowOf(((BackgroundThreadExecutor) TasksManager.getInstance().backgroundThreadExecutor).getBackgroundHandler().getLooper());
bgLooper.runToEndOfTasks();

Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();

RecordedRequest recordedRequest = server.takeRequest();
Headers headers = recordedRequest.getHeaders();
assertEquals("test-value", headers.get("test-key"));
}

@Test
public void testRubiconDefaultError() {
server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.htmlUnreachableFromRubicon()));
Expand Down

0 comments on commit 057d3bf

Please sign in to comment.