Skip to content

Commit

Permalink
Merge d11bf9c into 6bc83df
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon6193 committed Jun 28, 2019
2 parents 6bc83df + d11bf9c commit afeb526
Show file tree
Hide file tree
Showing 9 changed files with 386 additions and 8 deletions.
4 changes: 3 additions & 1 deletion button-merchant/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ task jacocoReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
'**/Manifest*.*',
'**/*Test*.*',
'android/**/*.*',
'com/usebutton/merchant/exception/**']
'com/usebutton/merchant/exception/**',
'com/usebutton/merchant/ThreadManager.*'
]

def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter)
def mainSrc = "${project.projectDir}/src/main/java"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,6 @@ public void updateCheckDeferredDeepLink(boolean checkedDeferredDeepLink) {
public void postOrder(Order order, DeviceManager deviceManager, Task.Listener listener) {
executorService.submit(
new PostOrderTask(listener, buttonApi, order, getApplicationId(),
getSourceToken(), deviceManager));
getSourceToken(), deviceManager, new ThreadManager()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import android.util.Log;

import com.usebutton.merchant.exception.ButtonNetworkException;
import com.usebutton.merchant.exception.HttpStatusException;
import com.usebutton.merchant.exception.NetworkNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;
Expand Down Expand Up @@ -107,13 +109,16 @@ public NetworkResponse executeRequest(@NonNull ApiRequest request)
if (responseCode >= 400) {
String message = "Unsuccessful Request. HTTP StatusCode: " + responseCode;
Log.e(TAG, message);
throw new ButtonNetworkException(message);
throw new HttpStatusException(message, responseCode);
}

JSONObject responseJson = readResponseBody(urlConnection);
return new NetworkResponse(responseCode, responseJson);
} catch (IOException | JSONException e) {
Log.e(TAG, e.getClass().getSimpleName() + " has occurred", e);
} catch (IOException e) {
Log.e(TAG, "Error has occurred", e);
throw new NetworkNotFoundException(e);
} catch (JSONException e) {
Log.e(TAG, "Error has occurred", e);
throw new ButtonNetworkException(e.getClass().getSimpleName() + " has occurred");
} finally {
if (urlConnection != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@
package com.usebutton.merchant;

import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;

import com.usebutton.merchant.exception.ButtonNetworkException;
import com.usebutton.merchant.exception.HttpStatusException;
import com.usebutton.merchant.exception.NetworkNotFoundException;

/**
* Asynchronous task used to report order to the Button API.
Expand All @@ -37,22 +42,72 @@ class PostOrderTask extends Task {
private final String sourceToken;
private final Order order;
private final DeviceManager deviceManager;
private final ThreadManager threadManager;

@VisibleForTesting
static final int MAX_RETRIES = 4;

private int retryCount = 0;

PostOrderTask(@Nullable Listener listener, ButtonApi buttonApi, Order order,
String applicationId, String sourceToken, DeviceManager deviceManager) {
String applicationId, String sourceToken, DeviceManager deviceManager,
ThreadManager threadManager) {
super(listener);
this.buttonApi = buttonApi;
this.order = order;
this.applicationId = applicationId;
this.sourceToken = sourceToken;
this.deviceManager = deviceManager;
this.threadManager = threadManager;
}

@Nullable
@Override
Void execute() throws Exception {
String advertisingId = deviceManager.isLimitAdTrackingEnabled()
? null : deviceManager.getAdvertisingId();
return buttonApi.postOrder(order, applicationId, sourceToken, advertisingId);

// loop and execute postOrder until max retries is met or non case exception is met
while (true) {
try {
return buttonApi.postOrder(order, applicationId, sourceToken, advertisingId);
} catch (ButtonNetworkException exception) {
if (!shouldRetry(exception)) {
throw exception;
}

retryCount++;
}
}
}

/**
* @param exception exception thrown by api request
* @return true if should retry
*/
private boolean shouldRetry(ButtonNetworkException exception) throws InterruptedException {
if (retryCount >= MAX_RETRIES) {
return false;
}

double delay = getRetryDelay();
if (exception instanceof NetworkNotFoundException) {
threadManager.sleep((long) delay);
return true;
}

if (exception instanceof HttpStatusException) {
HttpStatusException httpStatusException = (HttpStatusException) exception;
if (httpStatusException.wasRateLimited() || httpStatusException.wasServerError()) {
threadManager.sleep((long) delay);
return true;
}
}

return false;
}

private double getRetryDelay() {
return Math.pow(2, retryCount) * 100;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* ThreadManager.java
*
* Copyright (c) 2019 Button, Inc. (https://usebutton.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package com.usebutton.merchant;

/**
* Wrapper class for {@link java.lang.Thread}
*/
class ThreadManager {

void sleep(long millis) throws InterruptedException {
Thread.sleep(millis);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* HttpStatusException.java
*
* Copyright (c) 2019 Button, Inc. (https://usebutton.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package com.usebutton.merchant.exception;

/**
* Network error with status code encountered when communicating with the Button API
*/
public class HttpStatusException extends ButtonNetworkException {
private final int statusCode;

public HttpStatusException(String message, int statusCode) {
super(message);
this.statusCode = statusCode;
}

/**
* @return true if status code falls in the range indicating bad requests. (400-499)
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
public boolean wasBadRequest() {
return statusCode >= 400 && statusCode < 500;
}

/**
* @return if the exception was due to the server responding with a 401 (Unauthorized).
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
public boolean wasUnauthorized() {
return statusCode == 401;
}

/**
* @return if the exception was due to the server responding with a 429 (Rate Limited).
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
public boolean wasRateLimited() {
return statusCode == 429;
}

/**
* @return true if status code falls in the range indicating server errors. (500-599)
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
public boolean wasServerError() {
return statusCode >= 500 && statusCode < 600;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* NetworkNotFoundException.java
*
* Copyright (c) 2019 Button, Inc. (https://usebutton.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package com.usebutton.merchant.exception;

/**
* Network error encountered when communicating with the Button API
*
* ie. Device is not connected to the internet
*/
public class NetworkNotFoundException extends ButtonNetworkException {

public NetworkNotFoundException(Exception e) {
super(e);
}
}

0 comments on commit afeb526

Please sign in to comment.