This commit is contained in:
Unity Ads Travis 2018-07-12 13:50:33 +00:00
Родитель 9855a65bf2
Коммит 718bd2ce89
19 изменённых файлов: 747 добавлений и 684 удалений

Просмотреть файл

@ -8,8 +8,8 @@ android {
applicationId "com.unity3d.ads.example"
minSdkVersion 9
targetSdkVersion 23
versionCode = 2201
versionName = "2.2.1"
versionCode = 2300
versionName = "2.3.0"
}
buildTypes {
release {

Просмотреть файл

@ -5,12 +5,12 @@
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="UnityAds 2.2"
android:label="UnityAds 2.3"
android:theme="@style/AppTheme" >
<activity
android:name="com.unity3d.ads.example.UnityAdsExample"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
android:label="UnityAds 2.2" >
android:label="UnityAds 2.3" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

Просмотреть файл

@ -11,8 +11,8 @@ android {
defaultConfig {
minSdkVersion 9
targetSdkVersion 23
versionCode = 2201
versionName = "2.2.1"
versionCode = 2300
versionName = "2.3.0"
setProperty("archivesBaseName", "unity-ads")

Просмотреть файл

@ -30,7 +30,6 @@ import org.junit.runners.Suite;
StorageGeneralTest.class,
StorageMemoryTest.class,
VideoViewTest.class,
WebRequestTest.class,
WebViewAppTest.class,
WebViewBridgeInterfaceTest.class,
WebViewBridgeTest.class,
@ -39,7 +38,8 @@ import org.junit.runners.Suite;
VolumeChangeTest.class,
UtilitiesTest.class,
WebPlayerTest.class,
PreferencesTest.class
PreferencesTest.class,
WebRequestThreadPoolTest.class
})
public class UnitTestSuite {}

Просмотреть файл

@ -227,9 +227,6 @@ public class DeviceTest {
assertNotNull("Stats should not be null", data.get("stat"));
assertNotEquals("Stats should not be empty", data.get("stat"), "");
assertNotNull("Uptime should not be null", data.get("uptime"));
assertNotEquals("Uptime should not be empty", data.get("uptime"), "");
}
@Test

Просмотреть файл

@ -7,7 +7,6 @@ import android.support.test.runner.AndroidJUnit4;
import com.unity3d.ads.api.Request;
import com.unity3d.ads.properties.ClientProperties;
import com.unity3d.ads.request.WebRequest;
import com.unity3d.ads.request.WebRequestError;
import com.unity3d.ads.request.WebRequestEvent;
import com.unity3d.ads.test.TestUtilities;

Просмотреть файл

@ -1,17 +1,55 @@
package com.unity3d.ads.test.unit;
import android.support.test.InstrumentationRegistry;
import android.util.Log;
import com.unity3d.ads.misc.Utilities;
import com.unity3d.ads.properties.ClientProperties;
import com.unity3d.ads.properties.SdkProperties;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class UtilitiesTest {
@Before
public void setup() throws IOException {
ClientProperties.setApplicationContext(InstrumentationRegistry.getTargetContext());
assertNotEquals("Cache directory has not been properly initialized", null, SdkProperties.getCacheDirectory());
File tesfile_large = new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_large.dat");
tesfile_large.delete();
File tesfile_small = new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_small.dat");
tesfile_small.delete();
// Write large test file to cache directory
File largef = new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_large.dat");
FileOutputStream lfos = new FileOutputStream(largef, true);
for (int i = 0; i < 56789; i++) {
lfos.write((int)(Math.random() * 128) + 1);
}
lfos.flush();
lfos.close();
File smallf = new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_small.dat");
FileOutputStream sfos = new FileOutputStream(smallf, true);
for (int i = 0; i < 1024; i++) {
sfos.write((int)(Math.random() * 128) + 1);
}
sfos.flush();
sfos.close();
}
@Test
public void testSha256() throws Exception {
assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Utilities.Sha256(""));
@ -74,6 +112,15 @@ public class UtilitiesTest {
assertHash(0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
}
@Test
public void testReadFileBytes() throws Exception {
byte[] large_data = Utilities.readFileBytes(new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_large.dat"));
byte[] small_data = Utilities.readFileBytes(new File(SdkProperties.getCacheDirectory() + "/" + SdkProperties.getCacheFilePrefix() + "testfile_small.dat"));
assertEquals("Incorrect read large file data size", 56789, large_data.length);
assertEquals("Incorrect read small file data size", 1024, small_data.length);
}
public void assertHash(int size, String sha256) throws Exception {
byte[] buffer = new byte[size];

Просмотреть файл

@ -222,7 +222,7 @@ public class VideoViewTest extends AdUnitActivityTestBaseClass {
assertTrue("Condition Variable was not opened: VIDEOPLAYER GENERIC ERROR or PREPARE ERROR was not received", success);
assertEquals("Event category should be videoplayer category", WebViewEventCategory.VIDEOPLAYER, mockWebViewApp.EVENT_CATEGORIES.get(0));
assertEquals("Event ID should be generic error", VideoPlayerEvent.GENERIC_ERROR, mockWebViewApp.EVENTS.get(0));
assertTrue("Events should contain GENERIC_ERROR", mockWebViewApp.EVENTS.contains(VideoPlayerEvent.GENERIC_ERROR));
assertEquals("The video url and the url received from the completed event should be the same", invalidUrl, mockWebViewApp.EVENT_PARAMS[0]);
assertTrue("Didn't get activity finish", waitForActivityFinish(activity));
}

Просмотреть файл

@ -38,6 +38,9 @@ public class VolumeChangeTest extends AdUnitActivityTestBaseClass {
ClientProperties.setApplicationContext(getInstrumentation().getTargetContext());
AudioManager am = (AudioManager)ClientProperties.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
WebViewApp.setCurrentApp(new MockWebViewApp() {
private boolean allowEvents = true;
@Override
@ -114,7 +117,6 @@ public class VolumeChangeTest extends AdUnitActivityTestBaseClass {
VolumeChange.registerListener(vcl);
AudioManager am = (AudioManager)ClientProperties.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
cv = new ConditionVariable();

Просмотреть файл

@ -1,408 +0,0 @@
package com.unity3d.ads.test.unit;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.support.test.runner.AndroidJUnit4;
import com.unity3d.ads.request.IResolveHostListener;
import com.unity3d.ads.request.IWebRequestListener;
import com.unity3d.ads.request.ResolveHostError;
import com.unity3d.ads.request.WebRequest;
import com.unity3d.ads.request.WebRequestResultReceiver;
import com.unity3d.ads.request.WebRequestThread;
import com.unity3d.ads.test.TestUtilities;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
@RunWith(AndroidJUnit4.class)
public class WebRequestTest {
private static boolean SUCCESS = false;
private static String RESPONSE = null;
private static String ERROR = null;
private static int RESPONSE_CODE = -1;
private static String ADDRESS = null;
private static String HOST = null;
private static String validUrl = TestUtilities.getTestServerAddress();
private static String invalidUrl = "http://localhost-invalid:8000";
private static int connectTimeout = 30000;
private static int readTimeout = 30000;
@Before
public void prepareTests () {
SUCCESS = false;
RESPONSE = null;
RESPONSE_CODE = -1;
ERROR = null;
ADDRESS = null;
HOST = null;
}
@Test
public void testGetRequest () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE);
assertNull("Error should be null", ERROR);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE);
}
@Test
public void testPostRequest () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE);
}
@Test
public void testEmptyGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request("", WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testEmptyPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request("", WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testNullGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(null, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testNullPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(null, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testInvalidGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(invalidUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertNotNull("There should be a error message", ERROR);
assertFalse("Error message should contain something", ERROR.isEmpty());
}
@Test
public void testInvalidPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(invalidUrl, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertNotNull("There should be a error message", ERROR);
assertFalse("Error message should contain something", ERROR.isEmpty());
}
@Test
public void testGetRequestInvalidRequestMessage () throws Exception {
final ConditionVariable cv = new ConditionVariable();
IWebRequestListener listener = new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
};
Handler handler = new Handler(Looper.getMainLooper());
WebRequestThread.request(2, validUrl, WebRequest.RequestType.GET, null, null, connectTimeout, readTimeout, listener, new WebRequestResultReceiver(handler, listener));
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should not have succeeded but did. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertTrue("Error message was different than expected", ERROR.startsWith("Invalid Thread Message"));
}
@Test
public void testGetRequestInvalidResultMessage () throws Exception {
final ConditionVariable cv = new ConditionVariable();
IWebRequestListener listener = new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
};
Handler handler = new Handler(Looper.getMainLooper());
WebRequestThread.request(2, validUrl, WebRequest.RequestType.GET, null, null, connectTimeout, readTimeout, listener, new MockWebRequestResultReceiver(handler, listener));
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should not have succeeded but did. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertTrue("Error message was different than expected", ERROR.startsWith("Invalid resultCode"));
}
@Test
public void testCancelRequests () throws Exception {
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
}
});
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
WebRequestThread.cancel();
}
}, 10);
final ConditionVariable cv = new ConditionVariable();
boolean success = cv.block(500);
assertEquals("Shouldn't have received a responseCode", -1, RESPONSE_CODE);
assertNull("Shouldn't have received a repsonse", RESPONSE);
assertFalse("Shouldn't have received success", SUCCESS);
assertNull("Shouldn't have received and error", ERROR);
}
@Test
public void testResolveHost () throws Exception {
final ConditionVariable cv = new ConditionVariable();
boolean resolveSuccess = WebRequestThread.resolve("google-public-dns-a.google.com", new IResolveHostListener() {
@Override
public void onResolve(String host, String address) {
HOST = host;
ADDRESS = address;
cv.open();
}
@Override
public void onFailed(String host, ResolveHostError error, String errorMessage) {
cv.open();
}
});
boolean cvSuccess = cv.block(30000);
assertTrue("Resolve should have succeeded", resolveSuccess);
assertTrue("Condition variable was not opened (Resolving host took too long)", cvSuccess);
assertEquals("Host should still be: google-public-dns-a.google.com", "google-public-dns-a.google.com", HOST);
assertEquals("Host Address not what was expected", "8.8.8.8", ADDRESS);
}
public class MockWebRequestResultReceiver extends WebRequestResultReceiver {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
resultCode = 12345;
super.onReceiveResult(resultCode, resultData);
}
public MockWebRequestResultReceiver(Handler handler, IWebRequestListener listener) {
super(handler, listener);
}
}
}

Просмотреть файл

@ -0,0 +1,429 @@
package com.unity3d.ads.test.unit;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.support.test.runner.AndroidJUnit4;
import com.unity3d.ads.request.IWebRequestListener;
import com.unity3d.ads.request.WebRequest;
import com.unity3d.ads.request.WebRequestThread;
import com.unity3d.ads.test.TestUtilities;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
@RunWith(AndroidJUnit4.class)
public class WebRequestThreadPoolTest {
private static boolean SUCCESS = false;
private static String RESPONSE = null;
private static String ERROR = null;
private static int RESPONSE_CODE = -1;
private static boolean SUCCESS_2 = false;
private static String RESPONSE_2 = null;
private static String ERROR_2 = null;
private static int RESPONSE_CODE_2 = -1;
private static int RESPONSE_COUNT = 0;
private static String validUrl = TestUtilities.getTestServerAddress();
private static String invalidUrl = "http://localhost-invalid:8000";
private static int connectTimeout = 30000;
private static int readTimeout = 30000;
@Before
public void prepareTests () {
SUCCESS = false;
RESPONSE = null;
RESPONSE_CODE = -1;
ERROR = null;
SUCCESS_2 = false;
RESPONSE_2 = null;
RESPONSE_CODE_2 = -1;
ERROR_2 = null;
RESPONSE_COUNT = 0;
WebRequestThread.setConcurrentRequestCount(2);
}
@After
public void afterTest () {
WebRequestThread.reset();
}
@Test
public void testGetRequest () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertNull("Error should be null", ERROR);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE);
}
@Test
public void testGetRequestMultipleRequests () throws Exception {
final ConditionVariable cv1 = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
cv1.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
cv1.open();
}
});
final ConditionVariable cv2 = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS_2 = true;
RESPONSE_CODE_2 = responseCode;
RESPONSE_2 = response;
cv2.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS_2 = false;
ERROR_2 = error;
cv2.open();
}
});
final ConditionVariable cv3 = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
cv3.open();
}
@Override
public void onFailed(String url, String error) {
cv3.open();
}
});
boolean success1 = cv1.block(30000);
boolean success2 = cv2.block(1);
boolean success3 = cv3.block(30000);
assertTrue("ConditionVariable for first request was not opened", success1);
assertTrue("ConditionVariable for second request was not opened", success2);
assertTrue("ConditionVariable for third request was not opened", success3);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE);
assertNull("Error should be null", ERROR);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS_2);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE_2);
assertNull("Error should be null", ERROR_2);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE_2);
}
@Test
public void testPostRequest () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(validUrl, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have succeeded but didn't. SUCCESS=false", true, SUCCESS);
assertEquals("Status code of the request was assumed to be 200, but it wasn't", 200, RESPONSE_CODE);
assertEquals("Response was expected to be 'OK'", "OK", RESPONSE);
}
@Test
public void testEmptyGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request("", WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testEmptyPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request("", WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testNullGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(null, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testNullPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(null, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertEquals("Error message was different than expected", "Request is NULL or too short", ERROR);
}
@Test
public void testInvalidGetUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(invalidUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertNotNull("There should be a error message", ERROR);
assertFalse("Error message should contain something", ERROR.isEmpty());
}
@Test
public void testInvalidPostUrl () throws Exception {
final ConditionVariable cv = new ConditionVariable();
WebRequestThread.request(invalidUrl, WebRequest.RequestType.POST, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
cv.open();
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
cv.open();
}
});
boolean success = cv.block(30000);
assertTrue("ConditionVariable was not opened", success);
assertEquals("The request should have failed but didn't. SUCCESS=true", false, SUCCESS);
assertEquals("Status code of the request was assumed to be -1, but it wasn't", -1, RESPONSE_CODE);
assertNotNull("There should be a error message", ERROR);
assertFalse("Error message should contain something", ERROR.isEmpty());
}
@Test
public void testCancelRequests () throws Exception {
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
RESPONSE_COUNT++;
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
}
});
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
RESPONSE_COUNT++;
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
}
});
WebRequestThread.request(validUrl, WebRequest.RequestType.GET, null, connectTimeout, readTimeout, new IWebRequestListener() {
@Override
public void onComplete(String url, String response, int responseCode, Map<String, List<String>> headers) {
SUCCESS = true;
RESPONSE_CODE = responseCode;
RESPONSE = response;
RESPONSE_COUNT++;
}
@Override
public void onFailed(String url, String error) {
SUCCESS = false;
ERROR = error;
}
});
WebRequestThread.cancel();
final ConditionVariable cv = new ConditionVariable();
boolean success = cv.block(500);
assertEquals("response count should be zero", 0, RESPONSE_COUNT);
assertEquals("Shouldn't have received a responseCode", -1, RESPONSE_CODE);
assertNull("Shouldn't have received a response", RESPONSE);
assertFalse("Shouldn't have received success", SUCCESS);
assertNull("Shouldn't have received and error", ERROR);
}
}

Просмотреть файл

@ -290,7 +290,11 @@ public final class UnityAds {
* @param activity Current Android activity of calling app
*/
public static void show(final Activity activity) {
if(Placement.getDefaultPlacement() != null) {
show(activity, Placement.getDefaultPlacement());
} else {
handleShowError("", UnityAdsError.NOT_INITIALIZED, "Unity Ads default placement is not initialized");
}
}
/**
@ -346,10 +350,7 @@ public final class UnityAds {
}
}).start();
} else {
if (placementId == null) {
throw new IllegalArgumentException("PlacementID is null");
}
else if (!isSupported()) {
if (!isSupported()) {
handleShowError(placementId, UnityAdsError.NOT_INITIALIZED, "Unity Ads is not supported for this device");
} else if(!isInitialized()) {
handleShowError(placementId, UnityAdsError.NOT_INITIALIZED, "Unity Ads is not initialized");
@ -369,7 +370,12 @@ public final class UnityAds {
@Override
public void run() {
listener.onUnityAdsError(error, errorMessage);
if(placementId != null) {
listener.onUnityAdsFinish(placementId, FinishState.ERROR);
} else {
listener.onUnityAdsFinish("", FinishState.ERROR);
}
}
});
}

Просмотреть файл

@ -1,10 +1,7 @@
package com.unity3d.ads.api;
import com.unity3d.ads.log.DeviceLog;
import com.unity3d.ads.request.IResolveHostListener;
import com.unity3d.ads.request.IWebRequestListener;
import com.unity3d.ads.request.ResolveHostError;
import com.unity3d.ads.request.ResolveHostEvent;
import com.unity3d.ads.request.WebRequest;
import com.unity3d.ads.request.WebRequestError;
import com.unity3d.ads.request.WebRequestEvent;
@ -146,6 +143,24 @@ public class Request {
callback.invoke(id);
}
@WebViewExposed
public static void setConcurrentRequestCount(Integer count, final WebViewCallback callback) {
WebRequestThread.setConcurrentRequestCount(count);
callback.invoke();
}
@WebViewExposed
public static void setMaximumPoolSize(Integer count, final WebViewCallback callback) {
WebRequestThread.setMaximumPoolSize(count);
callback.invoke();
}
@WebViewExposed
public static void setKeepAliveTime(Integer milliseconds, final WebViewCallback callback) {
WebRequestThread.setKeepAliveTime(milliseconds.longValue());
callback.invoke();
}
public static JSONArray getResponseHeadersMap (Map<String, List<String>> responseHeaders) {
JSONArray retObj = new JSONArray();

Просмотреть файл

@ -656,20 +656,6 @@ public class Device {
}
}
try {
reader = new RandomAccessFile("/proc/uptime", "r");
String uptimeContent = reader.readLine();
retData.put("uptime", uptimeContent);
} catch (IOException e) {
DeviceLog.exception("Error while reading processor info: ", e);
} finally {
try {
reader.close();
} catch (IOException e) {
DeviceLog.exception("Error closing RandomAccessFile", e);
}
}
return retData;
}
}

Просмотреть файл

@ -0,0 +1,37 @@
package com.unity3d.ads.request;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CancelableThreadPoolExecutor extends ThreadPoolExecutor {
private final List<Runnable> _activeRunnable;
public CancelableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, LinkedBlockingQueue<Runnable> queue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit,queue);
_activeRunnable = new LinkedList<>();
}
@Override
protected synchronized void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
_activeRunnable.add(r);
}
@Override
protected synchronized void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
_activeRunnable.remove(r);
}
public synchronized void cancel() {
for(Runnable r : _activeRunnable) {
if (r instanceof WebRequestRunnable) {
((WebRequestRunnable)r).setCancelStatus(true);
}
}
}
}

Просмотреть файл

@ -1,126 +0,0 @@
package com.unity3d.ads.request;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.unity3d.ads.log.DeviceLog;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class WebRequestHandler extends Handler {
private WebRequest _currentRequest;
private boolean _canceled = false;
@Override
public void handleMessage (Message msg) {
Bundle data = msg.getData();
String url = data.getString("url");
data.remove("url");
String type = data.getString("type");
data.remove("type");
String body = data.getString("body");
data.remove("body");
WebRequestResultReceiver receiver = data.getParcelable("receiver");
data.remove("receiver");
int connectTimeout = data.getInt("connectTimeout");
data.remove("connectTimeout");
int readTimeout = data.getInt("readTimeout");
data.remove("readTimeout");
HashMap<String, List<String>> headers = null;
if (data.size() > 0) {
DeviceLog.debug("There are headers left in data, reading them");
headers = new HashMap<>();
List<String> values;
for (String k : data.keySet()) {
values = Arrays.asList(data.getStringArray(k));
headers.put(k, values);
}
}
if (msg.what == WebRequestThread.MSG_REQUEST) {
DeviceLog.debug("Handling request message: " + url + " type=" + type);
try {
makeRequest(url, type, headers, body, connectTimeout, readTimeout, receiver);
}
catch (MalformedURLException e) {
DeviceLog.exception("Malformed URL", e);
if (receiver != null) {
receiver.send(WebRequestResultReceiver.RESULT_FAILED, getBundleForFailResult(url, "Malformed URL", type, body));
}
}
} else {
DeviceLog.error("No implementation for message: " + msg.what);
if (receiver != null) {
receiver.send(WebRequestResultReceiver.RESULT_FAILED, getBundleForFailResult(url, "Invalid Thread Message", type, body));
}
}
}
public void setCancelStatus (boolean canceled) {
_canceled = canceled;
if (_canceled && _currentRequest != null) {
_currentRequest.cancel();
}
}
private void makeRequest (String url, String type, HashMap<String, List<String>> headers, String body, int connectTimeout, int readTimeout, WebRequestResultReceiver receiver) throws MalformedURLException {
if (_canceled) {
return;
}
_currentRequest = new WebRequest(url, type, headers, connectTimeout, readTimeout);
if (body != null) {
_currentRequest.setBody(body);
}
String response;
try {
response = _currentRequest.makeRequest();
} catch (IOException | NetworkIOException | IllegalStateException e) {
DeviceLog.exception("Error completing request", e);
receiver.send(WebRequestResultReceiver.RESULT_FAILED, getBundleForFailResult(url, e.getClass().getName() + ": " + e.getMessage(), type, body));
return;
}
if (!_currentRequest.isCanceled()) {
Bundle data = new Bundle();
data.putString("response", response);
data.putString("url", url);
data.putInt("responseCode", _currentRequest.getResponseCode());
for (String key : _currentRequest.getResponseHeaders().keySet()) {
if (key == null || key.contentEquals("null")) {
continue;
}
String[] values = new String[_currentRequest.getResponseHeaders().get(key).size()];
for (int valueidx = 0; valueidx < _currentRequest.getResponseHeaders().get(key).size(); valueidx++) {
values[valueidx] = _currentRequest.getResponseHeaders().get(key).get(valueidx);
}
data.putStringArray(key, values);
}
receiver.send(WebRequestResultReceiver.RESULT_SUCCESS, data);
}
}
private Bundle getBundleForFailResult (String url, String error, String type, String body) {
Bundle data = new Bundle();
data.putString("url", url);
data.putString("error", error);
data.putString("type", type);
data.putString("body", body);
return data;
}
}

Просмотреть файл

@ -1,67 +0,0 @@
package com.unity3d.ads.request;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import com.unity3d.ads.log.DeviceLog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WebRequestResultReceiver extends ResultReceiver {
public static final int RESULT_SUCCESS = 1;
public static final int RESULT_FAILED = 2;
private IWebRequestListener _listener;
public WebRequestResultReceiver (Handler handler, IWebRequestListener listener) {
super(handler);
_listener = listener;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
DeviceLog.entered();
if (_listener != null) {
switch (resultCode) {
case RESULT_SUCCESS:
String url = resultData.getString("url");
resultData.remove("url");
String response = resultData.getString("response");
resultData.remove("response");
int responseCode = resultData.getInt("responseCode");
resultData.remove("responseCode");
_listener.onComplete(url, response, responseCode, getResponseHeaders(resultData));
break;
case RESULT_FAILED:
_listener.onFailed(resultData.getString("url"), resultData.getString("error"));
break;
default:
DeviceLog.error("Unhandled resultCode: " + resultCode);
_listener.onFailed(resultData.getString("url"), "Invalid resultCode=" + resultCode);
break;
}
}
super.onReceiveResult(resultCode, resultData);
}
private Map<String, List<String>> getResponseHeaders(Bundle resultData) {
Map<String, List<String>> responseHeaders = null;
if (resultData.size() > 0) {
responseHeaders = new HashMap<>();
for (String k : resultData.keySet()) {
String[] tmpAr = resultData.getStringArray(k);
if (tmpAr != null) {
responseHeaders.put(k, new ArrayList<>(Arrays.asList(tmpAr)));
}
}
}
return responseHeaders;
}
}

Просмотреть файл

@ -0,0 +1,118 @@
package com.unity3d.ads.request;
import android.os.Bundle;
import com.unity3d.ads.log.DeviceLog;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WebRequestRunnable implements Runnable {
private WebRequest _currentRequest;
private boolean _canceled = false;
private final String _url;
private final String _type;
private final String _body;
private final int _connectTimeout;
private final int _readTimeout;
private final Map<String, List<String>> _headers;
private final IWebRequestListener _listener;
public WebRequestRunnable(String url, String type, String body, int connectTimeout, int readTimeout, Map<String, List<String>> headers, IWebRequestListener listener) {
_url = url;
_type = type;
_body = body;
_connectTimeout = connectTimeout;
_readTimeout = readTimeout;
_headers = headers;
_listener = listener;
}
@Override public void run() {
DeviceLog.debug("Handling request message: " + _url + " type=" + _type);
try {
makeRequest(_url, _type, _headers, _body, _connectTimeout, _readTimeout);
}
catch (MalformedURLException e) {
DeviceLog.exception("Malformed URL", e);
onFailed("Malformed URL");
}
}
public void setCancelStatus (boolean canceled) {
_canceled = canceled;
if (_canceled && _currentRequest != null) {
_currentRequest.cancel();
}
}
private void makeRequest (String url, String type, Map<String, List<String>> headers, String body, int connectTimeout, int readTimeout) throws MalformedURLException {
if (_canceled) {
return;
}
_currentRequest = new WebRequest(url, type, headers, connectTimeout, readTimeout);
if (body != null) {
_currentRequest.setBody(body);
}
String response;
try {
response = _currentRequest.makeRequest();
} catch (IOException | NetworkIOException | IllegalStateException e) {
DeviceLog.exception("Error completing request", e);
onFailed(e.getClass().getName() + ": " + e.getMessage());
return;
}
if (!_currentRequest.isCanceled()) {
Bundle data = new Bundle();
for (String key : _currentRequest.getResponseHeaders().keySet()) {
if (key == null || key.contentEquals("null")) {
continue;
}
String[] values = new String[_currentRequest.getResponseHeaders().get(key).size()];
for (int valueidx = 0; valueidx < _currentRequest.getResponseHeaders().get(key).size(); valueidx++) {
values[valueidx] = _currentRequest.getResponseHeaders().get(key).get(valueidx);
}
data.putStringArray(key, values);
}
onSucceed(response, _currentRequest.getResponseCode(), getResponseHeaders(data));
} else {
onFailed("Canceled");
}
}
private void onSucceed(String response, int responseCode, Map<String, List<String>> headers) {
_listener.onComplete(_url, response, responseCode, headers);
}
private void onFailed(String error) {
_listener.onFailed(_url, error);
}
private Map<String, List<String>> getResponseHeaders(Bundle resultData) {
Map<String, List<String>> responseHeaders = null;
if (resultData.size() > 0) {
responseHeaders = new HashMap<>();
for (String k : resultData.keySet()) {
String[] tmpAr = resultData.getStringArray(k);
if (tmpAr != null) {
responseHeaders.put(k, new ArrayList<>(Arrays.asList(tmpAr)));
}
}
}
return responseHeaders;
}
}

Просмотреть файл

@ -9,20 +9,41 @@ import com.unity3d.ads.log.DeviceLog;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class WebRequestThread extends Thread {
public class WebRequestThread {
protected static final int MSG_REQUEST = 1;
private static WebRequestHandler _handler;
private static boolean _ready = false;
private static LinkedBlockingQueue<Runnable> _queue;
private static CancelableThreadPoolExecutor _pool;
private static int _corePoolSize = 1;
private static int _maximumPoolSize = 1;
private static long _keepAliveTime = 1000;
private static final Object _readyLock = new Object();
private static void init() {
WebRequestThread thread = new WebRequestThread();
thread.setName("UnityAdsWebRequestThread");
thread.start();
private static synchronized void init() {
_queue = new LinkedBlockingQueue<>();
_pool = new CancelableThreadPoolExecutor(_corePoolSize, _maximumPoolSize, _keepAliveTime, TimeUnit.MILLISECONDS, _queue);
_pool.prestartAllCoreThreads();
_queue.add(new Runnable() {
@Override
public void run() {
_ready = true;
synchronized(_readyLock) {
_readyLock.notify();
}
}
});
while(!_ready) {
try {
@ -31,31 +52,36 @@ public class WebRequestThread extends Thread {
}
} catch (InterruptedException e) {
DeviceLog.debug("Couldn't synchronize thread");
return;
}
}
}
@Override
public void run() {
Looper.prepare();
public static synchronized void reset() {
cancel();
if (_handler == null) {
_handler = new WebRequestHandler();
if (_pool != null) {
_pool.shutdown();
try {
_pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
}
_queue.clear();
_pool = null;
_queue = null;
_ready = false;
}
}
_ready = true;
synchronized(_readyLock) {
_readyLock.notify();
public static synchronized void cancel () {
if (_pool != null) {
_pool.cancel();
for(Runnable runnable: _queue) {
if (runnable instanceof WebRequestRunnable)
((WebRequestRunnable)runnable).setCancelStatus(true);
}
Looper.loop();
}
public static void cancel () {
if (_handler != null) {
_handler.removeMessages(MSG_REQUEST);
_handler.setCancelStatus(true);
_queue.clear();
_pool.purge();
}
}
@ -64,10 +90,6 @@ public class WebRequestThread extends Thread {
}
public static synchronized void request (String url, WebRequest.RequestType requestType, Map<String, List<String>> headers, String requestBody, Integer connectTimeout, Integer readTimeout, IWebRequestListener listener) {
request(MSG_REQUEST, url, requestType, headers, requestBody, connectTimeout, readTimeout, listener, new WebRequestResultReceiver(_handler, listener));
}
public static synchronized void request (int msgWhat, String url, WebRequest.RequestType requestType, Map<String, List<String>> headers, String requestBody, Integer connectTimeout, Integer readTimeout, IWebRequestListener listener, WebRequestResultReceiver receiver) {
if(!_ready) {
init();
}
@ -77,27 +99,33 @@ public class WebRequestThread extends Thread {
return;
}
Bundle params = new Bundle();
params.putString("url", url);
params.putString("type", requestType.name());
params.putString("body", requestBody);
params.putParcelable("receiver", receiver);
params.putInt("connectTimeout", connectTimeout);
params.putInt("readTimeout", readTimeout);
_queue.add(new WebRequestRunnable(url, requestType.name(), requestBody, connectTimeout, readTimeout, headers, listener));
}
if (headers != null) {
for (String s : headers.keySet()) {
String[] h = new String[headers.get(s).size()];
params.putStringArray(s, headers.get(s).toArray(h));
public static synchronized void setConcurrentRequestCount(int count) {
_corePoolSize = count;
_maximumPoolSize = _corePoolSize;
if (_pool != null) {
_pool.setCorePoolSize(_corePoolSize);
_pool.setMaximumPoolSize(_maximumPoolSize);
}
}
Message msg = new Message();
msg.what = msgWhat;
msg.setData(params);
public static synchronized void setMaximumPoolSize(int count) {
_maximumPoolSize = count;
_handler.setCancelStatus(false);
_handler.sendMessage(msg);
if (_pool != null) {
_pool.setMaximumPoolSize(_maximumPoolSize);
}
}
public static synchronized void setKeepAliveTime(long milliseconds) {
_keepAliveTime = milliseconds;
if (_pool != null) {
_pool.setKeepAliveTime(_keepAliveTime, TimeUnit.MILLISECONDS);
}
}
public static synchronized boolean resolve (final String host, final IResolveHostListener listener) {