From 4e7ca46e9a404c85135a8f3a80ade4a3e8c4db2b Mon Sep 17 00:00:00 2001 From: Michael Shafrir Date: Sat, 8 Jun 2019 21:24:46 -0400 Subject: [PATCH] Remove toJson() from StripeJsonModel `toJson()` was previously used in the implementation of `equals()` (see #813). Now that it is no longer used in `equals()`, it is no longer needed. Remove all implementations of toJson() and rename StripeJsonModel to StripeModel. Also improve object construction in `AbstractEphemeralKey` by creating a Builder object instead of using reflection. --- .../activity/PaymentIntentActivity.java | 5 +- .../stripe/android/AbstractEphemeralKey.java | 218 ++++++++---------- .../stripe/android/CustomerEphemeralKey.java | 53 ++--- .../com/stripe/android/CustomerSession.java | 2 +- .../stripe/android/EphemeralKeyManager.java | 22 +- .../android/EphemeralKeyUpdateListener.java | 1 - .../android/IssuingCardEphemeralKey.java | 53 ++--- .../stripe/android/IssuingCardPinService.java | 38 +-- .../com/stripe/android/model/Address.java | 16 +- .../java/com/stripe/android/model/Card.java | 35 +-- .../com/stripe/android/model/Customer.java | 36 +-- .../stripe/android/model/CustomerSource.java | 13 +- .../stripe/android/model/PaymentIntent.java | 32 +-- .../stripe/android/model/PaymentMethod.java | 121 +--------- .../android/model/ShippingInformation.java | 15 +- .../stripe/android/model/ShippingMethod.java | 26 +-- .../java/com/stripe/android/model/Source.java | 53 +---- .../stripe/android/model/SourceCardData.java | 21 +- .../android/model/SourceCodeVerification.java | 15 +- .../com/stripe/android/model/SourceOwner.java | 29 +-- .../stripe/android/model/SourceReceiver.java | 17 +- .../stripe/android/model/SourceRedirect.java | 13 +- .../android/model/SourceSepaDebitData.java | 15 -- .../stripe/android/model/StripeJsonModel.java | 84 ------- .../com/stripe/android/model/StripeModel.java | 45 ++++ .../android/model/StripeSourceTypeModel.java | 10 +- .../wallets/AmexExpressCheckoutWallet.java | 6 - .../android/model/wallets/ApplePayWallet.java | 6 - .../model/wallets/GooglePayWallet.java | 6 - .../model/wallets/MasterpassWallet.java | 17 -- .../model/wallets/SamsungPayWallet.java | 6 - .../model/wallets/VisaCheckoutWallet.java | 17 -- .../stripe/android/model/wallets/Wallet.java | 39 +--- .../stripe/android/CustomerSessionTest.java | 5 +- .../android/EphemeralKeyManagerTest.java | 34 +-- .../com/stripe/android/EphemeralKeyTest.java | 34 +-- .../android/IssuingCardPinServiceTest.java | 20 +- .../com/stripe/android/model/AddressTest.java | 10 - .../com/stripe/android/model/CardTest.java | 19 +- .../android/model/CustomerSourceTest.java | 68 ++---- .../stripe/android/model/CustomerTest.java | 112 ++++----- .../android/model/PaymentIntentTest.java | 17 +- .../android/model/PaymentMethodTest.java | 36 +-- .../android/model/ShippingMethodTest.java | 37 +-- .../model/SourceCodeVerificationTest.java | 28 +-- .../stripe/android/model/SourceOwnerTest.java | 22 +- .../android/model/SourceReceiverTest.java | 14 -- .../android/model/SourceRedirectTest.java | 8 - .../com/stripe/android/model/SourceTest.java | 25 +- .../android/model/StripeJsonModelTest.java | 174 -------------- .../android/model/StripeJsonUtilsTest.java | 212 ++++++----------- .../stripe/android/model/StripeModelTest.java | 125 ++++++++++ .../model/StripeSourceTypeModelTest.java | 55 ++--- .../model/wallets/WalletFactoryTest.java | 12 - .../android/testharness/JsonTestUtils.java | 72 ++---- .../testharness/JsonTestUtilsTest.java | 114 +++------ .../android/view/CardMultilineWidgetTest.java | 9 +- 57 files changed, 686 insertions(+), 1661 deletions(-) delete mode 100644 stripe/src/main/java/com/stripe/android/model/StripeJsonModel.java create mode 100644 stripe/src/main/java/com/stripe/android/model/StripeModel.java delete mode 100644 stripe/src/test/java/com/stripe/android/model/StripeJsonModelTest.java create mode 100644 stripe/src/test/java/com/stripe/android/model/StripeModelTest.java diff --git a/example/src/main/java/com/stripe/example/activity/PaymentIntentActivity.java b/example/src/main/java/com/stripe/example/activity/PaymentIntentActivity.java index fe2fb7b84f9..ffb56582328 100644 --- a/example/src/main/java/com/stripe/example/activity/PaymentIntentActivity.java +++ b/example/src/main/java/com/stripe/example/activity/PaymentIntentActivity.java @@ -158,7 +158,7 @@ private void retrievePaymentIntent() { .observeOn(AndroidSchedulers.mainThread()) .subscribe( paymentIntent -> mPaymentIntentValue.setText(paymentIntent != null ? - paymentIntent.toJson().toString() : + new JSONObject(paymentIntent.toMap()).toString() : getString(R.string.error_while_retrieving_payment_intent)), throwable -> Log.e(TAG, throwable.toString()) ); @@ -188,7 +188,8 @@ private void confirmPaymentIntent(@NonNull final Card card) { .subscribe( paymentIntent -> { if (paymentIntent != null) { - mPaymentIntentValue.setText(paymentIntent.toJson().toString()); + mPaymentIntentValue.setText( + new JSONObject(paymentIntent.toMap()).toString()); if (paymentIntent.requiresAction()) { Toast.makeText(PaymentIntentActivity.this, diff --git a/stripe/src/main/java/com/stripe/android/AbstractEphemeralKey.java b/stripe/src/main/java/com/stripe/android/AbstractEphemeralKey.java index 50623d6c9bd..44972febda6 100644 --- a/stripe/src/main/java/com/stripe/android/AbstractEphemeralKey.java +++ b/stripe/src/main/java/com/stripe/android/AbstractEphemeralKey.java @@ -5,24 +5,23 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import com.stripe.android.model.StripeJsonModel; +import com.stripe.android.model.StripeModel; import com.stripe.android.utils.ObjectUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.lang.reflect.InvocationTargetException; -import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; /** * Represents an Ephemeral Key that can be used temporarily for certain operations. */ -abstract class AbstractEphemeralKey extends StripeJsonModel implements Parcelable { +abstract class AbstractEphemeralKey extends StripeModel implements Parcelable { static final String FIELD_CREATED = "created"; static final String FIELD_EXPIRES = "expires"; @@ -32,7 +31,6 @@ abstract class AbstractEphemeralKey extends StripeJsonModel implements Parcelabl static final String FIELD_ID = "id"; static final String FIELD_ASSOCIATED_OBJECTS = "associated_objects"; static final String FIELD_TYPE = "type"; - static final String NULL = "null"; @NonNull final String mObjectId; private final long mCreated; @@ -53,83 +51,30 @@ abstract class AbstractEphemeralKey extends StripeJsonModel implements Parcelabl */ AbstractEphemeralKey(@NonNull Parcel in) { mCreated = in.readLong(); - mObjectId = in.readString(); + mObjectId = Objects.requireNonNull(in.readString()); mExpires = in.readLong(); - mId = in.readString(); + mId = Objects.requireNonNull(in.readString()); mLiveMode = in.readInt() == 1; - mObject = in.readString(); - mSecret = in.readString(); - mType = in.readString(); + mObject = Objects.requireNonNull(in.readString()); + mSecret = Objects.requireNonNull(in.readString()); + mType = Objects.requireNonNull(in.readString()); } - AbstractEphemeralKey( - long created, - @NonNull String objectId, - long expires, - @NonNull String id, - boolean liveMode, - @NonNull String object, - @NonNull String secret, - @NonNull String type - ) { - mCreated = created; - mObjectId = objectId; - mExpires = expires; - mId = id; - mLiveMode = liveMode; - mObject = object; - mSecret = secret; - mType = type; - } - - AbstractEphemeralKey(@Nullable JSONObject jsonObject) throws JSONException { - mCreated = jsonObject.getLong(FIELD_CREATED); - mExpires = jsonObject.getLong(FIELD_EXPIRES); - mId = jsonObject.getString(FIELD_ID); - mLiveMode = jsonObject.getBoolean(FIELD_LIVEMODE); - mObject = jsonObject.getString(FIELD_OBJECT); - mSecret = jsonObject.getString(FIELD_SECRET); - - // Get the values from the associated objects array first element - JSONArray associatedObjectArray = jsonObject.getJSONArray(FIELD_ASSOCIATED_OBJECTS); - JSONObject typeObject = associatedObjectArray.getJSONObject(0); - mType = typeObject.getString(FIELD_TYPE); - mObjectId = typeObject.getString(FIELD_ID); - } - - @NonNull - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - JSONArray associatedObjectsArray = new JSONArray(); - JSONObject associatedObject = new JSONObject(); - - try { - jsonObject.put(FIELD_CREATED, mCreated); - jsonObject.put(FIELD_EXPIRES, mExpires); - jsonObject.put(FIELD_OBJECT, mObject); - jsonObject.put(FIELD_ID, mId); - jsonObject.put(FIELD_SECRET, mSecret); - jsonObject.put(FIELD_LIVEMODE, mLiveMode); - - associatedObject.put(FIELD_TYPE, mType); - associatedObject.put(FIELD_ID, mObjectId); - associatedObjectsArray.put(associatedObject); - - jsonObject.put(FIELD_ASSOCIATED_OBJECTS, associatedObjectsArray); - } catch (JSONException impossible) { - // An exception can only be thrown from put operations if the key is null - // or the value is a non-finite number. - throw new IllegalArgumentException("JSONObject creation exception thrown."); - } - - return jsonObject; + AbstractEphemeralKey(@NonNull Builder builder) { + mCreated = builder.mCreated; + mObjectId = Objects.requireNonNull(builder.mObjectId); + mExpires = builder.mExpires; + mId = Objects.requireNonNull(builder.mId); + mLiveMode = builder.mLiveMode; + mObject = Objects.requireNonNull(builder.mObject); + mSecret = Objects.requireNonNull(builder.mSecret); + mType = Objects.requireNonNull(builder.mType); } @NonNull @Override public Map toMap() { - final AbstractMap map = new HashMap<>(); + final Map map = new HashMap<>(); map.put(FIELD_CREATED, mCreated); map.put(FIELD_EXPIRES, mExpires); map.put(FIELD_OBJECT, mObject); @@ -161,12 +106,11 @@ public int describeContents() { * @param flags any flags (unused) for writing this object */ @Override - public void writeToParcel(Parcel out, int flags) { + public void writeToParcel(@NonNull Parcel out, int flags) { out.writeLong(mCreated); out.writeString(mObjectId); out.writeLong(mExpires); out.writeString(mId); - // There is no writeBoolean out.writeInt(mLiveMode ? 1 : 0); out.writeString(mObject); out.writeString(mSecret); @@ -205,49 +149,24 @@ String getType() { return mType; } - @NonNull - protected static TEphemeralKey fromString( - @Nullable String rawJson, Class ephemeralKeyClass) throws JSONException { - if (rawJson == null) { - throw new IllegalArgumentException("Attempted to instantiate " + - ephemeralKeyClass.getSimpleName() + " with null raw key"); - } - JSONObject object = new JSONObject(rawJson); - return fromJson(object, ephemeralKeyClass); - } - @NonNull protected static TEphemeralKey fromJson( - @Nullable JSONObject jsonObject, Class ephemeralKeyClass) { - if (jsonObject == null) { - throw new IllegalArgumentException("Exception instantiating " + - ephemeralKeyClass.getSimpleName() + - " null JSON"); - } - - try { - return (TEphemeralKey) - ephemeralKeyClass.getConstructor(JSONObject.class).newInstance(jsonObject); - } catch (InstantiationException e) { - throw new IllegalArgumentException("Exception instantiating " + - ephemeralKeyClass.getSimpleName(), e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException("Exception instantiating " + - ephemeralKeyClass.getSimpleName(), e); - } catch (InvocationTargetException e) { - if (e.getTargetException() != null) { - throw new IllegalArgumentException("Improperly formatted JSON for ephemeral key " + - ephemeralKeyClass.getSimpleName() + - " - " + e.getTargetException().getMessage(), - e.getTargetException()); - } - throw new IllegalArgumentException("Improperly formatted JSON for ephemeral key " + - ephemeralKeyClass.getSimpleName(), e); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("Class " + - ephemeralKeyClass.getSimpleName() + - " does not have an accessible (JSONObject) constructor", e); - } + @NonNull JSONObject jsonObject, @NonNull Builder builder) + throws JSONException { + // Get the values from the associated objects array first element + final JSONArray associatedObjectArray = jsonObject.getJSONArray(FIELD_ASSOCIATED_OBJECTS); + final JSONObject typeObject = associatedObjectArray.getJSONObject(0); + + return builder + .setCreated(jsonObject.getLong(FIELD_CREATED)) + .setExpires(jsonObject.getLong(FIELD_EXPIRES)) + .setId(jsonObject.getString(FIELD_ID)) + .setLiveMode(jsonObject.getBoolean(FIELD_LIVEMODE)) + .setObject(jsonObject.getString(FIELD_OBJECT)) + .setSecret(jsonObject.getString(FIELD_SECRET)) + .setType(typeObject.getString(FIELD_TYPE)) + .setObjectId(typeObject.getString(FIELD_ID)) + .build(); } @Override @@ -272,4 +191,71 @@ public int hashCode() { return ObjectUtils.hash(mObjectId, mCreated, mExpires, mId, mLiveMode, mObject, mSecret, mType); } + + abstract static class Builder { + @Nullable private String mObjectId; + private long mCreated; + private long mExpires; + @Nullable private String mId; + private boolean mLiveMode; + @Nullable private String mObject; + @Nullable private String mSecret; + @Nullable private String mType; + + @NonNull + Builder setObjectId(@NonNull String objectId) { + this.mObjectId = objectId; + return this; + } + + @NonNull + Builder setCreated(long created) { + this.mCreated = created; + return this; + } + + @NonNull + Builder setExpires(long expires) { + this.mExpires = expires; + return this; + } + + @NonNull + Builder setId(@NonNull String id) { + this.mId = id; + return this; + } + + @NonNull + Builder setLiveMode(boolean liveMode) { + this.mLiveMode = liveMode; + return this; + } + + @NonNull + Builder setObject(@NonNull String object) { + this.mObject = object; + return this; + } + + @NonNull + Builder setSecret(@NonNull String secret) { + this.mSecret = secret; + return this; + } + + @NonNull + Builder setType(@NonNull String type) { + this.mType = type; + return this; + } + + @NonNull + abstract T build(); + } + + abstract static class BuilderFactory> { + @NonNull + abstract Builder create(); + } } diff --git a/stripe/src/main/java/com/stripe/android/CustomerEphemeralKey.java b/stripe/src/main/java/com/stripe/android/CustomerEphemeralKey.java index c0ea04a2951..075bd8300cc 100644 --- a/stripe/src/main/java/com/stripe/android/CustomerEphemeralKey.java +++ b/stripe/src/main/java/com/stripe/android/CustomerEphemeralKey.java @@ -3,12 +3,11 @@ import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; -import android.support.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; -class CustomerEphemeralKey extends AbstractEphemeralKey { +final class CustomerEphemeralKey extends AbstractEphemeralKey { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @@ -27,30 +26,8 @@ private CustomerEphemeralKey(@NonNull Parcel in) { super(in); } - protected CustomerEphemeralKey( - long created, - @NonNull String customerId, - long expires, - @NonNull String id, - boolean liveMode, - @NonNull String object, - @NonNull String secret, - @NonNull String type - ) { - super(created, - customerId, - expires, - id, - liveMode, - object, - secret, - type); - - } - - @SuppressWarnings("checkstyle:RedundantModifier") // Not actually redundant :| - public CustomerEphemeralKey(@Nullable JSONObject jsonObject) throws JSONException { - super(jsonObject); + private CustomerEphemeralKey(@NonNull Builder builder) { + super(builder); } @NonNull @@ -59,14 +36,24 @@ String getCustomerId() { } @NonNull - static CustomerEphemeralKey fromString(@Nullable String rawJson) throws JSONException { - return AbstractEphemeralKey - .fromString(rawJson, CustomerEphemeralKey.class); + static CustomerEphemeralKey fromJson(@NonNull JSONObject jsonObject) throws JSONException { + return AbstractEphemeralKey.fromJson(jsonObject, new Builder()); } - @NonNull - static CustomerEphemeralKey fromJson(@Nullable JSONObject jsonObject) { - return AbstractEphemeralKey - .fromJson(jsonObject, CustomerEphemeralKey.class); + static final class Builder extends AbstractEphemeralKey.Builder { + @NonNull + @Override + CustomerEphemeralKey build() { + return new CustomerEphemeralKey(this); + } + } + + static final class BuilderFactory extends AbstractEphemeralKey + .BuilderFactory> { + @NonNull + @Override + Builder create() { + return new Builder(); + } } } diff --git a/stripe/src/main/java/com/stripe/android/CustomerSession.java b/stripe/src/main/java/com/stripe/android/CustomerSession.java index 062ec55c5bf..c6f87f246d3 100644 --- a/stripe/src/main/java/com/stripe/android/CustomerSession.java +++ b/stripe/src/main/java/com/stripe/android/CustomerSession.java @@ -262,7 +262,7 @@ public void onError(@NonNull StripeException exception, @NonNull String operatio KEY_REFRESH_BUFFER_IN_SECONDS, proxyNowCalendar, mOperationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); } @RestrictTo(RestrictTo.Scope.LIBRARY) diff --git a/stripe/src/main/java/com/stripe/android/EphemeralKeyManager.java b/stripe/src/main/java/com/stripe/android/EphemeralKeyManager.java index c88bfa746e3..a96a8ecf2da 100644 --- a/stripe/src/main/java/com/stripe/android/EphemeralKeyManager.java +++ b/stripe/src/main/java/com/stripe/android/EphemeralKeyManager.java @@ -5,30 +5,33 @@ import android.support.annotation.VisibleForTesting; import org.json.JSONException; +import org.json.JSONObject; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.Map; import java.util.concurrent.TimeUnit; -class EphemeralKeyManager { +class EphemeralKeyManager { - @NonNull private final Class mEphemeralKeyClass; + @NonNull private final AbstractEphemeralKey + .BuilderFactory> mEphemeralkeyBuilderFactory; @NonNull private final EphemeralKeyProvider mEphemeralKeyProvider; @Nullable private final Calendar mOverrideCalendar; - @NonNull private final KeyManagerListener mListener; + @NonNull private final KeyManagerListener mListener; private final long mTimeBufferInSeconds; - @Nullable private TEphemeralKey mEphemeralKey; + @Nullable private EphemeralKey mEphemeralKey; EphemeralKeyManager( @NonNull EphemeralKeyProvider ephemeralKeyProvider, - @NonNull KeyManagerListener keyManagerListener, + @NonNull KeyManagerListener keyManagerListener, long timeBufferInSeconds, @Nullable Calendar overrideCalendar, @NonNull OperationIdFactory operationIdFactory, - @NonNull Class ephemeralKeyClass) { - mEphemeralKeyClass = ephemeralKeyClass; + @NonNull AbstractEphemeralKey.BuilderFactory> + ephemeralKeyBuilderFactory) { + mEphemeralkeyBuilderFactory = ephemeralKeyBuilderFactory; mEphemeralKeyProvider = ephemeralKeyProvider; mListener = keyManagerListener; mTimeBufferInSeconds = timeBufferInSeconds; @@ -52,7 +55,7 @@ void retrieveEphemeralKey(@NonNull String operationId, @Nullable @VisibleForTesting - TEphemeralKey getEphemeralKey() { + EphemeralKey getEphemeralKey() { return mEphemeralKey; } @@ -71,7 +74,8 @@ private void updateKey( return; } try { - mEphemeralKey = AbstractEphemeralKey.fromString(key, mEphemeralKeyClass); + mEphemeralKey = AbstractEphemeralKey.fromJson(new JSONObject(key), + mEphemeralkeyBuilderFactory.create()); mListener.onKeyUpdate(mEphemeralKey, operationId, actionString, arguments); } catch (JSONException e) { mListener.onKeyError(operationId, diff --git a/stripe/src/main/java/com/stripe/android/EphemeralKeyUpdateListener.java b/stripe/src/main/java/com/stripe/android/EphemeralKeyUpdateListener.java index 5291c67a1a3..36a7c671166 100644 --- a/stripe/src/main/java/com/stripe/android/EphemeralKeyUpdateListener.java +++ b/stripe/src/main/java/com/stripe/android/EphemeralKeyUpdateListener.java @@ -1,7 +1,6 @@ package com.stripe.android; import android.support.annotation.NonNull; -import android.support.annotation.Nullable; /** * Represents a listener for Ephemeral Key Update events. diff --git a/stripe/src/main/java/com/stripe/android/IssuingCardEphemeralKey.java b/stripe/src/main/java/com/stripe/android/IssuingCardEphemeralKey.java index 6f7fb2e259a..305a0f6b198 100644 --- a/stripe/src/main/java/com/stripe/android/IssuingCardEphemeralKey.java +++ b/stripe/src/main/java/com/stripe/android/IssuingCardEphemeralKey.java @@ -3,12 +3,8 @@ import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import org.json.JSONException; -import org.json.JSONObject; - -class IssuingCardEphemeralKey extends AbstractEphemeralKey { +final class IssuingCardEphemeralKey extends AbstractEphemeralKey { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @@ -27,30 +23,8 @@ private IssuingCardEphemeralKey(@NonNull Parcel in) { super(in); } - protected IssuingCardEphemeralKey( - long created, - @NonNull String customerId, - long expires, - @NonNull String id, - boolean liveMode, - @NonNull String object, - @NonNull String secret, - @NonNull String type - ) { - super(created, - customerId, - expires, - id, - liveMode, - object, - secret, - type); - - } - - @SuppressWarnings("checkstyle:RedundantModifier") // Not actually redundant :| - public IssuingCardEphemeralKey(@Nullable JSONObject jsonObject) throws JSONException { - super(jsonObject); + private IssuingCardEphemeralKey(@NonNull Builder builder) { + super(builder); } @NonNull @@ -58,15 +32,20 @@ String getIssuingCardId() { return mObjectId; } - @NonNull - static IssuingCardEphemeralKey fromString(@Nullable String rawJson) throws JSONException { - return AbstractEphemeralKey - .fromString(rawJson, IssuingCardEphemeralKey.class); + static final class Builder extends AbstractEphemeralKey.Builder { + @NonNull + @Override + IssuingCardEphemeralKey build() { + return new IssuingCardEphemeralKey(this); + } } - @NonNull - static IssuingCardEphemeralKey fromJson(@Nullable JSONObject jsonObject) { - return AbstractEphemeralKey - .fromJson(jsonObject, IssuingCardEphemeralKey.class); + static final class BuilderFactory extends AbstractEphemeralKey + .BuilderFactory> { + @NonNull + @Override + Builder create() { + return new Builder(); + } } } diff --git a/stripe/src/main/java/com/stripe/android/IssuingCardPinService.java b/stripe/src/main/java/com/stripe/android/IssuingCardPinService.java index 1764ca9f9c6..1536055722a 100644 --- a/stripe/src/main/java/com/stripe/android/IssuingCardPinService.java +++ b/stripe/src/main/java/com/stripe/android/IssuingCardPinService.java @@ -16,10 +16,12 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * Methods for retrieval / update of a Stripe Issuing card */ +@SuppressWarnings("WeakerAccess") public class IssuingCardPinService implements EphemeralKeyManager.KeyManagerListener { @@ -71,7 +73,7 @@ public static IssuingCardPinService create( KEY_REFRESH_BUFFER_IN_SECONDS, null, operationIdFactory, - IssuingCardEphemeralKey.class); + new IssuingCardEphemeralKey.BuilderFactory()); mApiHandler = apiHandler; } @@ -148,16 +150,16 @@ public void onKeyUpdate(@NonNull IssuingCardEphemeralKey ephemeralKey, null); return; } - String cardId = (String) arguments.get(ARGUMENT_CARD_ID); - String verificationId = (String) arguments.get(ARGUMENT_VERIFICATION_ID); - String userOneTimeCode = (String) arguments.get(ARGUMENT_ONE_TIME_CODE); + final String cardId = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_CARD_ID)); + final String verificationId = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_VERIFICATION_ID)); + final String userOneTimeCode = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_ONE_TIME_CODE)); try { - final String pin = mApiHandler.retrieveIssuingCardPin( - cardId, - verificationId, - userOneTimeCode, - ephemeralKey.getSecret()); + final String pin = mApiHandler.retrieveIssuingCardPin(cardId, verificationId, + userOneTimeCode, ephemeralKey.getSecret()); listener.onIssuingCardPinRetrieved(pin); } catch (InvalidRequestException e) { @@ -217,17 +219,17 @@ public void onKeyUpdate(@NonNull IssuingCardEphemeralKey ephemeralKey, null); return; } - String cardId = (String) arguments.get(ARGUMENT_CARD_ID); - String newPin = (String) arguments.get(ARGUMENT_NEW_PIN); - String verificationId = (String) arguments.get(ARGUMENT_VERIFICATION_ID); - String userOneTimeCode = (String) arguments.get(ARGUMENT_ONE_TIME_CODE); + final String cardId = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_CARD_ID)); + final String newPin = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_NEW_PIN)); + final String verificationId = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_VERIFICATION_ID)); + final String userOneTimeCode = + (String) Objects.requireNonNull(arguments.get(ARGUMENT_ONE_TIME_CODE)); try { - mApiHandler.updateIssuingCardPin( - cardId, - newPin, - verificationId, - userOneTimeCode, + mApiHandler.updateIssuingCardPin(cardId, newPin, verificationId, userOneTimeCode, ephemeralKey.getSecret()); listener.onIssuingCardPinUpdated(); } catch (InvalidRequestException e) { diff --git a/stripe/src/main/java/com/stripe/android/model/Address.java b/stripe/src/main/java/com/stripe/android/model/Address.java index fc340a0126f..b536ab873e9 100644 --- a/stripe/src/main/java/com/stripe/android/model/Address.java +++ b/stripe/src/main/java/com/stripe/android/model/Address.java @@ -20,13 +20,12 @@ import java.util.Map; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for an owner address * object in the Source api. */ -public class Address extends StripeJsonModel implements Parcelable { +public class Address extends StripeModel implements Parcelable { @IntDef({ RequiredBillingAddressFields.NONE, @@ -141,19 +140,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putStringIfNotNull(jsonObject, FIELD_CITY, mCity); - putStringIfNotNull(jsonObject, FIELD_COUNTRY, mCountry); - putStringIfNotNull(jsonObject, FIELD_LINE_1, mLine1); - putStringIfNotNull(jsonObject, FIELD_LINE_2, mLine2); - putStringIfNotNull(jsonObject, FIELD_POSTAL_CODE, mPostalCode); - putStringIfNotNull(jsonObject, FIELD_STATE, mState); - return jsonObject; - } - @Nullable public static Address fromString(@Nullable String jsonString) { try { diff --git a/stripe/src/main/java/com/stripe/android/model/Card.java b/stripe/src/main/java/com/stripe/android/model/Card.java index 59daf318d53..57a5305a160 100644 --- a/stripe/src/main/java/com/stripe/android/model/Card.java +++ b/stripe/src/main/java/com/stripe/android/model/Card.java @@ -30,14 +30,11 @@ import static com.stripe.android.model.StripeJsonUtils.optHash; import static com.stripe.android.model.StripeJsonUtils.optInteger; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putIntegerIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringHashIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * A model object representing a Card in the Android SDK. */ -public class Card extends StripeJsonModel implements StripePaymentSource { +public class Card extends StripeModel implements StripePaymentSource { @Retention(RetentionPolicy.SOURCE) @StringDef({ @@ -790,36 +787,6 @@ public String getCvcCheck() { return cvcCheck; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject object = new JSONObject(); - putStringIfNotNull(object, FIELD_NAME, name); - putStringIfNotNull(object, FIELD_ADDRESS_CITY, addressCity); - putStringIfNotNull(object, FIELD_ADDRESS_COUNTRY, addressCountry); - putStringIfNotNull(object, FIELD_ADDRESS_LINE1, addressLine1); - putStringIfNotNull(object, FIELD_ADDRESS_LINE1_CHECK, addressLine1Check); - putStringIfNotNull(object, FIELD_ADDRESS_LINE2, addressLine2); - putStringIfNotNull(object, FIELD_ADDRESS_STATE, addressState); - putStringIfNotNull(object, FIELD_ADDRESS_ZIP, addressZip); - putStringIfNotNull(object, FIELD_ADDRESS_ZIP_CHECK, addressZipCheck); - putStringIfNotNull(object, FIELD_BRAND, brand); - putStringIfNotNull(object, FIELD_CURRENCY, currency); - putStringIfNotNull(object, FIELD_COUNTRY, country); - putStringIfNotNull(object, FIELD_CUSTOMER, customerId); - putIntegerIfNotNull(object, FIELD_EXP_MONTH, expMonth); - putIntegerIfNotNull(object, FIELD_EXP_YEAR, expYear); - putStringIfNotNull(object, FIELD_FINGERPRINT, fingerprint); - putStringIfNotNull(object, FIELD_FUNDING, funding); - putStringIfNotNull(object, FIELD_CVC_CHECK, cvcCheck); - putStringIfNotNull(object, FIELD_LAST4, last4); - putStringIfNotNull(object, FIELD_ID, id); - putStringIfNotNull(object, FIELD_TOKENIZATION_METHOD, tokenizationMethod); - putStringHashIfNotNull(object, FIELD_METADATA, metadata); - putStringIfNotNull(object, FIELD_OBJECT, VALUE_CARD); - return object; - } - @NonNull @Override public Map toMap() { diff --git a/stripe/src/main/java/com/stripe/android/model/Customer.java b/stripe/src/main/java/com/stripe/android/model/Customer.java index 928ee8fde05..3091e29e292 100644 --- a/stripe/src/main/java/com/stripe/android/model/Customer.java +++ b/stripe/src/main/java/com/stripe/android/model/Customer.java @@ -19,15 +19,11 @@ import static com.stripe.android.model.StripeJsonUtils.optBoolean; import static com.stripe.android.model.StripeJsonUtils.optInteger; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putBooleanIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putIntegerIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putObjectIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for a Stripe Customer object */ -public class Customer extends StripeJsonModel { +public class Customer extends StripeModel { private static final String FIELD_ID = "id"; private static final String FIELD_OBJECT = "object"; @@ -83,6 +79,7 @@ public List getSources() { return mSources; } + @Nullable public Boolean getHasMore() { return mHasMore; } @@ -105,28 +102,6 @@ public CustomerSource getSourceById(@NonNull String sourceId) { return null; } - @NonNull - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - putStringIfNotNull(jsonObject, FIELD_ID, mId); - putStringIfNotNull(jsonObject, FIELD_OBJECT, VALUE_CUSTOMER); - putStringIfNotNull(jsonObject, FIELD_DEFAULT_SOURCE, mDefaultSource); - StripeJsonModel.putStripeJsonModelIfNotNull(jsonObject, - FIELD_SHIPPING, - mShippingInformation); - JSONObject sourcesObject = new JSONObject(); - putStringIfNotNull(sourcesObject, FIELD_OBJECT, VALUE_LIST); - putBooleanIfNotNull(sourcesObject, FIELD_HAS_MORE, mHasMore); - putIntegerIfNotNull(sourcesObject, FIELD_TOTAL_COUNT, mTotalCount); - putStripeJsonModelListIfNotNull(sourcesObject, FIELD_DATA, mSources); - putStringIfNotNull(sourcesObject, FIELD_URL, mUrl); - - putObjectIfNotNull(jsonObject, FIELD_SOURCES, sourcesObject); - - return jsonObject; - } - @NonNull @Override public Map toMap() { @@ -135,17 +110,14 @@ public Map toMap() { map.put(FIELD_OBJECT, VALUE_CUSTOMER); map.put(FIELD_DEFAULT_SOURCE, mDefaultSource); - StripeJsonModel.putStripeJsonModelMapIfNotNull( - map, - FIELD_SHIPPING, - mShippingInformation); + putModelIfNotNull(map, FIELD_SHIPPING, mShippingInformation); final AbstractMap sourcesObject = new HashMap<>(); sourcesObject.put(FIELD_HAS_MORE, mHasMore); sourcesObject.put(FIELD_TOTAL_COUNT, mTotalCount); sourcesObject.put(FIELD_OBJECT, VALUE_LIST); sourcesObject.put(FIELD_URL, mUrl); - StripeJsonModel.putStripeJsonModelListIfNotNull( + StripeModel.putModelIfNotNull( sourcesObject, FIELD_DATA, mSources); diff --git a/stripe/src/main/java/com/stripe/android/model/CustomerSource.java b/stripe/src/main/java/com/stripe/android/model/CustomerSource.java index a0632640ab9..ac1053dec57 100644 --- a/stripe/src/main/java/com/stripe/android/model/CustomerSource.java +++ b/stripe/src/main/java/com/stripe/android/model/CustomerSource.java @@ -16,7 +16,7 @@ /** * Model of the "data" object inside a {@link Customer} "source" object. */ -public class CustomerSource extends StripeJsonModel implements StripePaymentSource { +public class CustomerSource extends StripeModel implements StripePaymentSource { @NonNull private final StripePaymentSource mStripePaymentSource; @@ -121,17 +121,6 @@ public Map toMap() { return new HashMap<>(); } - @NonNull - @Override - public JSONObject toJson() { - if (mStripePaymentSource instanceof Source) { - return ((Source) mStripePaymentSource).toJson(); - } else if (mStripePaymentSource instanceof Card) { - return ((Card) mStripePaymentSource).toJson(); - } - return new JSONObject(); - } - @Override public boolean equals(@Nullable Object obj) { return this == obj || (obj instanceof CustomerSource && typedEquals((CustomerSource) obj)); diff --git a/stripe/src/main/java/com/stripe/android/model/PaymentIntent.java b/stripe/src/main/java/com/stripe/android/model/PaymentIntent.java index 615ec85360a..3d35344384a 100644 --- a/stripe/src/main/java/com/stripe/android/model/PaymentIntent.java +++ b/stripe/src/main/java/com/stripe/android/model/PaymentIntent.java @@ -19,17 +19,11 @@ import java.util.Map; import java.util.Objects; -import static com.stripe.android.model.StripeJsonUtils.listToJsonArray; import static com.stripe.android.model.StripeJsonUtils.optBoolean; import static com.stripe.android.model.StripeJsonUtils.optCurrency; import static com.stripe.android.model.StripeJsonUtils.optLong; import static com.stripe.android.model.StripeJsonUtils.optMap; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putArrayIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putBooleanIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putLongIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putMapIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * A PaymentIntent tracks the process of collecting a payment from your customer. @@ -39,7 +33,7 @@ *
  • PaymentIntents API
  • * */ -public class PaymentIntent extends StripeJsonModel { +public class PaymentIntent extends StripeModel { private static final String VALUE_PAYMENT_INTENT = "payment_intent"; static final String FIELD_ID = "id"; @@ -328,30 +322,6 @@ private static List jsonArrayToList(@Nullable JSONArray jsonArray) { return list; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putStringIfNotNull(jsonObject, FIELD_ID, mId); - putStringIfNotNull(jsonObject, FIELD_OBJECT, mObjectType); - putArrayIfNotNull(jsonObject, FIELD_PAYMENT_METHOD_TYPES, - listToJsonArray(mPaymentMethodTypes)); - putLongIfNotNull(jsonObject, FIELD_AMOUNT, mAmount); - putLongIfNotNull(jsonObject, FIELD_CANCELED, mCanceledAt); - putStringIfNotNull(jsonObject, FIELD_CAPTURE_METHOD, mCaptureMethod); - putStringIfNotNull(jsonObject, FIELD_CLIENT_SECRET, mClientSecret); - putStringIfNotNull(jsonObject, FIELD_CONFIRMATION_METHOD, mConfirmationMethod); - putLongIfNotNull(jsonObject, FIELD_CREATED, mCreated); - putStringIfNotNull(jsonObject, FIELD_CURRENCY, mCurrency); - putStringIfNotNull(jsonObject, FIELD_DESCRIPTION, mDescription); - putBooleanIfNotNull(jsonObject, FIELD_LIVEMODE, mLiveMode); - putMapIfNotNull(jsonObject, FIELD_NEXT_ACTION, mNextAction); - putStringIfNotNull(jsonObject, FIELD_RECEIPT_EMAIL, mReceiptEmail); - putStringIfNotNull(jsonObject, FIELD_SOURCE, mSource); - putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus != null ? mStatus.code : null); - return jsonObject; - } - @NonNull @Override public Map toMap() { diff --git a/stripe/src/main/java/com/stripe/android/model/PaymentMethod.java b/stripe/src/main/java/com/stripe/android/model/PaymentMethod.java index f82c52c0a36..eba57044139 100644 --- a/stripe/src/main/java/com/stripe/android/model/PaymentMethod.java +++ b/stripe/src/main/java/com/stripe/android/model/PaymentMethod.java @@ -33,7 +33,8 @@ * * See {@link PaymentMethodCreateParams} for PaymentMethod creation */ -public class PaymentMethod extends StripeJsonModel implements Parcelable { +@SuppressWarnings("WeakerAccess") +public class PaymentMethod extends StripeModel implements Parcelable { private static final String FIELD_ID = "id"; private static final String FIELD_BILLING_DETAILS = "billing_details"; private static final String FIELD_CARD = "card"; @@ -110,31 +111,6 @@ public Map toMap() { return paymentMethod; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject paymentMethod = new JSONObject(); - try { - paymentMethod.put(FIELD_ID, id); - paymentMethod.put(FIELD_CREATED, created); - paymentMethod.put(FIELD_CUSTOMER, customerId); - paymentMethod.put(FIELD_LIVEMODE, liveMode); - paymentMethod.put(FIELD_METADATA, metadata != null ? new JSONObject(metadata) : null); - paymentMethod.put(FIELD_TYPE, type); - paymentMethod.put(FIELD_BILLING_DETAILS, - billingDetails != null ? billingDetails.toJson() : null); - paymentMethod.put(FIELD_CARD, - card != null ? card.toJson() : null); - paymentMethod.put(FIELD_CARD_PRESENT, - cardPresent != null ? cardPresent.toJson() : null); - paymentMethod.put(FIELD_IDEAL, - ideal != null ? ideal.toJson() : null); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return paymentMethod; - } - @Nullable public static PaymentMethod fromString(@Nullable String jsonString) { if (jsonString == null) { @@ -241,12 +217,13 @@ private PaymentMethod(@NonNull Parcel in) { customerId = in.readString(); final int mapSize = in.readInt(); if (mapSize >= 0) { - metadata = new HashMap<>(mapSize); - for (int x = 0; x < mapSize; x++) { + final AbstractMap metadata = new HashMap<>(mapSize); + for (int i = 0; i < mapSize; i++) { metadata.put(in.readString(), in.readString()); } + this.metadata = metadata; } else { - metadata = null; + this.metadata = null; } } @@ -343,7 +320,7 @@ public PaymentMethod build() { } } - public static final class BillingDetails extends StripeJsonModel implements Parcelable { + public static final class BillingDetails extends StripeModel implements Parcelable { static final String FIELD_ADDRESS = "address"; static final String FIELD_EMAIL = "email"; static final String FIELD_NAME = "name"; @@ -414,21 +391,6 @@ public Map toMap() { return billingDetails; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject billingDetails = new JSONObject(); - try { - billingDetails.put(FIELD_ADDRESS, address != null ? address.toJson() : null); - billingDetails.put(FIELD_EMAIL, email); - billingDetails.put(FIELD_NAME, name); - billingDetails.put(FIELD_PHONE, phone); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return billingDetails; - } - @Nullable public static BillingDetails fromJson(@Nullable JSONObject billingDetails) { if (billingDetails == null) { @@ -625,26 +587,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject json = new JSONObject(); - try { - json.put(FIELD_BRAND, brand); - json.put(FIELD_CHECKS, checks != null ? checks.toJson() : null); - json.put(FIELD_COUNTRY, country); - json.put(FIELD_EXP_MONTH, expiryMonth); - json.put(FIELD_EXP_YEAR, expiryYear); - json.put(FIELD_FUNDING, funding); - json.put(FIELD_LAST4, last4); - json.put(FIELD_THREE_D_SECURE_USAGE, threeDSecureUsage != null ? - threeDSecureUsage.toJson() : null); - json.put(FIELD_WALLET, wallet); - } catch (JSONException ignore) { - } - return json; - } - @Nullable public static Card fromJson(@Nullable JSONObject cardJson) { if (cardJson == null) { @@ -759,7 +701,7 @@ public Card build() { } } - public static final class Checks extends StripeJsonModel implements Parcelable { + public static final class Checks extends StripeModel implements Parcelable { private static final String FIELD_ADDRESS_LINE1_CHECK = "address_line1_check"; private static final String FIELD_ADDRESS_POSTAL_CODE_CHECK = "address_postal_code_check"; @@ -816,19 +758,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject json = new JSONObject(); - try { - json.put(FIELD_ADDRESS_LINE1_CHECK, addressLine1Check); - json.put(FIELD_ADDRESS_POSTAL_CODE_CHECK, addressPostalCodeCheck); - json.put(FIELD_CVC_CHECK, cvcCheck); - } catch (JSONException ignore) { - } - return json; - } - @Nullable public static Checks fromJson(@Nullable JSONObject checksJson) { if (checksJson == null) { @@ -889,7 +818,7 @@ public Checks build() { } } - public static final class ThreeDSecureUsage extends StripeJsonModel implements Parcelable { + public static final class ThreeDSecureUsage extends StripeModel implements Parcelable { private static final String FIELD_IS_SUPPORTED = "supported"; public final boolean isSupported; @@ -933,17 +862,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject json = new JSONObject(); - try { - json.put(FIELD_IS_SUPPORTED, isSupported); - } catch (JSONException ignore) { - } - return json; - } - @Nullable public static ThreeDSecureUsage fromJson(@Nullable JSONObject threeDSecureUsage) { if (threeDSecureUsage == null) { @@ -1018,12 +936,6 @@ public Map toMap() { return new HashMap<>(); } - @NonNull - @Override - public JSONObject toJson() { - return new JSONObject(); - } - @Override public int hashCode() { return ObjectUtils.hash(type); @@ -1086,19 +998,6 @@ public Map toMap() { return ideal; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject ideal = new JSONObject(); - try { - ideal.put(FIELD_BANK, bank); - ideal.put(FIELD_BIC, bankIdentifierCode); - } catch (JSONException e) { - throw new RuntimeException(e); - } - return ideal; - } - @Nullable public static Ideal fromJson(@Nullable JSONObject ideal) { if (ideal == null) { @@ -1149,7 +1048,7 @@ public Ideal build() { } } - private abstract static class PaymentMethodTypeImpl extends StripeJsonModel + private abstract static class PaymentMethodTypeImpl extends StripeModel implements Parcelable { @NonNull public final Type type; diff --git a/stripe/src/main/java/com/stripe/android/model/ShippingInformation.java b/stripe/src/main/java/com/stripe/android/model/ShippingInformation.java index cf25b72d103..4d39670c14b 100644 --- a/stripe/src/main/java/com/stripe/android/model/ShippingInformation.java +++ b/stripe/src/main/java/com/stripe/android/model/ShippingInformation.java @@ -15,12 +15,11 @@ import java.util.Map; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model representing a shipping address object */ -public class ShippingInformation extends StripeJsonModel implements Parcelable { +public class ShippingInformation extends StripeModel implements Parcelable { public static final Creator CREATOR = new Creator() { @Override public ShippingInformation createFromParcel(Parcel source) { @@ -85,23 +84,13 @@ public static ShippingInformation fromJson(@Nullable JSONObject jsonObject) { optString(jsonObject, FIELD_PHONE)); } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putStringIfNotNull(jsonObject, FIELD_NAME, mName); - putStringIfNotNull(jsonObject, FIELD_PHONE, mPhone); - putStripeJsonModelIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); - return jsonObject; - } - @NonNull @Override public Map toMap() { final AbstractMap map = new HashMap<>(); map.put(FIELD_NAME, mName); map.put(FIELD_PHONE, mPhone); - putStripeJsonModelMapIfNotNull(map, FIELD_ADDRESS, mAddress); + putModelIfNotNull(map, FIELD_ADDRESS, mAddress); StripeNetworkUtils.removeNullAndEmptyParams(map); return map; } diff --git a/stripe/src/main/java/com/stripe/android/model/ShippingMethod.java b/stripe/src/main/java/com/stripe/android/model/ShippingMethod.java index 51d2e629263..6d2a5d5ea61 100644 --- a/stripe/src/main/java/com/stripe/android/model/ShippingMethod.java +++ b/stripe/src/main/java/com/stripe/android/model/ShippingMethod.java @@ -8,20 +8,16 @@ import com.stripe.android.utils.ObjectUtils; -import org.json.JSONObject; - import java.util.AbstractMap; import java.util.Currency; import java.util.HashMap; import java.util.Map; - -import static com.stripe.android.model.StripeJsonUtils.putLongIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; +import java.util.Objects; /** * Model representing a shipping method in the Android SDK. */ -public class ShippingMethod extends StripeJsonModel implements Parcelable { +public class ShippingMethod extends StripeModel implements Parcelable { public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @@ -69,10 +65,10 @@ public ShippingMethod(@NonNull String label, private ShippingMethod(@NonNull Parcel in) { mAmount = in.readLong(); - mCurrencyCode = in.readString(); + mCurrencyCode = Objects.requireNonNull(in.readString()); mDetail = in.readString(); - mIdentifier = in.readString(); - mLabel = in.readString(); + mIdentifier = Objects.requireNonNull(in.readString()); + mLabel = Objects.requireNonNull(in.readString()); } /** @@ -117,18 +113,6 @@ public String getIdentifier() { return mIdentifier; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putLongIfNotNull(jsonObject, FIELD_AMOUNT, mAmount); - putStringIfNotNull(jsonObject, FIELD_CURRENCY_CODE, mCurrencyCode); - putStringIfNotNull(jsonObject, FIELD_DETAIL, mDetail); - putStringIfNotNull(jsonObject, FIELD_IDENTIFIER, mIdentifier); - putStringIfNotNull(jsonObject, FIELD_LABEL, mLabel); - return jsonObject; - } - @NonNull @Override public Map toMap() { diff --git a/stripe/src/main/java/com/stripe/android/model/Source.java b/stripe/src/main/java/com/stripe/android/model/Source.java index a0042adc1fb..71dcdce687d 100644 --- a/stripe/src/main/java/com/stripe/android/model/Source.java +++ b/stripe/src/main/java/com/stripe/android/model/Source.java @@ -19,17 +19,16 @@ import java.util.Set; import static com.stripe.android.StripeNetworkUtils.removeNullAndEmptyParams; -import static com.stripe.android.model.StripeJsonUtils.mapToJsonObject; import static com.stripe.android.model.StripeJsonUtils.optLong; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * A model class representing a source in the Android SDK. More detailed information and interaction * can be seen at * https://stripe.com/docs/api/sources/object?lang=java. */ -public class Source extends StripeJsonModel implements StripePaymentSource { +@SuppressWarnings("WeakerAccess") +public class Source extends StripeModel implements StripePaymentSource { static final String VALUE_SOURCE = "source"; private static final String VALUE_CARD = "card"; @@ -358,10 +357,11 @@ public void setUsage(@Usage String usage) { public Map toMap() { final AbstractMap map = new HashMap<>(); map.put(FIELD_ID, mId); + map.put(FIELD_OBJECT, VALUE_SOURCE); map.put(FIELD_AMOUNT, mAmount); map.put(FIELD_CLIENT_SECRET, mClientSecret); - putStripeJsonModelMapIfNotNull(map, FIELD_CODE_VERIFICATION, mCodeVerification); + putModelIfNotNull(map, FIELD_CODE_VERIFICATION, mCodeVerification); map.put(FIELD_CREATED, mCreated); map.put(FIELD_CURRENCY, mCurrency); @@ -369,9 +369,9 @@ public Map toMap() { map.put(FIELD_LIVEMODE, mLiveMode); map.put(FIELD_METADATA, mMetaData); - putStripeJsonModelMapIfNotNull(map, FIELD_OWNER, mOwner); - putStripeJsonModelMapIfNotNull(map, FIELD_RECEIVER, mReceiver); - putStripeJsonModelMapIfNotNull(map, FIELD_REDIRECT, mRedirect); + putModelIfNotNull(map, FIELD_OWNER, mOwner); + putModelIfNotNull(map, FIELD_RECEIVER, mReceiver); + putModelIfNotNull(map, FIELD_REDIRECT, mRedirect); map.put(mTypeRaw, mSourceTypeData); @@ -382,43 +382,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - try { - putStringIfNotNull(jsonObject, FIELD_ID, mId); - jsonObject.put(FIELD_OBJECT, VALUE_SOURCE); - jsonObject.put(FIELD_AMOUNT, mAmount); - putStringIfNotNull(jsonObject, FIELD_CLIENT_SECRET, mClientSecret); - putStripeJsonModelIfNotNull(jsonObject, FIELD_CODE_VERIFICATION, mCodeVerification); - jsonObject.put(FIELD_CREATED, mCreated); - putStringIfNotNull(jsonObject, FIELD_CURRENCY, mCurrency); - putStringIfNotNull(jsonObject, FIELD_FLOW, mFlow); - jsonObject.put(FIELD_LIVEMODE, mLiveMode); - - JSONObject metaDataObject = mapToJsonObject(mMetaData); - if (metaDataObject != null) { - jsonObject.put(FIELD_METADATA, metaDataObject); - } - - JSONObject sourceTypeJsonObject = mapToJsonObject(mSourceTypeData); - - if (sourceTypeJsonObject != null) { - jsonObject.put(mTypeRaw, sourceTypeJsonObject); - } - - putStripeJsonModelIfNotNull(jsonObject, FIELD_OWNER, mOwner); - putStripeJsonModelIfNotNull(jsonObject, FIELD_RECEIVER, mReceiver); - putStripeJsonModelIfNotNull(jsonObject, FIELD_REDIRECT, mRedirect); - putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); - putStringIfNotNull(jsonObject, FIELD_TYPE, mTypeRaw); - putStringIfNotNull(jsonObject, FIELD_USAGE, mUsage); - - } catch (JSONException ignored) { } - return jsonObject; - } - @Nullable public static Source fromString(@Nullable String jsonString) { try { @@ -515,7 +478,7 @@ private static Source fromSourceJson(@NonNull JSONObject jsonObject) { } @Nullable - private static T optStripeJsonModel( + private static T optStripeJsonModel( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String key, Class type) { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceCardData.java b/stripe/src/main/java/com/stripe/android/model/SourceCardData.java index d4f9acf4a1e..6c7bb62ec4f 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceCardData.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceCardData.java @@ -22,12 +22,11 @@ import static com.stripe.android.model.StripeJsonUtils.optInteger; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putIntegerIfNotNull; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for data contained in the SourceTypeData of a Card Source. */ +@SuppressWarnings("WeakerAccess") public class SourceCardData extends StripeSourceTypeModel { @Retention(RetentionPolicy.SOURCE) @@ -165,24 +164,6 @@ public String getTokenizationMethod() { return mTokenizationMethod; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = super.toJson(); - putStringIfNotNull(jsonObject, FIELD_ADDRESS_LINE1_CHECK, mAddressLine1Check); - putStringIfNotNull(jsonObject, FIELD_ADDRESS_ZIP_CHECK, mAddressZipCheck); - putStringIfNotNull(jsonObject, FIELD_BRAND, mBrand); - putStringIfNotNull(jsonObject, FIELD_COUNTRY, mCountry); - putStringIfNotNull(jsonObject, FIELD_DYNAMIC_LAST4, mDynamicLast4); - putIntegerIfNotNull(jsonObject, FIELD_EXP_MONTH, mExpiryMonth); - putIntegerIfNotNull(jsonObject, FIELD_EXP_YEAR, mExpiryYear); - putStringIfNotNull(jsonObject, FIELD_FUNDING, mFunding); - putStringIfNotNull(jsonObject, FIELD_LAST4, mLast4); - putStringIfNotNull(jsonObject, FIELD_THREE_D_SECURE, mThreeDSecureStatus); - putStringIfNotNull(jsonObject, FIELD_TOKENIZATION_METHOD, mTokenizationMethod); - return jsonObject; - } - @NonNull @Override public Map toMap() { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceCodeVerification.java b/stripe/src/main/java/com/stripe/android/model/SourceCodeVerification.java index 15a77b7581d..4c2b942cb9a 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceCodeVerification.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceCodeVerification.java @@ -21,7 +21,7 @@ * https://stripe.com/docs/api/sources/object#source_object-code_verification * object in the source api, not source code verification */ -public class SourceCodeVerification extends StripeJsonModel { +public class SourceCodeVerification extends StripeModel { // Note: these are the same as the values for the @Redirect.Status StringDef. // They don't have to stay the same forever, so they are redefined here. @@ -69,19 +69,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - - try { - jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); - StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); - } catch (JSONException ignored) { } - - return jsonObject; - } - @Nullable public static SourceCodeVerification fromString(@Nullable String jsonString) { try { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceOwner.java b/stripe/src/main/java/com/stripe/android/model/SourceOwner.java index d0ffbee85c9..8bdc36d4541 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceOwner.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceOwner.java @@ -14,13 +14,12 @@ import static com.stripe.android.StripeNetworkUtils.removeNullAndEmptyParams; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for a owner object * in the Source api. */ -public class SourceOwner extends StripeJsonModel { +public class SourceOwner extends StripeModel { private static final String VERIFIED = "verified_"; private static final String FIELD_ADDRESS = "address"; @@ -152,32 +151,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - final JSONObject jsonAddressObject = mAddress == null ? null : mAddress.toJson(); - final JSONObject jsonVerifiedAddressObject = mVerifiedAddress == null - ? null - : mVerifiedAddress.toJson(); - try { - if (jsonAddressObject != null && jsonAddressObject.length() > 0) { - jsonObject.put(FIELD_ADDRESS, jsonAddressObject); - } - putStringIfNotNull(jsonObject, FIELD_EMAIL, mEmail); - putStringIfNotNull(jsonObject, FIELD_NAME, mName); - putStringIfNotNull(jsonObject, FIELD_PHONE, mPhone); - if (jsonVerifiedAddressObject != null && jsonVerifiedAddressObject.length() > 0) { - jsonObject.put(FIELD_VERIFIED_ADDRESS, jsonVerifiedAddressObject); - } - putStringIfNotNull(jsonObject, FIELD_VERIFIED_EMAIL, mVerifiedEmail); - putStringIfNotNull(jsonObject, FIELD_VERIFIED_NAME, mVerifiedName); - putStringIfNotNull(jsonObject, FIELD_VERIFIED_PHONE, mVerifiedPhone); - } catch (JSONException ignored) { } - - return jsonObject; - } - @Nullable public static SourceOwner fromString(@Nullable String jsonString) { try { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceReceiver.java b/stripe/src/main/java/com/stripe/android/model/SourceReceiver.java index 219c6846bfc..88d2e5be8de 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceReceiver.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceReceiver.java @@ -16,7 +16,7 @@ * Model for a receiver object in * the source api. Present if the {@link Source} is a receiver. */ -public class SourceReceiver extends StripeJsonModel { +public class SourceReceiver extends StripeModel { private static final String FIELD_ADDRESS = "address"; private static final String FIELD_AMOUNT_CHARGED = "amount_charged"; @@ -86,21 +86,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); - try { - jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); - jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); - jsonObject.put(FIELD_AMOUNT_RETURNED, mAmountReturned); - } catch (JSONException jsonException) { - return jsonObject; - } - return jsonObject; - } - @Nullable public static SourceReceiver fromString(@Nullable String jsonString) { try { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceRedirect.java b/stripe/src/main/java/com/stripe/android/model/SourceRedirect.java index fef8be556b3..0b9839db231 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceRedirect.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceRedirect.java @@ -18,13 +18,12 @@ import static com.stripe.android.StripeNetworkUtils.removeNullAndEmptyParams; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for a * redirect object in the source api. */ -public class SourceRedirect extends StripeJsonModel { +public class SourceRedirect extends StripeModel { @Retention(RetentionPolicy.SOURCE) @StringDef({ @@ -93,16 +92,6 @@ public Map toMap() { return map; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putStringIfNotNull(jsonObject, FIELD_RETURN_URL, mReturnUrl); - putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); - putStringIfNotNull(jsonObject, FIELD_URL, mUrl); - return jsonObject; - } - @Nullable public static SourceRedirect fromString(@Nullable String jsonString) { try { diff --git a/stripe/src/main/java/com/stripe/android/model/SourceSepaDebitData.java b/stripe/src/main/java/com/stripe/android/model/SourceSepaDebitData.java index c42a4fb9358..b18e653cfdb 100644 --- a/stripe/src/main/java/com/stripe/android/model/SourceSepaDebitData.java +++ b/stripe/src/main/java/com/stripe/android/model/SourceSepaDebitData.java @@ -18,7 +18,6 @@ import java.util.Set; import static com.stripe.android.model.StripeJsonUtils.optString; -import static com.stripe.android.model.StripeJsonUtils.putStringIfNotNull; /** * Model for the SourceTypeData contained in a SEPA Debit Source object. @@ -119,20 +118,6 @@ public String getMandateUrl() { return mMandateUrl; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = super.toJson(); - putStringIfNotNull(jsonObject, FIELD_BANK_CODE, mBankCode); - putStringIfNotNull(jsonObject, FIELD_BRANCH_CODE, mBranchCode); - putStringIfNotNull(jsonObject, FIELD_COUNTRY, mCountry); - putStringIfNotNull(jsonObject, FIELD_FINGERPRINT, mFingerPrint); - putStringIfNotNull(jsonObject, FIELD_LAST4, mLast4); - putStringIfNotNull(jsonObject, FIELD_MANDATE_REFERENCE, mMandateReference); - putStringIfNotNull(jsonObject, FIELD_MANDATE_URL, mMandateUrl); - return jsonObject; - } - @NonNull @Override public Map toMap() { diff --git a/stripe/src/main/java/com/stripe/android/model/StripeJsonModel.java b/stripe/src/main/java/com/stripe/android/model/StripeJsonModel.java deleted file mode 100644 index 88895979ab1..00000000000 --- a/stripe/src/main/java/com/stripe/android/model/StripeJsonModel.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.stripe.android.model; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.Size; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Represents a JSON model used in the Stripe Api. - */ -public abstract class StripeJsonModel { - - @NonNull - public abstract Map toMap(); - - @NonNull - public abstract JSONObject toJson(); - - static void putStripeJsonModelMapIfNotNull( - @NonNull Map upperLevelMap, - @NonNull @Size(min = 1) String key, - @Nullable StripeJsonModel jsonModel) { - if (jsonModel == null) { - return; - } - upperLevelMap.put(key, jsonModel.toMap()); - } - - - static void putStripeJsonModelIfNotNull( - @NonNull JSONObject jsonObject, - @NonNull @Size(min = 1) String key, - @Nullable StripeJsonModel jsonModel) { - if (jsonModel == null) { - return; - } - - try { - jsonObject.put(key, jsonModel.toJson()); - } catch (JSONException ignored) { - } - } - - static void putStripeJsonModelListIfNotNull( - @NonNull Map upperLevelMap, - @NonNull @Size(min = 1) String key, - @Nullable List jsonModelList) { - if (jsonModelList == null) { - return; - } - - List> mapList = new ArrayList<>(); - for (int i = 0; i < jsonModelList.size(); i++) { - mapList.add(jsonModelList.get(i).toMap()); - } - upperLevelMap.put(key, mapList); - } - - - static void putStripeJsonModelListIfNotNull( - @NonNull JSONObject jsonObject, - @NonNull @Size(min = 1) String key, - @Nullable List jsonModelList) { - if (jsonModelList == null) { - return; - } - - try { - JSONArray array = new JSONArray(); - for (StripeJsonModel model : jsonModelList) { - array.put(model.toJson()); - } - jsonObject.put(key, array); - } catch (JSONException ignored) { - } - } -} diff --git a/stripe/src/main/java/com/stripe/android/model/StripeModel.java b/stripe/src/main/java/com/stripe/android/model/StripeModel.java new file mode 100644 index 00000000000..a6d6aeb014b --- /dev/null +++ b/stripe/src/main/java/com/stripe/android/model/StripeModel.java @@ -0,0 +1,45 @@ +package com.stripe.android.model; + +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.Size; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Represents a JSON model used in the Stripe Api. + */ +public abstract class StripeModel { + + @NonNull + public abstract Map toMap(); + + @Override + public abstract int hashCode(); + + @Override + public abstract boolean equals(@Nullable Object obj); + + static void putModelIfNotNull( + @NonNull Map upperLevelMap, + @NonNull @Size(min = 1) String key, + @Nullable StripeModel model) { + if (model == null) { + return; + } + upperLevelMap.put(key, model.toMap()); + } + + static void putModelIfNotNull( + @NonNull Map upperLevelMap, + @NonNull @Size(min = 1) String key, + @NonNull List models) { + final List> mapList = new ArrayList<>(); + for (StripeModel model : models) { + mapList.add(model.toMap()); + } + upperLevelMap.put(key, mapList); + } +} diff --git a/stripe/src/main/java/com/stripe/android/model/StripeSourceTypeModel.java b/stripe/src/main/java/com/stripe/android/model/StripeSourceTypeModel.java index 225c3e70bd4..86b3b9e0e06 100644 --- a/stripe/src/main/java/com/stripe/android/model/StripeSourceTypeModel.java +++ b/stripe/src/main/java/com/stripe/android/model/StripeSourceTypeModel.java @@ -15,7 +15,7 @@ import java.util.Map; import java.util.Set; -public abstract class StripeSourceTypeModel extends StripeJsonModel { +public abstract class StripeSourceTypeModel extends StripeModel { @NonNull private final Map mAdditionalFields; private static final String NULL = "null"; @@ -35,14 +35,6 @@ public Map toMap() { return new HashMap<>(mAdditionalFields); } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject jsonObject = new JSONObject(); - putAdditionalFieldsIntoJsonObject(jsonObject, mAdditionalFields); - return jsonObject; - } - /** * Convert a {@link JSONObject} to a flat, string-keyed map. * diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/AmexExpressCheckoutWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/AmexExpressCheckoutWallet.java index 35a562b8942..190aac2f66d 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/AmexExpressCheckoutWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/AmexExpressCheckoutWallet.java @@ -24,12 +24,6 @@ Map getWalletTypeMap() { return new HashMap<>(); } - @NonNull - @Override - JSONObject getWalletTypeJson() { - return new JSONObject(); - } - @NonNull static AmexExpressCheckoutWallet.Builder fromJson(@NonNull JSONObject walletJson) { return new Builder(); diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/ApplePayWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/ApplePayWallet.java index cdd808107f0..f4091847b18 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/ApplePayWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/ApplePayWallet.java @@ -24,12 +24,6 @@ Map getWalletTypeMap() { return new HashMap<>(); } - @NonNull - @Override - JSONObject getWalletTypeJson() { - return new JSONObject(); - } - @NonNull static ApplePayWallet.Builder fromJson(@NonNull JSONObject walletJson) { return new Builder(); diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/GooglePayWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/GooglePayWallet.java index 81d338c1c39..d2a666dd7e8 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/GooglePayWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/GooglePayWallet.java @@ -24,12 +24,6 @@ Map getWalletTypeMap() { return new HashMap<>(); } - @NonNull - @Override - JSONObject getWalletTypeJson() { - return new JSONObject(); - } - @NonNull static GooglePayWallet.Builder fromJson(@NonNull JSONObject walletJson) { return new Builder(); diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/MasterpassWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/MasterpassWallet.java index 9f5c07e8849..89f650ac7fb 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/MasterpassWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/MasterpassWallet.java @@ -7,7 +7,6 @@ import com.stripe.android.utils.ObjectUtils; -import org.json.JSONException; import org.json.JSONObject; import java.util.AbstractMap; @@ -48,22 +47,6 @@ Map getWalletTypeMap() { return wallet; } - @NonNull - @Override - JSONObject getWalletTypeJson() { - final JSONObject wallet = new JSONObject(); - try { - wallet.put(FIELD_BILLING_ADDRESS, - billingAddress != null ? billingAddress.toJson() : null); - wallet.put(FIELD_EMAIL, email); - wallet.put(FIELD_NAME, name); - wallet.put(FIELD_SHIPPING_ADDRESS, - shippingAddress != null ? shippingAddress.toJson() : null); - } catch (JSONException ignore) { - } - return wallet; - } - @NonNull static MasterpassWallet.Builder fromJson(@NonNull JSONObject wallet) { return new Builder() diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/SamsungPayWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/SamsungPayWallet.java index 792e54e620f..f13adcba675 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/SamsungPayWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/SamsungPayWallet.java @@ -24,12 +24,6 @@ Map getWalletTypeMap() { return new HashMap<>(); } - @NonNull - @Override - JSONObject getWalletTypeJson() { - return new JSONObject(); - } - @NonNull static SamsungPayWallet.Builder fromJson(@NonNull JSONObject walletJson) { return new Builder(); diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/VisaCheckoutWallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/VisaCheckoutWallet.java index cd2a1e8c3e4..59d0148aa86 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/VisaCheckoutWallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/VisaCheckoutWallet.java @@ -7,7 +7,6 @@ import com.stripe.android.utils.ObjectUtils; -import org.json.JSONException; import org.json.JSONObject; import java.util.AbstractMap; @@ -48,22 +47,6 @@ Map getWalletTypeMap() { return wallet; } - @NonNull - @Override - JSONObject getWalletTypeJson() { - final JSONObject wallet = new JSONObject(); - try { - wallet.put(FIELD_BILLING_ADDRESS, - billingAddress != null ? billingAddress.toJson() : null); - wallet.put(FIELD_EMAIL, email); - wallet.put(FIELD_NAME, name); - wallet.put(FIELD_SHIPPING_ADDRESS, - shippingAddress != null ? shippingAddress.toJson() : null); - } catch (JSONException ignore) { - } - return wallet; - } - @NonNull static VisaCheckoutWallet.Builder fromJson(@NonNull JSONObject wallet) { return new Builder() diff --git a/stripe/src/main/java/com/stripe/android/model/wallets/Wallet.java b/stripe/src/main/java/com/stripe/android/model/wallets/Wallet.java index 63ffb13a890..6b68ae8a94d 100644 --- a/stripe/src/main/java/com/stripe/android/model/wallets/Wallet.java +++ b/stripe/src/main/java/com/stripe/android/model/wallets/Wallet.java @@ -5,10 +5,9 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import com.stripe.android.model.StripeJsonModel; +import com.stripe.android.model.StripeModel; import com.stripe.android.utils.ObjectUtils; -import org.json.JSONException; import org.json.JSONObject; import java.util.AbstractMap; @@ -17,7 +16,7 @@ import static com.stripe.android.model.StripeJsonUtils.optString; -public abstract class Wallet extends StripeJsonModel implements Parcelable { +public abstract class Wallet extends StripeModel implements Parcelable { static final String FIELD_DYNAMIC_LAST4 = "dynamic_last4"; static final String FIELD_TYPE = "type"; @@ -55,19 +54,6 @@ public final Map toMap() { return wallet; } - @NonNull - @Override - public final JSONObject toJson() { - final JSONObject wallet = new JSONObject(); - try { - wallet.put(FIELD_TYPE, walletType.code); - wallet.put(FIELD_DYNAMIC_LAST4, dynamicLast4); - wallet.put(walletType.code, getWalletTypeJson()); - } catch (JSONException ignore) { - } - return wallet; - } - @Override public int hashCode() { return ObjectUtils.hash(dynamicLast4, walletType); @@ -86,9 +72,6 @@ private boolean typedEquals(@NonNull Wallet wallet) { @NonNull abstract Map getWalletTypeMap(); - @NonNull - abstract JSONObject getWalletTypeJson(); - abstract static class Builder { @Nullable private String mDynamicLast4; @@ -128,7 +111,7 @@ static Type fromCode(@Nullable String code) { } } - public static class Address extends StripeJsonModel implements Parcelable { + public static class Address extends StripeModel implements Parcelable { static final String FIELD_CITY = "city"; static final String FIELD_COUNTRY = "country"; static final String FIELD_LINE1 = "line1"; @@ -202,22 +185,6 @@ public Map toMap() { return address; } - @NonNull - @Override - public JSONObject toJson() { - final JSONObject address = new JSONObject(); - try { - address.put(FIELD_CITY, city); - address.put(FIELD_COUNTRY, country); - address.put(FIELD_LINE1, line1); - address.put(FIELD_LINE2, line2); - address.put(FIELD_POSTAL_CODE, postalCode); - address.put(FIELD_STATE, state); - } catch (JSONException ignore) { - } - return address; - } - @Nullable static Address fromJson(@Nullable JSONObject addressJson) { if (addressJson == null) { diff --git a/stripe/src/test/java/com/stripe/android/CustomerSessionTest.java b/stripe/src/test/java/com/stripe/android/CustomerSessionTest.java index 537a82eee59..2caf55e0dbf 100644 --- a/stripe/src/test/java/com/stripe/android/CustomerSessionTest.java +++ b/stripe/src/test/java/com/stripe/android/CustomerSessionTest.java @@ -29,6 +29,7 @@ import com.stripe.android.view.PaymentMethodsActivity; import org.json.JSONException; +import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -98,7 +99,7 @@ public class CustomerSessionTest extends BaseViewTest { " }]\n" + "}"; - public static final String FIRST_TEST_CUSTOMER_OBJECT = + static final String FIRST_TEST_CUSTOMER_OBJECT = "{\n" + " \"id\": \"cus_AQsHpvKfKwJDrF\",\n" + " \"object\": \"customer\",\n" + @@ -200,7 +201,7 @@ public void tearDown() { @NonNull private CustomerEphemeralKey getCustomerEphemeralKey(@NonNull String key) { try { - return CustomerEphemeralKey.fromString(key); + return CustomerEphemeralKey.fromJson(new JSONObject(key)); } catch (JSONException e) { throw new RuntimeException(e); } diff --git a/stripe/src/test/java/com/stripe/android/EphemeralKeyManagerTest.java b/stripe/src/test/java/com/stripe/android/EphemeralKeyManagerTest.java index 459fb479a06..8888e473ad7 100644 --- a/stripe/src/test/java/com/stripe/android/EphemeralKeyManagerTest.java +++ b/stripe/src/test/java/com/stripe/android/EphemeralKeyManagerTest.java @@ -5,6 +5,7 @@ import com.stripe.android.testharness.TestEphemeralKeyProvider; import org.json.JSONException; +import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -67,7 +68,7 @@ public class EphemeralKeyManagerTest { @Before public void setup() throws JSONException { MockitoAnnotations.initMocks(this); - mCustomerEphemeralKey = CustomerEphemeralKey.fromString(FIRST_SAMPLE_KEY_RAW); + mCustomerEphemeralKey = CustomerEphemeralKey.fromJson(new JSONObject(FIRST_SAMPLE_KEY_RAW)); mTestEphemeralKeyProvider = new TestEphemeralKeyProvider(); } @@ -147,7 +148,7 @@ public void createKeyManager_updatesEphemeralKey_notifiesListener() { TEST_SECONDS_BUFFER, null, mOperationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); verify(mKeyManagerListener).onKeyUpdate( ArgumentMatchers.any(), @@ -169,7 +170,7 @@ public void retrieveEphemeralKey_whenUpdateNecessary_returnsUpdateAndArguments() TEST_SECONDS_BUFFER, fixedCalendar, mOperationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); final String operationId = mOperationIdFactory.create(); final String actionString = "action"; @@ -214,7 +215,7 @@ public void updateKeyIfNecessary_whenReturnsError_setsExistingKeyToNull() { TEST_SECONDS_BUFFER, proxyCalendar, mOperationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); // Make sure we're in a good state verify(mKeyManagerListener).onKeyUpdate( @@ -250,7 +251,7 @@ public void triggerCorrectErrorOnInvalidRawKey() { TEST_SECONDS_BUFFER, null, operationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); verify(mKeyManagerListener, never()).onKeyUpdate( ArgumentMatchers.isNull(), @@ -279,7 +280,7 @@ public void triggerCorrectErrorOnInvalidJsonKey() { TEST_SECONDS_BUFFER, null, operationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); verify(mKeyManagerListener, never()).onKeyUpdate( ArgumentMatchers.isNull(), @@ -288,10 +289,9 @@ public void triggerCorrectErrorOnInvalidJsonKey() { ArgumentMatchers.>isNull()); verify(mKeyManagerListener).onKeyError(operationId, HttpURLConnection.HTTP_INTERNAL_ERROR, - "EphemeralKeyUpdateListener.onKeyUpdate was passed a JSON String " + - "that was invalid: [Improperly formatted JSON for ephemeral " + - "key CustomerEphemeralKey - No value for created]. The raw body " + - "from Stripe's response should be passed"); + "EphemeralKeyUpdateListener.onKeyUpdate was passed a value that " + + "could not be JSON parsed: [No value for associated_objects]. The raw " + + "body from Stripe's response should be passed"); assertNull(keyManager.getEphemeralKey()); } @@ -308,7 +308,7 @@ public void triggerCorrectErrorOnNullKey() { TEST_SECONDS_BUFFER, null, operationIdFactory, - CustomerEphemeralKey.class); + new CustomerEphemeralKey.BuilderFactory()); verify(mKeyManagerListener, never()).onKeyUpdate( ArgumentMatchers.isNull(), @@ -323,7 +323,15 @@ public void triggerCorrectErrorOnNullKey() { @NonNull private CustomerEphemeralKey createEphemeralKey(long expires) { - return new CustomerEphemeralKey(1501199335L, "cus_AQsHpvKfKwJDrF", - expires, "ephkey_123", false, "customer", "", ""); + return new CustomerEphemeralKey.Builder() + .setObject("ephemeral_key") + .setCreated(1501199335L) + .setObjectId("cus_AQsHpvKfKwJDrF") + .setExpires(expires) + .setId("ephkey_123") + .setLiveMode(false) + .setType("customer") + .setSecret("ek_test_123") + .build(); } } diff --git a/stripe/src/test/java/com/stripe/android/EphemeralKeyTest.java b/stripe/src/test/java/com/stripe/android/EphemeralKeyTest.java index 8c403d3d300..a446ecca985 100644 --- a/stripe/src/test/java/com/stripe/android/EphemeralKeyTest.java +++ b/stripe/src/test/java/com/stripe/android/EphemeralKeyTest.java @@ -19,12 +19,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; @RunWith(RobolectricTestRunner.class) public class EphemeralKeyTest { - private static final String SAMPLE_KEY_RAW = "{\n" + + private static final String KEY_JSON = "{\n" + " \"id\": \"ephkey_123\",\n" + " \"object\": \"ephemeral_key\",\n" + " \"secret\": \"ek_test_123\",\n" + @@ -40,17 +39,13 @@ public class EphemeralKeyTest { "}"; @NonNull - private CustomerEphemeralKey getCustomerEphemeralKey(@NonNull String key) { - try { - return CustomerEphemeralKey.fromString(key); - } catch (JSONException e) { - throw new RuntimeException(e); - } + private CustomerEphemeralKey getCustomerEphemeralKey() throws JSONException { + return CustomerEphemeralKey.fromJson(new JSONObject(KEY_JSON)); } @Test - public void fromJson_createsKeyWithExpectedValues() { - CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(SAMPLE_KEY_RAW); + public void fromJson_createsKeyWithExpectedValues() throws JSONException { + CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(); assertNotNull(ephemeralKey); assertEquals("ephkey_123", ephemeralKey.getId()); assertEquals("ephemeral_key", ephemeralKey.getObject()); @@ -63,20 +58,13 @@ public void fromJson_createsKeyWithExpectedValues() { } @Test - public void fromJson_toJson_createsEqualObject() { - try { - JSONObject originalObject = new JSONObject(SAMPLE_KEY_RAW); - CustomerEphemeralKey key = CustomerEphemeralKey.fromJson(originalObject); - assertNotNull(key); - JsonTestUtils.assertJsonEquals(originalObject, key.toJson()); - } catch (JSONException unexpected) { - fail("Failure to parse test JSON"); - } + public void fromJson_createsNotNullObject() throws JSONException { + assertNotNull(CustomerEphemeralKey.fromJson(new JSONObject(KEY_JSON))); } @Test - public void toMap_createsMapWithExpectedValues() { - CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(SAMPLE_KEY_RAW); + public void toMap_createsMapWithExpectedValues() throws JSONException { + CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(); assertNotNull(ephemeralKey); Map expectedMap = new HashMap() {{ put(CustomerEphemeralKey.FIELD_ID, "ephkey_123"); @@ -98,8 +86,8 @@ public void toMap_createsMapWithExpectedValues() { } @Test - public void toParcel_fromParcel_createsExpectedObject() { - CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(SAMPLE_KEY_RAW); + public void toParcel_fromParcel_createsExpectedObject() throws JSONException { + CustomerEphemeralKey ephemeralKey = getCustomerEphemeralKey(); assertNotNull(ephemeralKey); Parcel parcel = Parcel.obtain(); ephemeralKey.writeToParcel(parcel, 0); diff --git a/stripe/src/test/java/com/stripe/android/IssuingCardPinServiceTest.java b/stripe/src/test/java/com/stripe/android/IssuingCardPinServiceTest.java index 9fe82783ac2..cbdd1c60a1a 100644 --- a/stripe/src/test/java/com/stripe/android/IssuingCardPinServiceTest.java +++ b/stripe/src/test/java/com/stripe/android/IssuingCardPinServiceTest.java @@ -25,16 +25,16 @@ public class IssuingCardPinServiceTest { private static final String EPHEMERAL_KEY = "{\n" + - " \"id\": \"ephkey_123\",\n" + - " \"object\": \"ephemeral_key\",\n" + - " \"secret\": \"ek_test_123\",\n" + - " \"created\": 1501179335,\n" + - " \"livemode\": false,\n" + - " \"expires\": 1501199335,\n" + - " \"associated_objects\": [{\n" + - " \"type\": \"issuing.card\",\n" + - " \"id\": \"ic_abcd\"\n" + - " }]\n" + + "\t\"id\": \"ephkey_123\",\n" + + "\t\"object\": \"ephemeral_key\",\n" + + "\t\"secret\": \"ek_test_123\",\n" + + "\t\"created\": 1501179335,\n" + + "\t\"livemode\": false,\n" + + "\t\"expires\": 1501199335,\n" + + "\t\"associated_objects\": [{\n" + + "\t\t\"type\": \"issuing.card\",\n" + + "\t\t\"id\": \"ic_abcd\"\n" + + "\t}]\n" + "}"; @Mock private RequestExecutor mRequestExecutor; diff --git a/stripe/src/test/java/com/stripe/android/model/AddressTest.java b/stripe/src/test/java/com/stripe/android/model/AddressTest.java index f12430bd2c4..65bf4a6efdc 100644 --- a/stripe/src/test/java/com/stripe/android/model/AddressTest.java +++ b/stripe/src/test/java/com/stripe/android/model/AddressTest.java @@ -1,13 +1,10 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -37,13 +34,6 @@ public class AddressTest { private static final Address ADDRESS = Address.fromString(JSON_ADDRESS); - @Test - public void fromJsonString_backToJson_createsIdenticalElement() throws JSONException { - assertNotNull(ADDRESS); - JSONObject rawConversion = new JSONObject(JSON_ADDRESS); - assertJsonEquals(rawConversion, ADDRESS.toJson()); - } - @Test public void fromJsonString_toMap_createsExpectedMap() { assertNotNull(ADDRESS); diff --git a/stripe/src/test/java/com/stripe/android/model/CardTest.java b/stripe/src/test/java/com/stripe/android/model/CardTest.java index 0e4b11dad4f..fe721b37403 100644 --- a/stripe/src/test/java/com/stripe/android/model/CardTest.java +++ b/stripe/src/test/java/com/stripe/android/model/CardTest.java @@ -17,7 +17,6 @@ import static com.stripe.android.model.Card.asFundingType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -85,11 +84,11 @@ public class CardTest { " }"; private static final String BAD_JSON = "{ \"id\": "; - private Calendar calendar; + + private final Calendar calendar = Calendar.getInstance(); @Before public void setup() { - calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, 1997); calendar.set(Calendar.MONTH, Calendar.AUGUST); calendar.set(Calendar.DAY_OF_MONTH, 29); @@ -665,20 +664,6 @@ public void fromString_whenStringIsValidJson_returnsExpectedCard() { assertEquals(expectedCard, actualCard); } - @Test - public void fromString_toJson_yieldsSameObject() { - Card cardFromJson = Card.fromString(JSON_CARD_USD); - assertNotNull(cardFromJson); - - JSONObject cycledCardObject = cardFromJson.toJson(); - try { - JSONObject rawJsonObject = new JSONObject(JSON_CARD_USD); - JsonTestUtils.assertJsonEquals(cycledCardObject, rawJsonObject); - } catch (JSONException unexpected) { - fail(); - } - } - @Test public void toMap_catchesAllFields_fromRawJson() { try { diff --git a/stripe/src/test/java/com/stripe/android/model/CustomerSourceTest.java b/stripe/src/test/java/com/stripe/android/model/CustomerSourceTest.java index 8e7f3f187da..1503b87033b 100644 --- a/stripe/src/test/java/com/stripe/android/model/CustomerSourceTest.java +++ b/stripe/src/test/java/com/stripe/android/model/CustomerSourceTest.java @@ -1,7 +1,5 @@ package com.stripe.android.model; -import com.stripe.android.testharness.JsonTestUtils; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -12,7 +10,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * Test class for {@link CustomerSource} model class. @@ -45,36 +42,29 @@ public class CustomerSourceTest { " }"; @Test - public void fromJson_whenCard_createsCustomerSourceData() { - try { - JSONObject jsonCard = new JSONObject(JSON_CARD_USD); - CustomerSource sourceData = CustomerSource.fromJson(jsonCard); - assertNotNull(sourceData); - assertNotNull(sourceData.asCard()); - assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.getId()); - assertNull(sourceData.getTokenizationMethod()); - } catch (JSONException jsonException) { - fail("Test data failure: " + jsonException.getMessage()); - } + public void fromJson_whenCard_createsCustomerSourceData() throws JSONException { + final JSONObject jsonCard = new JSONObject(JSON_CARD_USD); + final CustomerSource sourceData = CustomerSource.fromJson(jsonCard); + assertNotNull(sourceData); + assertNotNull(sourceData.asCard()); + assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.getId()); + assertNull(sourceData.getTokenizationMethod()); } @Test - public void fromJson_whenCardWithTokenization_createsSourceDataWithTokenization() { - try { - JSONObject jsonCard = new JSONObject(JSON_APPLE_PAY_CARD); - CustomerSource sourceData = CustomerSource.fromJson(jsonCard); - assertNotNull(sourceData); - assertNotNull(sourceData.asCard()); - assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.getId()); - assertEquals("apple_pay", sourceData.getTokenizationMethod()); - } catch (JSONException jsonException) { - fail("Test data failure: " + jsonException.getMessage()); - } + public void fromJson_whenCardWithTokenization_createsSourceDataWithTokenization() + throws JSONException { + final JSONObject jsonCard = new JSONObject(JSON_APPLE_PAY_CARD); + final CustomerSource sourceData = CustomerSource.fromJson(jsonCard); + assertNotNull(sourceData); + assertNotNull(sourceData.asCard()); + assertEquals("card_189fi32eZvKYlo2CHK8NPRME", sourceData.getId()); + assertEquals("apple_pay", sourceData.getTokenizationMethod()); } @Test public void fromJson_whenSource_createsCustomerSourceData() { - CustomerSource sourceData = + final CustomerSource sourceData = CustomerSource.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); assertNotNull(sourceData); assertNotNull(sourceData.asSource()); @@ -82,32 +72,20 @@ public void fromJson_whenSource_createsCustomerSourceData() { } @Test - public void fromExampleJsonSource_toJson_createsSameObject() { - try { - JSONObject original = new JSONObject(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); - CustomerSource sourceData = CustomerSource.fromJson(original); - assertNotNull(sourceData); - JsonTestUtils.assertJsonEquals(original, sourceData.toJson()); - } catch (JSONException exception) { - fail("Test data failure: " + exception.getMessage()); - } + public void fromExampleJsonSource_createsSameObject() throws JSONException { + assertNotNull(CustomerSource.fromJson(new JSONObject(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS))); } @Test - public void getSourceType_whenCard_returnsCard() { - try { - JSONObject jsonCard = new JSONObject(JSON_CARD_USD); - CustomerSource sourceData = CustomerSource.fromJson(jsonCard); - assertNotNull(sourceData); - assertEquals(Source.CARD, sourceData.getSourceType()); - } catch (JSONException jsonException) { - fail("Test data failure: " + jsonException.getMessage()); - } + public void getSourceType_whenCard_returnsCard() throws JSONException { + final CustomerSource sourceData = CustomerSource.fromJson(new JSONObject(JSON_CARD_USD)); + assertNotNull(sourceData); + assertEquals(Source.CARD, sourceData.getSourceType()); } @Test public void getSourceType_whenSourceThatIsNotCard_returnsSourceType() { - CustomerSource alipaySource = CustomerSource.fromString(EXAMPLE_ALIPAY_SOURCE); + final CustomerSource alipaySource = CustomerSource.fromString(EXAMPLE_ALIPAY_SOURCE); assertNotNull(alipaySource); assertEquals(Source.ALIPAY, alipaySource.getSourceType()); } diff --git a/stripe/src/test/java/com/stripe/android/model/CustomerTest.java b/stripe/src/test/java/com/stripe/android/model/CustomerTest.java index 9fa31e5274e..290c43b2e14 100644 --- a/stripe/src/test/java/com/stripe/android/model/CustomerTest.java +++ b/stripe/src/test/java/com/stripe/android/model/CustomerTest.java @@ -2,8 +2,6 @@ import android.support.annotation.NonNull; -import com.stripe.android.testharness.JsonTestUtils; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -14,11 +12,9 @@ import static com.stripe.android.model.SourceTest.EXAMPLE_ALIPAY_SOURCE; import static com.stripe.android.model.SourceTest.EXAMPLE_JSON_SOURCE_WITHOUT_NULLS; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Test class for {@link Customer} model object. @@ -61,20 +57,21 @@ public void fromJson_whenNotACustomer_returnsNull() { @Test public void fromJson_whenCustomer_returnsExpectedCustomer() { - Customer customer = Customer.fromString(TEST_CUSTOMER_OBJECT); + final Customer customer = Customer.fromString(TEST_CUSTOMER_OBJECT); assertNotNull(customer); assertEquals("cus_AQsHpvKfKwJDrF", customer.getId()); assertEquals("abc123", customer.getDefaultSource()); assertNull(customer.getShippingInformation()); assertNotNull(customer.getSources()); assertEquals("/v1/customers/cus_AQsHpvKfKwJDrF/sources", customer.getUrl()); - assertFalse(customer.getHasMore()); + assertEquals(Boolean.FALSE, customer.getHasMore()); assertEquals(Integer.valueOf(0), customer.getTotalCount()); } @Test - public void fromJson_whenCustomerHasApplePay_returnsCustomerWithoutApplePaySources() { - Customer customer = Customer.fromString(createTestCustomerObjectWithApplePaySource()); + public void fromJson_whenCustomerHasApplePay_returnsCustomerWithoutApplePaySources() + throws JSONException { + final Customer customer = Customer.fromString(createTestCustomerObjectWithApplePaySource()); assertNotNull(customer); assertEquals(2, customer.getSources().size()); // Note that filtering the apple_pay sources intentionally does not change the total @@ -83,63 +80,52 @@ public void fromJson_whenCustomerHasApplePay_returnsCustomerWithoutApplePaySourc } @Test - public void fromJson_toJson_createsSameObject() { - try { - JSONObject rawJsonCustomer = new JSONObject(TEST_CUSTOMER_OBJECT); - Customer customer = Customer.fromString(TEST_CUSTOMER_OBJECT); - assertNotNull(customer); - JsonTestUtils.assertJsonEquals(rawJsonCustomer, customer.toJson()); - assertEquals(Customer.fromString(TEST_CUSTOMER_OBJECT), - Customer.fromString(TEST_CUSTOMER_OBJECT)); - } catch (JSONException testDataException) { - fail("Test data failure: " + testDataException.getMessage()); - } + public void fromJson_createsSameObject() { + Customer customer = Customer.fromString(TEST_CUSTOMER_OBJECT); + assertNotNull(customer); + assertEquals(Customer.fromString(TEST_CUSTOMER_OBJECT), + Customer.fromString(TEST_CUSTOMER_OBJECT)); } @NonNull - private String createTestCustomerObjectWithApplePaySource() { - try { - JSONObject rawJsonCustomer = new JSONObject(TEST_CUSTOMER_OBJECT); - JSONObject sourcesObject = rawJsonCustomer.getJSONObject("sources"); - JSONArray sourcesArray = sourcesObject.getJSONArray("data"); - - sourcesObject.put("total_count", 5); - CustomerSource applePayCard = CustomerSource.fromString(JSON_APPLE_PAY_CARD); - assertNotNull(applePayCard); - sourcesArray.put(applePayCard.toJson()); - - Card testCard = Card.fromString(JSON_CARD_USD); - assertNotNull(testCard); - - JSONObject manipulatedCard = new JSONObject(JSON_CARD_USD); - manipulatedCard.put("id", "card_id55555"); - manipulatedCard.put("tokenization_method", "apple_pay"); - Card manipulatedApplePayCard = Card.fromJson(manipulatedCard); - assertNotNull(manipulatedApplePayCard); - - Source sourceCardWithApplePay = Source.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); - // Note that we don't yet explicitly support bitcoin sources, but this data is - // convenient for the test because it is not an apple pay source. - Source alipaySource = Source.fromString(EXAMPLE_ALIPAY_SOURCE); - assertNotNull(sourceCardWithApplePay); - assertNotNull(alipaySource); - sourcesArray.put(sourceCardWithApplePay.toJson()); - sourcesArray.put(alipaySource.toJson()); - - sourcesArray.put(testCard.toJson()); - sourcesArray.put(manipulatedApplePayCard.toJson()); - sourcesObject.put("data", sourcesArray); - - rawJsonCustomer.put("sources", sourcesObject); - - // Verify JSON manipulation - assertTrue(rawJsonCustomer.has("sources")); - assertTrue(rawJsonCustomer.getJSONObject("sources").has("data")); - assertEquals(5, rawJsonCustomer.getJSONObject("sources").getJSONArray("data").length()); - return rawJsonCustomer.toString(); - } catch (JSONException testDataException) { - fail("Test data failure: " + testDataException.getMessage()); - return null; - } + private String createTestCustomerObjectWithApplePaySource() throws JSONException { + final JSONObject rawJsonCustomer = new JSONObject(TEST_CUSTOMER_OBJECT); + final JSONObject sourcesObject = rawJsonCustomer.getJSONObject("sources"); + final JSONArray sourcesArray = sourcesObject.getJSONArray("data"); + + sourcesObject.put("total_count", 5); + final CustomerSource applePayCard = CustomerSource.fromString(JSON_APPLE_PAY_CARD); + assertNotNull(applePayCard); + sourcesArray.put(new JSONObject(applePayCard.toMap())); + + final Card testCard = Card.fromString(JSON_CARD_USD); + assertNotNull(testCard); + + final JSONObject manipulatedCard = new JSONObject(JSON_CARD_USD); + manipulatedCard.put("id", "card_id55555"); + manipulatedCard.put("tokenization_method", "apple_pay"); + final Card manipulatedApplePayCard = Card.fromJson(manipulatedCard); + assertNotNull(manipulatedApplePayCard); + + Source sourceCardWithApplePay = Source.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); + // Note that we don't yet explicitly support bitcoin sources, but this data is + // convenient for the test because it is not an apple pay source. + final Source alipaySource = Source.fromString(EXAMPLE_ALIPAY_SOURCE); + assertNotNull(sourceCardWithApplePay); + assertNotNull(alipaySource); + sourcesArray.put(new JSONObject(sourceCardWithApplePay.toMap())); + sourcesArray.put(new JSONObject(alipaySource.toMap())); + sourcesArray.put(new JSONObject(testCard.toMap())); + sourcesArray.put(new JSONObject(manipulatedApplePayCard.toMap())); + sourcesObject.put("data", sourcesArray); + + rawJsonCustomer.put("sources", sourcesObject); + + // Verify JSON manipulation + assertTrue(rawJsonCustomer.has("sources")); + assertTrue(rawJsonCustomer.getJSONObject("sources").has("data")); + assertEquals(5, + rawJsonCustomer.getJSONObject("sources").getJSONArray("data").length()); + return rawJsonCustomer.toString(); } } diff --git a/stripe/src/test/java/com/stripe/android/model/PaymentIntentTest.java b/stripe/src/test/java/com/stripe/android/model/PaymentIntentTest.java index 62d25752fa1..f8f1ff40a34 100644 --- a/stripe/src/test/java/com/stripe/android/model/PaymentIntentTest.java +++ b/stripe/src/test/java/com/stripe/android/model/PaymentIntentTest.java @@ -1,9 +1,8 @@ package com.stripe.android.model; import android.net.Uri; +import android.support.annotation.NonNull; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @@ -12,8 +11,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEqualsExcludingNulls; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -180,16 +179,8 @@ public class PaymentIntentTest { put(PaymentIntent.FIELD_STATUS, PaymentIntent.Status.Succeeded.code); }}; - private static final PaymentIntent PAYMENT_INTENT_WITH_SOURCE = PaymentIntent - .fromString(PAYMENT_INTENT_WITH_SOURCE_JSON); - - @Test - public void fromJsonString_backToJson_createsIdenticalElement() throws JSONException { - assertNotNull(PAYMENT_INTENT_WITH_SOURCE); - JSONObject rawConversion = new JSONObject(PAYMENT_INTENT_WITH_SOURCE_JSON); - JSONObject actualObject = PAYMENT_INTENT_WITH_SOURCE.toJson(); - assertJsonEqualsExcludingNulls(rawConversion, actualObject); - } + @NonNull private static final PaymentIntent PAYMENT_INTENT_WITH_SOURCE = + Objects.requireNonNull(PaymentIntent.fromString(PAYMENT_INTENT_WITH_SOURCE_JSON)); @Test public void fromJsonString_toMap_createsExpectedMap() { diff --git a/stripe/src/test/java/com/stripe/android/model/PaymentMethodTest.java b/stripe/src/test/java/com/stripe/android/model/PaymentMethodTest.java index 459c0d647d6..b6d1ad1ebca 100644 --- a/stripe/src/test/java/com/stripe/android/model/PaymentMethodTest.java +++ b/stripe/src/test/java/com/stripe/android/model/PaymentMethodTest.java @@ -2,8 +2,6 @@ import android.os.Parcel; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @@ -13,6 +11,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) @@ -129,32 +128,6 @@ public class PaymentMethodTest { .build(); } - @Test - public void toJson_withIdeal_shouldReturnExpectedJson() throws JSONException { - final JSONObject paymentMethod = new PaymentMethod.Builder() - .setId("pm_123456789") - .setCreated(1550757934255L) - .setLiveMode(true) - .setType("ideal") - .setCustomerId("cus_AQsHpvKfKwJDrF") - .setBillingDetails(BILLING_DETAILS) - .setIdeal(new PaymentMethod.Ideal.Builder() - .setBank("my bank") - .setBankIdentifierCode("bank id") - .build()) - .build() - .toJson(); - - assertEquals(new JSONObject(RAW_IDEAL_JSON).toString(), paymentMethod.toString()); - } - - @Test - public void toJson_withCard_shouldReturnExpectedJson() throws JSONException { - assertEquals(new JSONObject(RAW_CARD_JSON).toString(), - CARD_PAYMENT_METHOD.toJson().toString()); - } - - @Test public void equals_withEqualPaymentMethods_shouldReturnTrue() { assertEquals(CARD_PAYMENT_METHOD, new PaymentMethod.Builder() @@ -173,6 +146,13 @@ public void fromString_shouldReturnExpectedPaymentMethod() { assertEquals(CARD_PAYMENT_METHOD, PaymentMethod.fromString(RAW_CARD_JSON)); } + @Test + public void fromString_withIdeal_returnsExpectedObject() { + final PaymentMethod paymentMethod = PaymentMethod.fromString(RAW_IDEAL_JSON); + assertNotNull(paymentMethod); + assertEquals("ideal", paymentMethod.type); + } + @Test public void billingDetailsToMap_removesNullValues() { final Map billingDetails = diff --git a/stripe/src/test/java/com/stripe/android/model/ShippingMethodTest.java b/stripe/src/test/java/com/stripe/android/model/ShippingMethodTest.java index 9e4c04d5747..56c6f097646 100644 --- a/stripe/src/test/java/com/stripe/android/model/ShippingMethodTest.java +++ b/stripe/src/test/java/com/stripe/android/model/ShippingMethodTest.java @@ -2,51 +2,30 @@ import android.support.annotation.NonNull; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * Test class for {@link ShippingMethod} */ public class ShippingMethodTest { - private static final String EXAMPLE_JSON_SHIPPING_ADDRESS = "{" + - "\"amount\": 599," + - "\"currency_code\": \"USD\",\n" + - "\"detail\": \"Arrives tomorrow\"," + - "\"identifier\": \"fedex\"," + - "\"label\": \"FedEx\"" + - "}"; - - private static final Map EXAMPLE_MAP_SHIPPING_ADDRESS= new HashMap() {{ - put("amount", 599L); - put("currency_code", "USD"); - put("detail", "Arrives tomorrow"); - put("identifier", "fedex"); - put("label", "FedEx"); - }}; + private static final Map EXAMPLE_MAP_SHIPPING_ADDRESS = + new HashMap() {{ + put("amount", 599L); + put("currency_code", "USD"); + put("detail", "Arrives tomorrow"); + put("identifier", "fedex"); + put("label", "FedEx"); + }}; private final static ShippingMethod SHIPPING_METHOD = createShippingMethod(); - @Test - public void testJSONConversion() { - try { - JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_SHIPPING_ADDRESS); - assertJsonEquals(SHIPPING_METHOD.toJson(), rawConversion); - } catch (JSONException jsonException) { - fail("Test Data failure: " + jsonException.getLocalizedMessage()); - } - } - @Test public void testMapCreation() { assertMapEquals(SHIPPING_METHOD.toMap(), EXAMPLE_MAP_SHIPPING_ADDRESS); diff --git a/stripe/src/test/java/com/stripe/android/model/SourceCodeVerificationTest.java b/stripe/src/test/java/com/stripe/android/model/SourceCodeVerificationTest.java index 00e5546a23a..3a925fdf871 100644 --- a/stripe/src/test/java/com/stripe/android/model/SourceCodeVerificationTest.java +++ b/stripe/src/test/java/com/stripe/android/model/SourceCodeVerificationTest.java @@ -1,17 +1,12 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * Test class for {@link SourceCodeVerification}. @@ -29,26 +24,11 @@ public class SourceCodeVerificationTest { put("status", "pending"); }}; - private SourceCodeVerification mCodeVerification; - - @Before - public void setup() { - mCodeVerification = SourceCodeVerification.fromString(EXAMPLE_JSON_CODE_VERIFICATION); - assertNotNull(mCodeVerification); - } - - @Test - public void fromJsonString_backToJson_createsIdenticalElement() { - try { - JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_CODE_VERIFICATION); - assertJsonEquals(rawConversion, mCodeVerification.toJson()); - } catch (JSONException jsonException) { - fail("Test Data failure: " + jsonException.getLocalizedMessage()); - } - } - @Test public void fromJsonString_toMap_createsExpectedMap() { - assertMapEquals(EXAMPLE_MAP_CODE_VERIFICATION, mCodeVerification.toMap()); + final SourceCodeVerification codeVerification = + SourceCodeVerification.fromString(EXAMPLE_JSON_CODE_VERIFICATION); + assertNotNull(codeVerification); + assertMapEquals(EXAMPLE_MAP_CODE_VERIFICATION, codeVerification.toMap()); } } diff --git a/stripe/src/test/java/com/stripe/android/model/SourceOwnerTest.java b/stripe/src/test/java/com/stripe/android/model/SourceOwnerTest.java index 7a14493f8e7..2926cdeb98f 100644 --- a/stripe/src/test/java/com/stripe/android/model/SourceOwnerTest.java +++ b/stripe/src/test/java/com/stripe/android/model/SourceOwnerTest.java @@ -1,18 +1,13 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static com.stripe.android.model.AddressTest.JSON_ADDRESS; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * Test class for {@link SourceOwner} model. @@ -47,22 +42,9 @@ public class SourceOwnerTest { put("phone", "4158675309"); }}; - private SourceOwner mSourceOwner; - - @Before - public void setup() { - mSourceOwner = SourceOwner.fromString(EXAMPLE_JSON_OWNER_WITHOUT_NULLS); - assertNotNull(mSourceOwner); - } - @Test - public void fromJsonStringWithoutNulls_backToJson_createsIdenticalElement() { - try { - JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_OWNER_WITHOUT_NULLS); - assertJsonEquals(rawConversion, mSourceOwner.toJson()); - } catch (JSONException jsonException) { - fail("Test Data failure: " + jsonException.getLocalizedMessage()); - } + public void fromJsonStringWithoutNulls_isNotNull() { + assertNotNull(SourceOwner.fromString(EXAMPLE_JSON_OWNER_WITHOUT_NULLS)); } @Test diff --git a/stripe/src/test/java/com/stripe/android/model/SourceReceiverTest.java b/stripe/src/test/java/com/stripe/android/model/SourceReceiverTest.java index 3c55170646e..b4a9c1caa95 100644 --- a/stripe/src/test/java/com/stripe/android/model/SourceReceiverTest.java +++ b/stripe/src/test/java/com/stripe/android/model/SourceReceiverTest.java @@ -1,17 +1,13 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; /** * Test class for {@link SourceReceiver}. @@ -41,16 +37,6 @@ public void setup() { assertNotNull(mSourceReceiver); } - @Test - public void fromJsonString_backToJson_createsIdenticalElement() { - try { - JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_RECEIVER); - assertJsonEquals(rawConversion, mSourceReceiver.toJson()); - } catch (JSONException jsonException) { - fail("Test Data failure: " + jsonException.getLocalizedMessage()); - } - } - @Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_RECEIVER, mSourceReceiver.toMap()); diff --git a/stripe/src/test/java/com/stripe/android/model/SourceRedirectTest.java b/stripe/src/test/java/com/stripe/android/model/SourceRedirectTest.java index 795ffabd77d..151513e05dc 100644 --- a/stripe/src/test/java/com/stripe/android/model/SourceRedirectTest.java +++ b/stripe/src/test/java/com/stripe/android/model/SourceRedirectTest.java @@ -1,14 +1,11 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -37,11 +34,6 @@ public void setup() { assertNotNull(mSourceRedirect); } - @Test - public void fromJsonString_backToJson_createsIdenticalElement() throws JSONException { - assertJsonEquals(new JSONObject(EXAMPLE_JSON_REDIRECT), mSourceRedirect.toJson()); - } - @Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_REDIRECT, mSourceRedirect.toMap()); diff --git a/stripe/src/test/java/com/stripe/android/model/SourceTest.java b/stripe/src/test/java/com/stripe/android/model/SourceTest.java index fcf70071c1a..bc0dcfcdc9d 100644 --- a/stripe/src/test/java/com/stripe/android/model/SourceTest.java +++ b/stripe/src/test/java/com/stripe/android/model/SourceTest.java @@ -1,8 +1,5 @@ package com.stripe.android.model; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Before; import org.junit.Test; import java.util.HashMap; @@ -14,13 +11,11 @@ import static com.stripe.android.model.SourceOwnerTest.EXAMPLE_MAP_OWNER; import static com.stripe.android.model.SourceReceiverTest.EXAMPLE_MAP_RECEIVER; import static com.stripe.android.model.SourceRedirectTest.EXAMPLE_JSON_REDIRECT; -import static com.stripe.android.testharness.JsonTestUtils.assertJsonEquals; import static com.stripe.android.testharness.JsonTestUtils.assertMapEquals; 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.fail; /** * Test class for {@link Source} model. @@ -124,6 +119,7 @@ public class SourceTest { private static final Map EXAMPLE_SOURCE_MAP = new HashMap() {{ put("id", "src_19t3xKBZqEXluyI4uz2dxAfQ"); + put("object", "source"); put("amount", 1000L); put("client_secret", "src_client_secret_of43INi1HteJwXVe3djAUosN"); put("created", 1488499654L); @@ -203,24 +199,9 @@ public class SourceTest { " \"tokenization_method\": null\n" + "}\n"; - private Source mSource; - - @Before - public void setup() { - mSource = Source.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); - assertNotNull(mSource); - } - @Test - public void fromJsonString_backToJson_createsIdenticalElement() { - try { - JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS); - JSONObject actualObject = mSource.toJson(); - assertJsonEquals(rawConversion, actualObject); - assertEquals(mSource, Source.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS)); - } catch (JSONException jsonException) { - fail("Test Data failure: " + jsonException.getLocalizedMessage()); - } + public void fromJsonStringWithoutNulls_isNotNull() { + assertNotNull(Source.fromString(EXAMPLE_JSON_SOURCE_WITHOUT_NULLS)); } @Test diff --git a/stripe/src/test/java/com/stripe/android/model/StripeJsonModelTest.java b/stripe/src/test/java/com/stripe/android/model/StripeJsonModelTest.java deleted file mode 100644 index 5c2f81b3982..00000000000 --- a/stripe/src/test/java/com/stripe/android/model/StripeJsonModelTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.stripe.android.model; - -import android.support.annotation.NonNull; - -import com.stripe.android.testharness.JsonTestUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * Test class for {@link StripeJsonModel}. - */ -public class StripeJsonModelTest { - - @Test - public void equals_whenEquals_returnsTrue() { - assertTrue(StripeJsonModel.class.isAssignableFrom(Card.class)); - - Card firstCard = Card.fromString(CardTest.JSON_CARD_USD); - Card secondCard = Card.fromString(CardTest.JSON_CARD_USD); - - assertEquals(firstCard, secondCard); - // Just confirming for sanity - assertNotSame(firstCard, secondCard); - } - - @Test - public void equals_whenNotEquals_returnsFalse() { - assertTrue(StripeJsonModel.class.isAssignableFrom(Card.class)); - final Card firstCard = Card.create("4242", null, null, null); - final Card secondCard = Card.create("4343", null, null, null); - assertNotEquals(firstCard, secondCard); - } - - @Test - public void hashCode_whenEquals_returnsSameValue() { - assertTrue(StripeJsonModel.class.isAssignableFrom(Card.class)); - - Card firstCard = Card.fromString(CardTest.JSON_CARD_USD); - Card secondCard = Card.fromString(CardTest.JSON_CARD_USD); - assertNotNull(firstCard); - assertNotNull(secondCard); - - assertEquals(firstCard.hashCode(), secondCard.hashCode()); - } - - @Test - public void hashCode_whenNotEquals_returnsDifferentValues() { - assertTrue(StripeJsonModel.class.isAssignableFrom(Card.class)); - - Card usdCard = Card.fromString(CardTest.JSON_CARD_USD); - Card eurCard = Card.fromString(CardTest.JSON_CARD_EUR); - - assertNotNull(usdCard); - assertNotNull(eurCard); - - assertNotEquals(usdCard.hashCode(), eurCard.hashCode()); - } - - @Test - public void putStripeJsonModelListIfNotNull_forMapsWhenNull_doesNothing() { - Map sampleMap = new HashMap<>(); - StripeJsonModel.putStripeJsonModelListIfNotNull(sampleMap, "mapkey", null); - - assertTrue(sampleMap.isEmpty()); - } - - @Test - public void putStripeJsonModelListIfNotNull_forJsonWhenNull_doesNothing() { - JSONObject jsonObject = new JSONObject(); - StripeJsonModel.putStripeJsonModelListIfNotNull(jsonObject, "jsonkey", null); - - assertFalse(jsonObject.has("jsonkey")); - } - - @Test - @SuppressWarnings("unchecked") - public void putStripeJsonModelListIfNotNull_forMapsWhenNotNull_addsExpectedList() { - List exampleJsonModels = new ArrayList<>(); - exampleJsonModels.add(new ExampleJsonModel()); - exampleJsonModels.add(new ExampleJsonModel()); - - Map originalMap = new HashMap<>(); - StripeJsonModel.putStripeJsonModelListIfNotNull(originalMap, "mapkey", exampleJsonModels); - - assertFalse(originalMap.isEmpty()); - assertTrue(originalMap.get("mapkey") instanceof List); - - List> modelList = (List) originalMap.get("mapkey"); - List> expectedList = new ArrayList<>(); - expectedList.add(new ExampleJsonModel().toMap()); - expectedList.add(new ExampleJsonModel().toMap()); - - JsonTestUtils.assertListEquals(expectedList, modelList); - } - - @Test - public void putStripeJsonModelListIfNotNull_forJsonWhenNotNull_addsExpectedList() { - List exampleJsonModels = new ArrayList<>(); - exampleJsonModels.add(new ExampleJsonModel()); - exampleJsonModels.add(new ExampleJsonModel()); - - JSONObject jsonObject = new JSONObject(); - StripeJsonModel.putStripeJsonModelListIfNotNull(jsonObject, "listkey", exampleJsonModels); - - assertEquals(1, jsonObject.length()); - JSONArray jsonArray = jsonObject.optJSONArray("listkey"); - assertNotNull(jsonArray); - assertEquals(2, jsonArray.length()); - - JSONArray expectedArray = new JSONArray(); - expectedArray.put(new ExampleJsonModel().toJson()); - expectedArray.put(new ExampleJsonModel().toJson()); - - JsonTestUtils.assertJsonArrayEquals(expectedArray, jsonArray); - } - - private static class ExampleJsonModel extends StripeJsonModel { - - @NonNull - @Override - public Map toMap() { - Map map = new HashMap<>(); - map.put("akey", "avalue"); - map.put("bkey", "bvalue"); - return map; - } - - @NonNull - @Override - public JSONObject toJson() { - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("akey", "avalue"); - jsonObject.put("bkey", "bvalue"); - } catch (JSONException unexpected) { - fail("Test data failure: " + unexpected.getMessage()); - } - return jsonObject; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ExampleJsonModel)) { - return false; - } - - ExampleJsonModel other = (ExampleJsonModel) obj; - Map myMap = this.toMap(); - Map otherMap = other.toMap(); - for (String key : myMap.keySet()) { - if (!otherMap.containsKey(key) || myMap.get(key).equals(otherMap.get(key))) { - return false; - } - } - return myMap.size() == otherMap.size(); - } - } -} diff --git a/stripe/src/test/java/com/stripe/android/model/StripeJsonUtilsTest.java b/stripe/src/test/java/com/stripe/android/model/StripeJsonUtilsTest.java index 58fca0f199b..6950bfb3b8d 100644 --- a/stripe/src/test/java/com/stripe/android/model/StripeJsonUtilsTest.java +++ b/stripe/src/test/java/com/stripe/android/model/StripeJsonUtilsTest.java @@ -9,13 +9,13 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * Test class for {@link StripeJsonUtils}. @@ -87,68 +87,46 @@ public void nullIfNullOrEmpty_returnsInputIfNotNull() { } @Test - public void getString_whenFieldPresent_findsAndReturnsField() { + public void getString_whenFieldPresent_findsAndReturnsField() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("key", "value"); - assertEquals("value", StripeJsonUtils.getString(jsonObject, "key")); - } catch (JSONException jex) { - fail("No exception expected"); - } + jsonObject.put("key", "value"); + assertEquals("value", StripeJsonUtils.getString(jsonObject, "key")); } @Test - public void getString_whenFieldContainsRawNull_returnsNull() { + public void getString_whenFieldContainsRawNull_returnsNull() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("key", "null"); - assertNull(StripeJsonUtils.getString(jsonObject, "key")); - } catch (JSONException jex) { - fail("No exception expected"); - } + jsonObject.put("key", "null"); + assertNull(StripeJsonUtils.getString(jsonObject, "key")); } @Test(expected = JSONException.class) public void getString_whenFieldNotPresent_throwsJsonException() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); - StripeJsonUtils.getString(jsonObject, "differentKey"); - fail("Expected an exception."); } @Test - public void optString_whenFieldPresent_findsAndReturnsField() { + public void optString_whenFieldPresent_findsAndReturnsField() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("key", "value"); - assertEquals("value", StripeJsonUtils.optString(jsonObject, "key")); - } catch (JSONException jex) { - fail("No exception expected"); - } + jsonObject.put("key", "value"); + assertEquals("value", StripeJsonUtils.optString(jsonObject, "key")); } @Test - public void optString_whenFieldContainsRawNull_returnsNull() { + public void optString_whenFieldContainsRawNull_returnsNull() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("key", "null"); - assertNull(StripeJsonUtils.optString(jsonObject, "key")); - } catch (JSONException jex) { - fail("No exception expected"); - } + jsonObject.put("key", "null"); + assertNull(StripeJsonUtils.optString(jsonObject, "key")); } @Test - public void optString_whenFieldNotPresent_returnsNull() { + public void optString_whenFieldNotPresent_returnsNull() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("key", "value"); - Object ob = StripeJsonUtils.optString(jsonObject, "nokeyshere"); - assertNull(ob); - } catch (JSONException jex) { - fail("No exception expected"); - } + jsonObject.put("key", "value"); + Object ob = StripeJsonUtils.optString(jsonObject, "nokeyshere"); + assertNull(ob); } @Test @@ -172,24 +150,20 @@ public void jsonArrayToList_forNull_returnsNull() { } @Test - public void mapToJsonObject_forSimpleObjects_returnsExpectedObject() { + public void mapToJsonObject_forSimpleObjects_returnsExpectedObject() throws JSONException { Map testMap = new HashMap<>(); testMap.put("akey", "avalue"); testMap.put("bkey", "bvalue"); testMap.put("boolkey", true); testMap.put("numkey", 123); - try { - JSONObject expectedJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); - JSONObject testObject = StripeJsonUtils.mapToJsonObject(testMap); - JsonTestUtils.assertJsonEquals(expectedJsonObject, testObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject expectedJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); + JSONObject testObject = StripeJsonUtils.mapToJsonObject(testMap); + JsonTestUtils.assertJsonEquals(expectedJsonObject, testObject); } @Test - public void mapToJsonObject_forNestedMaps_returnsExpectedObject() { + public void mapToJsonObject_forNestedMaps_returnsExpectedObject() throws JSONException { Map testMap = new HashMap<>(); testMap.put("top_key", new HashMap() {{ @@ -205,17 +179,13 @@ public void mapToJsonObject_forNestedMaps_returnsExpectedObject() { put("another_inner_key", false); }}); - try { - JSONObject expectedJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); - JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); - JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject expectedJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); + JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); + JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); } @Test - public void mapToJsonObject_withNestedMapAndLists_returnsExpectedObject() { + public void mapToJsonObject_withNestedMapAndLists_returnsExpectedObject() throws JSONException { Map testMap = new HashMap<>(); testMap.put("other_outer_key", false); @@ -227,7 +197,7 @@ public void mapToJsonObject_withNestedMapAndLists_returnsExpectedObject() { itemsList.add("a string item"); itemsList.add(256); itemsList.add(Arrays.asList(1, 2, "C", 4)); - itemsList.add(Arrays.asList(new HashMap() {{ + itemsList.add(Collections.singletonList(new HashMap() {{ put("deep", "deepValue"); }})); testMap.put("outer_key", @@ -236,17 +206,13 @@ public void mapToJsonObject_withNestedMapAndLists_returnsExpectedObject() { put("another_key", "a simple value this time"); }}); - try { - JSONObject expectedJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); - JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); - JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject expectedJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); + JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); + JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); } @Test - public void listToJsonArray_forSimpleList_returnsExpectedArray() { + public void listToJsonArray_forSimpleList_returnsExpectedArray() throws JSONException { List testList = new ArrayList<>(); testList.add(1); testList.add(2); @@ -255,52 +221,40 @@ public void listToJsonArray_forSimpleList_returnsExpectedArray() { testList.add(true); testList.add("cde"); - try { - JSONArray expectedJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); - JSONArray testJsonArray = StripeJsonUtils.listToJsonArray(testList); - JsonTestUtils.assertJsonArrayEquals(expectedJsonArray, testJsonArray); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONArray expectedJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); + JSONArray testJsonArray = StripeJsonUtils.listToJsonArray(testList); + JsonTestUtils.assertJsonArrayEquals(expectedJsonArray, testJsonArray); } @Test - public void jsonObjectToMap_forSimpleObjects_returnsExpectedMap() { + public void jsonObjectToMap_forSimpleObjects_returnsExpectedMap() throws JSONException { Map expectedMap = new HashMap<>(); expectedMap.put("akey", "avalue"); expectedMap.put("bkey", "bvalue"); expectedMap.put("boolkey", true); expectedMap.put("numkey", 123); - try { - JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); - Map mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); - JsonTestUtils.assertMapEquals(expectedMap, mappedObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); + Map mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); + JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } @Test - public void jsonObjectToStringMap_forSimpleObjects_returnsExpectedMap() { + public void jsonObjectToStringMap_forSimpleObjects_returnsExpectedMap() throws JSONException { Map expectedMap = new HashMap<>(); expectedMap.put("akey", "avalue"); expectedMap.put("bkey", "bvalue"); expectedMap.put("boolkey", "true"); expectedMap.put("numkey", "123"); - try { - JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); - Map mappedObject = - StripeJsonUtils.jsonObjectToStringMap(testJsonObject); - JsonTestUtils.assertMapEquals(expectedMap, mappedObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); + Map mappedObject = + StripeJsonUtils.jsonObjectToStringMap(testJsonObject); + JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } @Test - public void jsonObjectToMap_forNestedObjects_returnsExpectedMap() { + public void jsonObjectToMap_forNestedObjects_returnsExpectedMap() throws JSONException { Map expectedMap = new HashMap<>(); expectedMap.put("top_key", new HashMap() {{ @@ -316,35 +270,29 @@ public void jsonObjectToMap_forNestedObjects_returnsExpectedMap() { put("another_inner_key", false); }}); - try { - JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); - Map mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); - JsonTestUtils.assertMapEquals(expectedMap, mappedObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); + Map mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); + JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } @Test - public void jsonObjectToStringMap_forNestedObjects_returnsExpectedFlatMap() { + public void jsonObjectToStringMap_forNestedObjects_returnsExpectedFlatMap() + throws JSONException { Map expectedMap = new HashMap<>(); expectedMap.put("top_key", "{\"first_inner_key\":{\"innermost_key\":1000," + "\"second_innermost_key\":\"second_inner_value\"}," + "\"second_inner_key\":\"just a value\"}"); expectedMap.put("second_outer_key", "{\"another_inner_key\":false}"); - try { - JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); - Map mappedObject = - StripeJsonUtils.jsonObjectToStringMap(testJsonObject); - JsonTestUtils.assertMapEquals(expectedMap, mappedObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); + Map mappedObject = + StripeJsonUtils.jsonObjectToStringMap(testJsonObject); + JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } @Test - public void jsonObjectToMap_withNestedObjectAndArrays_returnsExpectedMap() { + public void jsonObjectToMap_withNestedObjectAndArrays_returnsExpectedMap() + throws JSONException { Map expectedMap = new HashMap<>(); expectedMap.put("other_outer_key", false); @@ -356,7 +304,7 @@ public void jsonObjectToMap_withNestedObjectAndArrays_returnsExpectedMap() { itemsList.add("a string item"); itemsList.add(256); itemsList.add(Arrays.asList(1, 2, "C", 4)); - itemsList.add(Arrays.asList(new HashMap() {{ + itemsList.add(Collections.singletonList(new HashMap() {{ put("deep", "deepValue"); }})); expectedMap.put("outer_key", @@ -365,17 +313,13 @@ public void jsonObjectToMap_withNestedObjectAndArrays_returnsExpectedMap() { put("another_key", "a simple value this time"); }}); - try { - JSONObject testJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); - Map convertedMap = StripeJsonUtils.jsonObjectToMap(testJsonObject); - JsonTestUtils.assertMapEquals(expectedMap, convertedMap); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject testJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); + Map convertedMap = StripeJsonUtils.jsonObjectToMap(testJsonObject); + JsonTestUtils.assertMapEquals(expectedMap, convertedMap); } @Test - public void jsonArrayToList_forSimpleList_returnsExpectedList() { + public void jsonArrayToList_forSimpleList_returnsExpectedList() throws JSONException { List expectedList = new ArrayList<>(); expectedList.add(1); expectedList.add(2); @@ -384,41 +328,29 @@ public void jsonArrayToList_forSimpleList_returnsExpectedList() { expectedList.add(true); expectedList.add("cde"); - try { - JSONArray testJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); - List convertedJsonArray = StripeJsonUtils.jsonArrayToList(testJsonArray); - JsonTestUtils.assertListEquals(expectedList, convertedJsonArray); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONArray testJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); + List convertedJsonArray = StripeJsonUtils.jsonArrayToList(testJsonArray); + JsonTestUtils.assertListEquals(expectedList, convertedJsonArray); } @Test - public void mapToJsonObjectAndBackToMap_forComplicatedObject_isNoOp() { - try { - JSONObject testJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); - Map convertedMap = StripeJsonUtils.jsonObjectToMap(testJsonObject); - JSONObject cycledObject = StripeJsonUtils.mapToJsonObject(convertedMap); - JsonTestUtils.assertJsonEquals(cycledObject, testJsonObject); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + public void mapToJsonObjectAndBackToMap_forComplicatedObject_isNoOp() throws JSONException { + JSONObject testJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); + Map convertedMap = StripeJsonUtils.jsonObjectToMap(testJsonObject); + JSONObject cycledObject = StripeJsonUtils.mapToJsonObject(convertedMap); + JsonTestUtils.assertJsonEquals(cycledObject, testJsonObject); } @Test - public void stringHashToJsonObject_returnsExpectedObject() { + public void stringHashToJsonObject_returnsExpectedObject() throws JSONException { Map stringHash = new HashMap<>(); stringHash.put("akey", "avalue"); stringHash.put("bkey", "bvalue"); stringHash.put("ckey", "cvalue"); stringHash.put("dkey", "dvalue"); - try { - JSONObject expectedObject = new JSONObject(SIMPLE_JSON_HASH_OBJECT); - JsonTestUtils.assertJsonEquals(expectedObject, - StripeJsonUtils.stringHashToJsonObject(stringHash)); - } catch (JSONException jsonException) { - fail("Test data failure " + jsonException.getLocalizedMessage()); - } + JSONObject expectedObject = new JSONObject(SIMPLE_JSON_HASH_OBJECT); + JsonTestUtils.assertJsonEquals(expectedObject, + StripeJsonUtils.stringHashToJsonObject(stringHash)); } } diff --git a/stripe/src/test/java/com/stripe/android/model/StripeModelTest.java b/stripe/src/test/java/com/stripe/android/model/StripeModelTest.java new file mode 100644 index 00000000000..ddde517eb61 --- /dev/null +++ b/stripe/src/test/java/com/stripe/android/model/StripeModelTest.java @@ -0,0 +1,125 @@ +package com.stripe.android.model; + +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; + +import com.stripe.android.testharness.JsonTestUtils; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static com.stripe.android.model.StripeModel.putModelIfNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; + +public class StripeModelTest { + + @Test + public void equals_whenEquals_returnsTrue() { + assertTrue(StripeModel.class.isAssignableFrom(Card.class)); + + Card firstCard = Card.fromString(CardTest.JSON_CARD_USD); + Card secondCard = Card.fromString(CardTest.JSON_CARD_USD); + + assertEquals(firstCard, secondCard); + // Just confirming for sanity + assertNotSame(firstCard, secondCard); + } + + @Test + public void equals_whenNotEquals_returnsFalse() { + assertTrue(StripeModel.class.isAssignableFrom(Card.class)); + final Card firstCard = Card.create("4242", null, null, null); + final Card secondCard = Card.create("4343", null, null, null); + assertNotEquals(firstCard, secondCard); + } + + @Test + public void hashCode_whenEquals_returnsSameValue() { + assertTrue(StripeModel.class.isAssignableFrom(Card.class)); + + Card firstCard = Card.fromString(CardTest.JSON_CARD_USD); + Card secondCard = Card.fromString(CardTest.JSON_CARD_USD); + assertNotNull(firstCard); + assertNotNull(secondCard); + + assertEquals(firstCard.hashCode(), secondCard.hashCode()); + } + + @Test + public void hashCode_whenNotEquals_returnsDifferentValues() { + assertTrue(StripeModel.class.isAssignableFrom(Card.class)); + + Card usdCard = Card.fromString(CardTest.JSON_CARD_USD); + Card eurCard = Card.fromString(CardTest.JSON_CARD_EUR); + + assertNotNull(usdCard); + assertNotNull(eurCard); + + assertNotEquals(usdCard.hashCode(), eurCard.hashCode()); + } + + @Test + public void putStripeJsonModelListIfNotNull_forMapsWhenNotNull_addsExpectedList() { + List exampleJsonModels = new ArrayList<>(); + exampleJsonModels.add(new ExampleModel()); + exampleJsonModels.add(new ExampleModel()); + + final Map originalMap = new HashMap<>(); + putModelIfNotNull(originalMap, "mapkey", exampleJsonModels); + + assertFalse(originalMap.isEmpty()); + assertTrue(originalMap.get("mapkey") instanceof List); + + //noinspection unchecked + List> modelList = (List) originalMap.get("mapkey"); + List> expectedList = new ArrayList<>(); + expectedList.add(new ExampleModel().toMap()); + expectedList.add(new ExampleModel().toMap()); + + JsonTestUtils.assertListEquals(expectedList, modelList); + } + + private static class ExampleModel extends StripeModel { + @NonNull + @Override + public Map toMap() { + final Map map = new HashMap<>(); + map.put("akey", "avalue"); + map.put("bkey", "bvalue"); + return map; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (!(obj instanceof ExampleModel)) { + return false; + } + + final ExampleModel other = (ExampleModel) obj; + final Map myMap = toMap(); + final Map otherMap = other.toMap(); + for (String key : myMap.keySet()) { + if (!otherMap.containsKey(key) || + Objects.requireNonNull(myMap.get(key)).equals(otherMap.get(key))) { + return false; + } + } + return myMap.size() == otherMap.size(); + } + } +} diff --git a/stripe/src/test/java/com/stripe/android/model/StripeSourceTypeModelTest.java b/stripe/src/test/java/com/stripe/android/model/StripeSourceTypeModelTest.java index 5fbae125620..e239aa1f695 100644 --- a/stripe/src/test/java/com/stripe/android/model/StripeSourceTypeModelTest.java +++ b/stripe/src/test/java/com/stripe/android/model/StripeSourceTypeModelTest.java @@ -16,7 +16,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; /** * Test class for {@link StripeSourceTypeModel}. @@ -24,16 +23,13 @@ public class StripeSourceTypeModelTest { @Test - public void jsonObjectToMapWithoutKeys_whenHasKeyInput_returnsMapOmittingKeys() { + public void jsonObjectToMapWithoutKeys_whenHasKeyInput_returnsMapOmittingKeys() + throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("a_key", "a_value"); - jsonObject.put("b_key", "b_value"); - jsonObject.put("c_key", "c_value"); - jsonObject.put("d_key", "d_value"); - } catch (JSONException unexpected) { - fail("Unexpected error: " + unexpected.getLocalizedMessage()); - } + jsonObject.put("a_key", "a_value"); + jsonObject.put("b_key", "b_value"); + jsonObject.put("c_key", "c_value"); + jsonObject.put("d_key", "d_value"); Set omitKeys = new HashSet() {{ add("a_key"); @@ -49,14 +45,10 @@ public void jsonObjectToMapWithoutKeys_whenHasKeyInput_returnsMapOmittingKeys() } @Test - public void jsonObjectToMapWithoutKeys_whenAllKeysGiven_returnsNull() { + public void jsonObjectToMapWithoutKeys_whenAllKeysGiven_returnsNull() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("a_key", "a_value"); - jsonObject.put("b_key", "b_value"); - } catch (JSONException unexpected) { - fail("Unexpected error: " + unexpected.getLocalizedMessage()); - } + jsonObject.put("a_key", "a_value"); + jsonObject.put("b_key", "b_value"); Set omitKeys = new HashSet() {{ add("a_key"); @@ -67,14 +59,10 @@ public void jsonObjectToMapWithoutKeys_whenAllKeysGiven_returnsNull() { } @Test - public void jsonObjectToMapWithoutKeys_whenOtherKeysGiven_returnsFullMap() { + public void jsonObjectToMapWithoutKeys_whenOtherKeysGiven_returnsFullMap() throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("a_key", "a_value"); - jsonObject.put("b_key", "b_value"); - } catch (JSONException unexpected) { - fail("Unexpected error: " + unexpected.getLocalizedMessage()); - } + jsonObject.put("a_key", "a_value"); + jsonObject.put("b_key", "b_value"); Set omitKeys = new HashSet() {{ add("c_key"); @@ -100,13 +88,10 @@ public void putAdditionalFieldsIntoJsonObject_whenHasFields_putsThemIntoObject() } @Test - public void putAdditionalFieldsIntoJsonObject_whenHasDuplicateFields_putsThemIntoObject() { + public void putAdditionalFieldsIntoJsonObject_whenHasDuplicateFields_putsThemIntoObject() + throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("a_key", "original"); - } catch (JSONException unexpected) { - fail("Unexpected exception: " + unexpected); - } + jsonObject.put("a_key", "original"); Map additionalFields = new HashMap<>(); additionalFields.put("a_key", "a_value"); @@ -119,13 +104,11 @@ public void putAdditionalFieldsIntoJsonObject_whenHasDuplicateFields_putsThemInt } @Test - public void putAdditionalFieldsIntoJsonObject_whenNoFieldsArePassed_doesNothing() { + public void putAdditionalFieldsIntoJsonObject_whenNoFieldsArePassed_doesNothing() + throws JSONException { JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("a", "a_value"); - } catch (JSONException unexpected) { - fail("Unexpected error: " + unexpected.getLocalizedMessage()); - } + jsonObject.put("a", "a_value"); + Map emptyMap = new HashMap<>(); putAdditionalFieldsIntoJsonObject(jsonObject, emptyMap); diff --git a/stripe/src/test/java/com/stripe/android/model/wallets/WalletFactoryTest.java b/stripe/src/test/java/com/stripe/android/model/wallets/WalletFactoryTest.java index 53b5daf4d88..012cc195f01 100644 --- a/stripe/src/test/java/com/stripe/android/model/wallets/WalletFactoryTest.java +++ b/stripe/src/test/java/com/stripe/android/model/wallets/WalletFactoryTest.java @@ -89,8 +89,6 @@ public void testCreateVisaCheckoutWallet() throws JSONException { final JSONObject walletJson = new JSONObject(VISA_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof VisaCheckoutWallet); - final VisaCheckoutWallet visaCheckoutWallet = (VisaCheckoutWallet) wallet; - assertEquals(visaCheckoutWallet.toJson().toString(), walletJson.toString()); } @Test @@ -98,8 +96,6 @@ public void testCreateMasterpassWallet() throws JSONException { final JSONObject walletJson = new JSONObject(MASTERPASS_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof MasterpassWallet); - final MasterpassWallet masterpassWallet = (MasterpassWallet) wallet; - assertEquals(masterpassWallet.toJson().toString(), walletJson.toString()); } @Test @@ -107,8 +103,6 @@ public void testCreateAmexExpressCheckoutWallet() throws JSONException { final JSONObject walletJson = new JSONObject(AMEX_EXPRESS_CHECKOUT_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof AmexExpressCheckoutWallet); - final AmexExpressCheckoutWallet amexCheckoutWallet = (AmexExpressCheckoutWallet) wallet; - assertEquals(amexCheckoutWallet.toJson().toString(), walletJson.toString()); } @Test @@ -116,8 +110,6 @@ public void testCreateApplePayWallet() throws JSONException { final JSONObject walletJson = new JSONObject(APPLE_PAY_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof ApplePayWallet); - final ApplePayWallet applePayWallet = (ApplePayWallet) wallet; - assertEquals(applePayWallet.toJson().toString(), walletJson.toString()); } @Test @@ -125,8 +117,6 @@ public void testCreateGooglePayWallet() throws JSONException { final JSONObject walletJson = new JSONObject(GOOGLE_PAY_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof GooglePayWallet); - final GooglePayWallet googlePayWallet = (GooglePayWallet) wallet; - assertEquals(googlePayWallet.toJson().toString(), walletJson.toString()); } @Test @@ -134,8 +124,6 @@ public void testCreateSamsungPayWallet() throws JSONException { final JSONObject walletJson = new JSONObject(SAMSUNG_PAY_WALLET_JSON); final Wallet wallet = new WalletFactory().create(walletJson); assertTrue(wallet instanceof SamsungPayWallet); - final SamsungPayWallet samsungPayWallet = (SamsungPayWallet) wallet; - assertEquals(samsungPayWallet.toJson().toString(), walletJson.toString()); } @Test diff --git a/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtils.java b/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtils.java index b541c4ddd3b..2193fd2e949 100644 --- a/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtils.java +++ b/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtils.java @@ -1,5 +1,6 @@ package com.stripe.android.testharness; +import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.json.JSONArray; @@ -24,8 +25,9 @@ public class JsonTestUtils { * @param first the first object * @param second the second object */ - public static void assertJsonEquals(JSONObject first, JSONObject second) { - if (assertSameNullity(first, second)) { + public static void assertJsonEquals(@Nullable JSONObject first, @Nullable JSONObject second) { + assertSameNullity(first, second); + if (first == null || second == null) { return; } @@ -52,42 +54,6 @@ public static void assertJsonEquals(JSONObject first, JSONObject second) { } } - /** - * Assert that two {@link JSONObject JSONObjects} are equal, comparing key by key recursively. - * Ignores nulls. - * - * @param first the first object - * @param second the second object - */ - public static void assertJsonEqualsExcludingNulls(JSONObject first, JSONObject second) { - if (assertSameNullity(first, second)) { - return; - } - - Iterator keyIterator = first.keys(); - while(keyIterator.hasNext()) { - String key = keyIterator.next(); - String errorMessage = getKeyErrorMessage(key); - if (first.opt(key) != JSONObject.NULL) { - assertTrue(errorMessage, second.has(key)); - } - if (first.opt(key) instanceof JSONObject) { - assertTrue(errorMessage, second.opt(key) instanceof JSONObject); - assertJsonEqualsExcludingNulls(first.optJSONObject(key), second.optJSONObject(key)); - } else if (first.opt(key) instanceof JSONArray) { - assertTrue(errorMessage, second.opt(key) instanceof JSONArray); - assertJsonArrayEquals(first.optJSONArray(key), second.optJSONArray(key)); - } else if (first.opt(key) instanceof Number) { - assertTrue(errorMessage, second.opt(key) instanceof Number); - assertEquals(errorMessage, - ((Number) first.opt(key)).longValue(), - ((Number) second.opt(key)).longValue()); - } else { - assertEquals(errorMessage, first.opt(key), second.opt(key)); - } - } - } - /** * Assert that two {@link JSONArray JSONArrays} are equal, comparing index by index recursively. @@ -95,10 +61,13 @@ public static void assertJsonEqualsExcludingNulls(JSONObject first, JSONObject s * @param first the first array * @param second the second array */ - public static void assertJsonArrayEquals(JSONArray first, JSONArray second) { - if (assertSameNullity(first, second)) { + public static void assertJsonArrayEquals(@Nullable JSONArray first, + @Nullable JSONArray second) { + assertSameNullity(first, second); + if (first == null || second == null) { return; } + assertEquals(first.length(), second.length()); for (int i = 0; i < first.length(); i++) { if (first.opt(i) instanceof JSONObject) { @@ -123,9 +92,10 @@ public static void assertJsonArrayEquals(JSONArray first, JSONArray second) { * @param first the first map * @param second the second map */ - public static void assertMapEquals(Map first, - Map second) { - if (assertSameNullity(first, second)) { + public static void assertMapEquals(@Nullable Map first, + @Nullable Map second) { + assertSameNullity(first, second); + if (first == null || second == null) { return; } @@ -144,8 +114,9 @@ public static void assertMapEquals(Map first, * @param first the first list * @param second the second list */ - public static void assertListEquals(List first, List second) { - if (assertSameNullity(first, second)) { + public static void assertListEquals(@Nullable List first, @Nullable List second) { + assertSameNullity(first, second); + if (first == null || second == null) { return; } @@ -188,17 +159,14 @@ private static Map castMapWithGenerics(Map needsCasting) { * * @param first the first object to check * @param second the second object to check - * @return {@code false} if both objects are non-null, {@code true} if they are {@code null} */ - private static boolean assertSameNullity(@Nullable Object first, @Nullable Object second) { - boolean sameNullity = first == null - ? second == null - : second != null; + private static void assertSameNullity(@Nullable Object first, @Nullable Object second) { + boolean sameNullity = (first == null) == (second == null); assertTrue(sameNullity); - return first == null; } - private static String getKeyErrorMessage(String key) { + @NonNull + private static String getKeyErrorMessage(@NonNull String key) { return String.format(Locale.ENGLISH, "Matching error at key %s", key); } } diff --git a/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtilsTest.java b/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtilsTest.java index 0e6a7383289..5ffcc97de00 100644 --- a/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtilsTest.java +++ b/stripe/src/test/java/com/stripe/android/testharness/JsonTestUtilsTest.java @@ -12,11 +12,6 @@ import java.util.Map; import java.util.TreeMap; -import static org.junit.Assert.fail; - -/** - * Test class for the test utils class {@link JsonTestUtils}. - */ public class JsonTestUtilsTest { @Test @@ -35,70 +30,49 @@ public void assertJsonEquals_forNullAndNonNull_fails() { } @Test - public void assertJsonEquals_forSimpleObjects_passes() { - String simpleJson = "{\"key\": \"value\"}"; - try { - JSONObject first = new JSONObject(simpleJson); - JSONObject second = new JSONObject(simpleJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + public void assertJsonEquals_forSimpleObjects_passes() throws JSONException { + JSONObject first = new JSONObject("{\"key\": \"value\"}"); + JSONObject second = new JSONObject("{\"key\": \"value\"}"); + JsonTestUtils.assertJsonEquals(first, second); } @Test - public void assertJsonEquals_forSimpleObjectsWithNumbers_passes() { + public void assertJsonEquals_forSimpleObjectsWithNumbers_passes() throws JSONException { String simpleJson = "{\"key\": \"value\", \"key2\": 100}"; - try { - JSONObject first = new JSONObject(simpleJson); - JSONObject second = new JSONObject(simpleJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(simpleJson); + JSONObject second = new JSONObject(simpleJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test(expected = AssertionError.class) - public void assertJsonEquals_forSimpleUnequalObjects_fails() { + public void assertJsonEquals_forSimpleUnequalObjects_fails() throws JSONException { String simpleJson = "{\"key\": \"value\"}"; String differentJson = "{\"key2\": \"value2\"}"; - try { - JSONObject first = new JSONObject(simpleJson); - JSONObject second = new JSONObject(differentJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(simpleJson); + JSONObject second = new JSONObject(differentJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test(expected = AssertionError.class) - public void assertJsonEquals_forSimpleObjectsOfDifferentSize_fails() { + public void assertJsonEquals_forSimpleObjectsOfDifferentSize_fails() throws JSONException { String simpleJson = "{\"key\": \"value\"}"; String differentJson = "{\"key\": \"value\", \"key2\": \"value2\"}"; - try { - JSONObject first = new JSONObject(simpleJson); - JSONObject second = new JSONObject(differentJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(simpleJson); + JSONObject second = new JSONObject(differentJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test(expected = AssertionError.class) - public void assertJsonEquals_forSimpleUnequalObjectsWithSameKey_fails() { + public void assertJsonEquals_forSimpleUnequalObjectsWithSameKey_fails() throws JSONException { String simpleJson = "{\"key\": \"value\"}"; String differentJson = "{\"key\": \"value2\"}"; - try { - JSONObject first = new JSONObject(simpleJson); - JSONObject second = new JSONObject(differentJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(simpleJson); + JSONObject second = new JSONObject(differentJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test - public void assertJsonEquals_withNestedEqualObjects_passes() { + public void assertJsonEquals_withNestedEqualObjects_passes() throws JSONException { String nestedJson = "{\n" + " \"top_key\": {\n" + " \"first_inner_key\": {\n" + @@ -111,17 +85,13 @@ public void assertJsonEquals_withNestedEqualObjects_passes() { " \"another_inner_key\": \"a value\"\n" + " }\n" + "}"; - try { - JSONObject first = new JSONObject(nestedJson); - JSONObject second = new JSONObject(nestedJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(nestedJson); + JSONObject second = new JSONObject(nestedJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test(expected = AssertionError.class) - public void assertJsonEquals_withNestedUnequalObjects_fails() { + public void assertJsonEquals_withNestedUnequalObjects_fails() throws JSONException { String nestedJson = "{\n" + " \"top_key\": {\n" + " \"first_inner_key\": {\n" + @@ -146,17 +116,13 @@ public void assertJsonEquals_withNestedUnequalObjects_fails() { " \"another_inner_key\": \"a value\"\n" + " }\n" + "}"; - try { - JSONObject first = new JSONObject(nestedJson); - JSONObject second = new JSONObject(alteredNestedJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(nestedJson); + JSONObject second = new JSONObject(alteredNestedJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test - public void assertJsonEquals_forNestedEqualObjectsWithArrays_passes() { + public void assertJsonEquals_forNestedEqualObjectsWithArrays_passes() throws JSONException { String complicatedJson = "{\n" + " \"top_key\": {\n" + " \"first_inner_key\": {\n" + @@ -177,17 +143,13 @@ public void assertJsonEquals_forNestedEqualObjectsWithArrays_passes() { " \"anotherkey\": \"a simple value this time\"\n" + " }\n" + "}"; - try { - JSONObject first = new JSONObject(complicatedJson); - JSONObject second = new JSONObject(complicatedJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(complicatedJson); + JSONObject second = new JSONObject(complicatedJson); + JsonTestUtils.assertJsonEquals(first, second); } @Test(expected = AssertionError.class) - public void assertJsonEquals_forNestedUnEqualObjectsWithArrays_fails() { + public void assertJsonEquals_forNestedUnEqualObjectsWithArrays_fails() throws JSONException { String complicatedJson = "{\n" + " \"top_key\": {\n" + " \"first_inner_key\": {\n" + @@ -229,13 +191,9 @@ public void assertJsonEquals_forNestedUnEqualObjectsWithArrays_fails() { " \"anotherkey\": \"a simple value this time\"\n" + " }\n" + "}"; - try { - JSONObject first = new JSONObject(complicatedJson); - JSONObject second = new JSONObject(alteredComplicatedJson); - JsonTestUtils.assertJsonEquals(first, second); - } catch (JSONException dataException) { - fail("Test data failure: " + dataException.getLocalizedMessage()); - } + JSONObject first = new JSONObject(complicatedJson); + JSONObject second = new JSONObject(alteredComplicatedJson); + JsonTestUtils.assertJsonEquals(first, second); } // Note: more complicated list and array functions are tested in the JsonObject and Map diff --git a/stripe/src/test/java/com/stripe/android/view/CardMultilineWidgetTest.java b/stripe/src/test/java/com/stripe/android/view/CardMultilineWidgetTest.java index 5e2aed51614..c579baa0c23 100644 --- a/stripe/src/test/java/com/stripe/android/view/CardMultilineWidgetTest.java +++ b/stripe/src/test/java/com/stripe/android/view/CardMultilineWidgetTest.java @@ -615,8 +615,8 @@ public void setCardNumber_whenHasNoSpaces_canCreateValidCard() { public void validateCardNumber_whenValid_doesNotShowError() { mCardMultilineWidget.setCardNumber(VALID_VISA_WITH_SPACES); - Boolean isValid = mCardMultilineWidget.validateCardNumber(); - Boolean shouldShowError = mFullGroup.cardNumberEditText.getShouldShowError(); + boolean isValid = mCardMultilineWidget.validateCardNumber(); + boolean shouldShowError = mFullGroup.cardNumberEditText.getShouldShowError(); assertTrue(isValid); assertFalse(shouldShowError); @@ -627,14 +627,13 @@ public void validateCardNumber_whenInvalid_setsShowError() { String invalidNumber = "1234 1234 1234 1234"; mCardMultilineWidget.setCardNumber(invalidNumber); - Boolean isValid = mCardMultilineWidget.validateCardNumber(); - Boolean shouldShowError = mFullGroup.cardNumberEditText.getShouldShowError(); + boolean isValid = mCardMultilineWidget.validateCardNumber(); + boolean shouldShowError = mFullGroup.cardNumberEditText.getShouldShowError(); assertFalse(isValid); assertTrue(shouldShowError); } - @Test public void setEnabled_setsEnabledPropertyOnAllChildWidgets() { assertTrue(mCardMultilineWidget.isEnabled());