diff --git a/src/com/mangopay/MangoPayApi.java b/src/com/mangopay/MangoPayApi.java index 5fdc711f..667191f9 100644 --- a/src/com/mangopay/MangoPayApi.java +++ b/src/com/mangopay/MangoPayApi.java @@ -1,106 +1,115 @@ -package com.mangopay; - -import com.mangopay.core.Configuration; -import com.mangopay.core.*; - -/** - * MangoPay API main entry point. - * Provides managers to connect, send and read data from MangoPay API - * as well as holds configuration/authorization data. - */ -public class MangoPayApi { - - public MangoPayApi() { - - // default config setup - Config = new Configuration(); - OAuthTokenManager = new AuthorizationTokenManager(this); - - // API managers - AuthenticationManager = new ApiOAuth(this); - Clients = new ApiClients(this); - Users = new ApiUsers(this); - Wallets = new ApiWallets(this); - PayIns = new ApiPayIns(this); - PayOuts = new ApiPayOuts(this); - Refunds = new ApiRefunds(this); - Transfers = new ApiTransfers(this); - CardRegistrations = new ApiCardRegistrations(this); - Cards = new ApiCards(this); - Events = new ApiEvents(this); - } - - //////////////////////////////////////// - // Config/authorization related fields - //////////////////////////////////////// - - /** - * Authorization token methods. - */ - public AuthorizationTokenManager OAuthTokenManager; - - /** - * Configuration instance with default settings (to be reset if required). - */ - public Configuration Config; - - //////////////////////////////////////// - // API managers fields - //////////////////////////////////////// - - /** - * OAuth methods. - */ - public ApiOAuth AuthenticationManager; - - /** - * Clients methods. - */ - public ApiClients Clients; - - /** - * Users methods. - */ - public ApiUsers Users; - - /** - * Wallets methods. - */ - public ApiWallets Wallets; - - /** - * PayIns methods. - */ - public ApiPayIns PayIns; - - /** - * PayOuts methods. - */ - public ApiPayOuts PayOuts; - - /** - * Transfer methods. - */ - public ApiTransfers Transfers; - - /** - * CardRegistrations methods. - */ - public ApiCardRegistrations CardRegistrations; - - /** - * Cards methods. - */ - public ApiCards Cards; - - /** - * Refunds methods. - */ - public ApiRefunds Refunds; - - /** - * Events methods. - */ - public ApiEvents Events; - -} +package com.mangopay; + +import com.mangopay.core.Configuration; +import com.mangopay.core.*; + +/** + * MangoPay API main entry point. + * Provides managers to connect, send and read data from MangoPay API + * as well as holds configuration/authorization data. + */ +public class MangoPayApi { + + public MangoPayApi() { + + // default config setup + Config = new Configuration(); + OAuthTokenManager = new AuthorizationTokenManager(this); + + // API managers + AuthenticationManager = new ApiOAuth(this); + Clients = new ApiClients(this); + Users = new ApiUsers(this); + Wallets = new ApiWallets(this); + PayIns = new ApiPayIns(this); + PayOuts = new ApiPayOuts(this); + Refunds = new ApiRefunds(this); + Transfers = new ApiTransfers(this); + CardRegistrations = new ApiCardRegistrations(this); + Cards = new ApiCards(this); + Events = new ApiEvents(this); + CardPreAuthorizations = new ApiCardPreAuthorizations(this); + Hooks = new ApiHooks(this); + } + + //////////////////////////////////////// + // Config/authorization related fields + //////////////////////////////////////// + + /** + * Authorization token methods. + */ + public AuthorizationTokenManager OAuthTokenManager; + + /** + * Configuration instance with default settings (to be reset if required). + */ + public Configuration Config; + + //////////////////////////////////////// + // API managers fields + //////////////////////////////////////// + + /** + * OAuth methods. + */ + public ApiOAuth AuthenticationManager; + + /** + * Clients methods. + */ + public ApiClients Clients; + + /** + * Users methods. + */ + public ApiUsers Users; + + /** + * Wallets methods. + */ + public ApiWallets Wallets; + + /** + * PayIns methods. + */ + public ApiPayIns PayIns; + + /** + * PayOuts methods. + */ + public ApiPayOuts PayOuts; + + /** + * Transfer methods. + */ + public ApiTransfers Transfers; + + /** + * CardRegistrations methods. + */ + public ApiCardRegistrations CardRegistrations; + + public ApiCardPreAuthorizations CardPreAuthorizations; + + /** + * Cards methods. + */ + public ApiCards Cards; + + /** + * Refunds methods. + */ + public ApiRefunds Refunds; + + /** + * Events methods. + */ + public ApiEvents Events; + + /** + * Hooks methods. + */ + public ApiHooks Hooks; + +} diff --git a/src/com/mangopay/core/ApiBase.java b/src/com/mangopay/core/ApiBase.java index 19854415..d7a9f099 100644 --- a/src/com/mangopay/core/ApiBase.java +++ b/src/com/mangopay/core/ApiBase.java @@ -1,329 +1,348 @@ -package com.mangopay.core; - -import com.mangopay.MangoPayApi; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * MangoPay API base class. - */ -public abstract class ApiBase { - - /** - * Root/parent instance that holds the OAuthToken and Configuration instance - */ - protected MangoPayApi _root; - - /** - * Array with REST URL and request type. - */ - private Map methods = new HashMap(){{ - - put("authentication_base", new String[] { "/api/clients/", RequestType.POST }); - put("authentication_oauth", new String[] { "/api/oauth/token", RequestType.POST }); - - put("crosscurrencytransfers_create", new String[] { "/transfers/%s", RequestType.POST }); - put("crosscurrencytransfers_get", new String[] { "/transfers/%s", RequestType.GET }); - - put("events_all", new String[] { "/events", RequestType.GET }); - put("events_gethookcallbacks", new String[] { "/events/%s/hook-callbacks", RequestType.GET }); - - put("hooks_create", new String[] { "/hooks", RequestType.POST }); - put("hooks_all", new String[] { "/hooks", RequestType.GET }); - put("hooks_get", new String[] { "/hooks/%s", RequestType.GET }); - put("hooks_save", new String[] { "/hooks/%s", RequestType.PUT }); - - put("info_get", new String[] { "/info", RequestType.GET }); - put("info_getfeewallets", new String[] { "/info/fee-wallets", RequestType.GET }); - put("info_getmeansofpayment", new String[] { "/info/means-of-payment", RequestType.GET }); - - put("cardregistration_create", new String[] { "/cardregistrations", RequestType.POST }); - put("cardregistration_get", new String[] { "/cardregistrations/%s", RequestType.GET }); - put("cardregistration_save", new String[] { "/cardregistrations/%s", RequestType.PUT }); - - put("card_get", new String[] { "/cards/%s", RequestType.GET }); - - // pay ins URLs - put("payins_card-web_create", new String[] { "/payins/card/web/", RequestType.POST }); - put("payins_card-direct_create", new String[] { "/payins/card/direct/", RequestType.POST }); - put("payins_card-preauthorized_create", new String[] { "/payins/card/preauthorized/", RequestType.POST }); - put("payins_card-recurrentexecution_create", new String[] { "/payins/card/recurrent-pay-in-execution/", RequestType.POST }); - - put("payins_registeredcard-web_create", new String[] { "/payins/registered-card/web/", RequestType.POST }); - put("payins_registeredcard-direct_create", new String[] { "/payins/registered-card/direct/", RequestType.POST }); - put("payins_registeredcard-preauthorized_create", new String[] { "/payins/registered-card/preauthorized/", RequestType.POST }); - put("payins_registeredcard-recurrentexecution_create", new String[] { "/payins/registered-card/recurrent-pay-in-execution/", RequestType.POST }); - - put("payins_bankwirepayin-web_create", new String[] { "/payins/bankwire/web/", RequestType.POST }); - put("payins_bankwirepayin-direct_create", new String[] { "/payins/bankwire/direct/", RequestType.POST }); - put("payins_bankwirepayin-preauthorized_create", new String[] { "/payins/bankwire/preauthorized/", RequestType.POST }); - put("payins_bankwirepayin-recurrentexecution_create", new String[] { "/payins/bankwire/recurrent-pay-in-execution/", RequestType.POST }); - - put("payins_directcredit-web_create", new String[] { "/payins/direct-credit/web/", RequestType.POST }); - put("payins_directcredit-direct_create", new String[] { "/payins/direct-credit/direct/", RequestType.POST }); - put("payins_directcredit-preauthorized_create", new String[] { "/payins/direct-credit/preauthorized/", RequestType.POST }); - put("payins_directcredit-recurrentexecution_create", new String[] { "/payins/direct-credit/recurrent-pay-in-execution/", RequestType.POST }); - put("payins_get", new String[] { "/payins/%s", RequestType.GET }); - put("payins_createrefunds", new String[] { "/payins/%s/refunds", RequestType.POST }); - - put("payouts_bankwire_create", new String[] { "/payouts/bankwire/", RequestType.POST }); - put("payouts_merchantexpense_create", new String[] { "/payouts/merchant-expense/", RequestType.POST }); - put("payouts_amazongiftcard_create", new String[] { "/payouts/amazon-giftcard/", RequestType.POST }); - put("payouts_get", new String[] { "/payouts/%s", RequestType.GET }); - put("payouts_createrefunds", new String[] { "/payouts/%s/refunds", RequestType.POST }); - put("payouts_getrefunds", new String[] { "/payouts/%s/refunds", RequestType.GET }); - - put("reccurringpayinorders_create", new String[] { "/reccurring-pay-in-orders", RequestType.POST }); - put("reccurringpayinorders_get", new String[] { "/reccurring-pay-in-orders/%s", RequestType.GET }); - put("reccurringpayinorders_gettransactions", new String[] { "/reccurring-pay-in-orders/%s/transactions", RequestType.GET }); - - put("refunds_get", new String[] { "/refunds/%s", RequestType.GET }); - - put("repudiations_get", new String[] { "/repudiations/%s", RequestType.GET }); - - put("transfers_create", new String[] { "/transfers/", RequestType.POST }); - put("transfers_get", new String[] { "/transfers/%s", RequestType.GET }); - put("transfers_getrefunds", new String[] { "/transfers/%s/refunds", RequestType.GET }); - put("transfers_createrefunds", new String[] { "/transfers/%s/refunds", RequestType.POST }); - - put("users_createnaturals", new String[] { "/users/natural", RequestType.POST }); - put("users_createlegals", new String[] { "/users/legal", RequestType.POST }); - put("users_createkycrequests", new String[] { "/users/%s/KYC/requests", RequestType.POST }); - put("users_createbankaccounts", new String[] { "/users/%s/bankaccounts", RequestType.POST }); - put("users_all", new String[] { "/users", RequestType.GET }); - put("users_allkyc", new String[] { "/users/%s/KYC", RequestType.GET }); - put("users_allkycrequests", new String[] { "/users/%s/KYC/requests", RequestType.GET }); - put("users_allwallets", new String[] { "/users/%s/wallets", RequestType.GET }); - put("users_allbankaccount", new String[] { "/users/%s/bankaccounts", RequestType.GET }); - put("users_allpaymentcards", new String[] { "/users/%s/payment-cards", RequestType.GET }); - put("users_get", new String[] { "/users/%s", RequestType.GET }); - put("users_getnaturals", new String[] { "/users/natural/%s", RequestType.GET }); - put("users_getlegals", new String[] { "/users/legal/%s", RequestType.GET }); - put("users_getkycrequests", new String[] { "/users/%s/KYC/requests/%s", RequestType.GET }); - put("users_getproofofidentity", new String[] { "/users/%s/ProofOfIdentity", RequestType.GET }); - put("users_getproofofaddress", new String[] { "/users/%s/ProofOfAddress", RequestType.GET }); - put("users_getproofofregistration", new String[] { "/users/%s/ProofOfRegistration", RequestType.GET }); - put("users_getshareholderdeclaration", new String[] { "/users/%s/ShareholderDeclaration", RequestType.GET }); - put("users_getbankaccount", new String[] { "/users/%s/bankaccounts/%s", RequestType.GET }); - put("users_getpaymentcards", new String[] { "/users/%s/payment-cards/%s", RequestType.GET }); - put("users_savenaturals", new String[] { "/users/natural/%s", RequestType.PUT }); - put("users_savelegals", new String[] { "/users/legal/%s", RequestType.PUT }); - - put("users_createkycdocument", new String[] { "/users/%s/KYC/documents", RequestType.POST }); - put("users_getkycdocument", new String[] { "/users/%s/KYC/documents/%s", RequestType.GET }); - put("users_savekycdocument", new String[] { "/users/%s/KYC/documents/%s", RequestType.PUT }); - put("users_createkycpage", new String[] { "/users/%s/KYC/documents/%s/pages", RequestType.POST }); - - put("wallets_create", new String[] { "/wallets", RequestType.POST }); - put("wallets_allrecurringpayinorders", new String[] { "/wallets/%s/recurring-pay-in-orders", RequestType.GET }); - put("wallets_alltransactions", new String[] { "/wallets/%s/transactions", RequestType.GET }); - put("wallets_alltransactionspage", new String[] { "/wallets/%s/transactions/pages/%s", RequestType.GET }); - put("wallets_get", new String[] { "/wallets/%s", RequestType.GET }); - put("wallets_save", new String[] { "/wallets/%s", RequestType.PUT }); - - }}; - - /** - * Creates new API instance. - * @param root Root/parent instance that holds the OAuthToken and Configuration instance - */ - public ApiBase(MangoPayApi root) { - _root = root; - } - - /** - * Gets the URL of REST Mango Pay API. - * @param key The method key to get URL of. - * @return The URL string of given method. - */ - protected String getRequestUrl(String key) { - return this.methods.get(key)[0]; - } - - /** - * Gets the HTTP request verb. - * @param key The method key. - * @return One of the HTTP verbs: GET, PUT or POST. - */ - protected String getRequestType(String key) { - return this.methods.get(key)[1]; - } - - /** - * Creates the Dto instance. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param entity Dto instance that is going to be sent. - * @param entityId Entity identifier. - * @param secondEntityId Second entity identifier. - * @return The Dto instance returned from API. - */ - protected T createObject(Class classOfT, String methodKey, T entity, String entityId, String secondEntityId) throws Exception { - - String urlMethod; - - if (entityId.length() == 0) - urlMethod = this.getRequestUrl(methodKey); - else if (secondEntityId.length() == 0) - urlMethod = String.format(this.getRequestUrl(methodKey), entityId); - else - urlMethod = String.format(this.getRequestUrl(methodKey), entityId, secondEntityId); - - RestTool rest = new RestTool(this._root, true); - T result = rest.request(classOfT, urlMethod, this.getRequestType(methodKey), null, null, entity); - - return result; - - } - /** - * Creates the Dto instance. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param entity Dto instance that is going to be sent. - * @param entityId Entity identifier. - * @return The Dto instance returned from API. - */ - protected T createObject(Class classOfT, String methodKey, T entity, String entityId) throws Exception { - return createObject(classOfT, methodKey, entity, entityId, ""); - } - /** - * Creates the Dto instance. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param entity Dto instance that is going to be sent. - * @return The Dto instance returned from API. - */ - protected T createObject(Class classOfT, String methodKey, T entity) throws Exception { - return createObject(classOfT, methodKey, entity, ""); - } - - /** - * Gets the Dto instance from API. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param entityId Entity identifier. - * @param secondEntityId Entity identifier for the second entity. - * @return The Dto instance returned from API. - */ - protected T getObject(Class classOfT, String methodKey, String entityId, String secondEntityId) throws Exception { - - String urlMethod = String.format(this.getRequestUrl(methodKey), entityId, secondEntityId); - - RestTool rest = new RestTool(this._root, true); - T response = rest.request(classOfT, urlMethod, this.getRequestType(methodKey)); - - return response; - } - - /** - * Gets the Dto instance from API. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param entityId Entity identifier. - * @return The Dto instance returned from API. - */ - protected T getObject(Class classOfT, String methodKey, String entityId) throws Exception { - return getObject(classOfT, methodKey, entityId, ""); - } - - /** - * Gets the array of Dto instances from API. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param pagination Pagination object. - * @param entityId Entity identifier. - * @param additionalUrlParams Collection of key-value pairs of request - parameters. - * @return The array of Dto instances returned - from API. - */ - protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination, String entityId, Map additionalUrlParams) throws Exception { - - String urlMethod = ""; - - if (entityId.length() > 0) - urlMethod = String.format(this.getRequestUrl(methodKey), entityId); - else - urlMethod = this.getRequestUrl(methodKey); - - if (pagination == null) { - pagination = new Pagination(); - } - - RestTool rest = new RestTool(this._root, true); - - return rest.requestList(classOfT, classOfTItem, urlMethod, this.getRequestType(methodKey), null, pagination, additionalUrlParams); - - } - /** - * Gets the array of Dto instances from API. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param pagination Pagination object. - * @param entityId Entity identifier. - * @return The array of Dto instances returned - from API. - */ - protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination, String entityId) throws Exception { - return getList(classOfT, classOfTItem, methodKey, pagination, entityId, null); - } - /** - * Gets the array of Dto instances from API. - * @param - * @param classOfT The class on behalf of which the request is - being called. - * @param methodKey Relevant method key. - * @param pagination Pagination object. - * @return The array of Dto instances returned - from API. - */ - protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination) throws Exception { - return getList(classOfT, classOfTItem, methodKey, pagination, ""); - } - - /** - * Saves the Dto instance. - * @param methodKey Relevant method key. - * @param entity Dto instance that is going to be sent. - * @return The Dto instance returned from API. - */ - protected T updateObject(Class classOfT, String methodKey, T entity) throws Exception { - return updateObject(classOfT, methodKey, entity, ""); - } - - protected T updateObject(Class classOfT, String methodKey, T entity, String entityId) throws Exception { - - if (entity instanceof EntityBase) { - - String urlMethod; - - if (entityId.length() == 0) - urlMethod = String.format(this.getRequestUrl(methodKey), ((EntityBase)entity).Id); - else { - String ggg = this.getRequestUrl(methodKey); - urlMethod = String.format(this.getRequestUrl(methodKey), entityId, ((EntityBase)entity).Id); - } - - - RestTool rest = new RestTool(this._root, true); - return rest.request(classOfT, urlMethod, this.getRequestType(methodKey), null, null, entity); - } else { - return null; - } - } -} +package com.mangopay.core; + +import com.mangopay.MangoPayApi; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MangoPay API base class. + */ +public abstract class ApiBase { + + /** + * Root/parent instance that holds the OAuthToken and Configuration instance + */ + protected MangoPayApi _root; + + /** + * Array with REST URL and request type. + */ + private Map methods = new HashMap(){{ + + put("authentication_base", new String[] { "/api/clients/", RequestType.POST }); + put("authentication_oauth", new String[] { "/api/oauth/token", RequestType.POST }); + + put("events_all", new String[] { "/events", RequestType.GET }); + put("events_gethookcallbacks", new String[] { "/events/%s/hook-callbacks", RequestType.GET }); + + put("hooks_create", new String[] { "/hooks", RequestType.POST }); + put("hooks_all", new String[] { "/hooks", RequestType.GET }); + put("hooks_get", new String[] { "/hooks/%s", RequestType.GET }); + put("hooks_save", new String[] { "/hooks/%s", RequestType.PUT }); + + put("info_get", new String[] { "/info", RequestType.GET }); + put("info_getfeewallets", new String[] { "/info/fee-wallets", RequestType.GET }); + put("info_getmeansofpayment", new String[] { "/info/means-of-payment", RequestType.GET }); + + put("cardregistration_create", new String[] { "/cardregistrations", RequestType.POST }); + put("cardregistration_get", new String[] { "/cardregistrations/%s", RequestType.GET }); + put("cardregistration_save", new String[] { "/cardregistrations/%s", RequestType.PUT }); + + put("preauthorization_create", new String[] { "/preauthorizations/card/direct", RequestType.POST }); + put("preauthorization_get", new String[] { "/preauthorizations/%s", RequestType.GET }); + put("preauthorization_save", new String[] { "/preauthorizations/%s", RequestType.PUT }); + + put("card_get", new String[] { "/cards/%s", RequestType.GET }); + + // pay ins URLs + put("payins_card-web_create", new String[] { "/payins/card/web/", RequestType.POST }); + put("payins_card-direct_create", new String[] { "/payins/card/direct/", RequestType.POST }); + put("payins_card-preauthorized_create", new String[] { "/payins/card/preauthorized/", RequestType.POST }); + put("payins_card-recurrentexecution_create", new String[] { "/payins/card/recurrent-pay-in-execution/", RequestType.POST }); + + put("payins_registeredcard-web_create", new String[] { "/payins/registered-card/web/", RequestType.POST }); + put("payins_registeredcard-direct_create", new String[] { "/payins/registered-card/direct/", RequestType.POST }); + put("payins_registeredcard-preauthorized_create", new String[] { "/payins/registered-card/preauthorized/", RequestType.POST }); + put("payins_registeredcard-recurrentexecution_create", new String[] { "/payins/registered-card/recurrent-pay-in-execution/", RequestType.POST }); + + put("payins_bankwirepayin-web_create", new String[] { "/payins/bankwire/web/", RequestType.POST }); + put("payins_bankwirepayin-direct_create", new String[] { "/payins/bankwire/direct/", RequestType.POST }); + put("payins_bankwirepayin-preauthorized_create", new String[] { "/payins/bankwire/preauthorized/", RequestType.POST }); + put("payins_bankwirepayin-recurrentexecution_create", new String[] { "/payins/bankwire/recurrent-pay-in-execution/", RequestType.POST }); + + put("payins_directcredit-web_create", new String[] { "/payins/direct-credit/web/", RequestType.POST }); + put("payins_directcredit-direct_create", new String[] { "/payins/direct-credit/direct/", RequestType.POST }); + put("payins_directcredit-preauthorized_create", new String[] { "/payins/direct-credit/preauthorized/", RequestType.POST }); + put("payins_directcredit-recurrentexecution_create", new String[] { "/payins/direct-credit/recurrent-pay-in-execution/", RequestType.POST }); + put("payins_get", new String[] { "/payins/%s", RequestType.GET }); + put("payins_createrefunds", new String[] { "/payins/%s/refunds", RequestType.POST }); + + put("payins_preauthorized-direct_create", new String[] { "/payins/preauthorized/direct/", RequestType.POST }); + put("payins_bankwire-direct_create", new String[] { "/payins/bankwire/direct/", RequestType.POST }); + + put("payouts_bankwire_create", new String[] { "/payouts/bankwire/", RequestType.POST }); + put("payouts_merchantexpense_create", new String[] { "/payouts/merchant-expense/", RequestType.POST }); + put("payouts_amazongiftcard_create", new String[] { "/payouts/amazon-giftcard/", RequestType.POST }); + put("payouts_get", new String[] { "/payouts/%s", RequestType.GET }); + put("payouts_createrefunds", new String[] { "/payouts/%s/refunds", RequestType.POST }); + put("payouts_getrefunds", new String[] { "/payouts/%s/refunds", RequestType.GET }); + + put("reccurringpayinorders_create", new String[] { "/reccurring-pay-in-orders", RequestType.POST }); + put("reccurringpayinorders_get", new String[] { "/reccurring-pay-in-orders/%s", RequestType.GET }); + put("reccurringpayinorders_gettransactions", new String[] { "/reccurring-pay-in-orders/%s/transactions", RequestType.GET }); + + put("refunds_get", new String[] { "/refunds/%s", RequestType.GET }); + + put("repudiations_get", new String[] { "/repudiations/%s", RequestType.GET }); + + put("transfers_create", new String[] { "/transfers/", RequestType.POST }); + put("transfers_get", new String[] { "/transfers/%s", RequestType.GET }); + put("transfers_getrefunds", new String[] { "/transfers/%s/refunds", RequestType.GET }); + put("transfers_createrefunds", new String[] { "/transfers/%s/refunds", RequestType.POST }); + + put("users_createnaturals", new String[] { "/users/natural", RequestType.POST }); + put("users_createlegals", new String[] { "/users/legal", RequestType.POST }); + put("users_createkycrequests", new String[] { "/users/%s/KYC/requests", RequestType.POST }); + + put("users_createbankaccounts_iban", new String[] { "/users/%s/bankaccounts/iban", RequestType.POST }); + put("users_createbankaccounts_gb", new String[] { "/users/%s/bankaccounts/gb", RequestType.POST }); + put("users_createbankaccounts_us", new String[] { "/users/%s/bankaccounts/us", RequestType.POST }); + put("users_createbankaccounts_ca", new String[] { "/users/%s/bankaccounts/ca", RequestType.POST }); + put("users_createbankaccounts_other", new String[] { "/users/%s/bankaccounts/other", RequestType.POST }); + + put("users_all", new String[] { "/users", RequestType.GET }); + put("users_allkyc", new String[] { "/users/%s/KYC", RequestType.GET }); + put("users_allkycrequests", new String[] { "/users/%s/KYC/requests", RequestType.GET }); + put("users_allwallets", new String[] { "/users/%s/wallets", RequestType.GET }); + put("users_allbankaccount", new String[] { "/users/%s/bankaccounts", RequestType.GET }); + put("users_allpaymentcards", new String[] { "/users/%s/payment-cards", RequestType.GET }); + put("users_get", new String[] { "/users/%s", RequestType.GET }); + put("users_getnaturals", new String[] { "/users/natural/%s", RequestType.GET }); + put("users_getlegals", new String[] { "/users/legal/%s", RequestType.GET }); + put("users_getkycrequests", new String[] { "/users/%s/KYC/requests/%s", RequestType.GET }); + put("users_getproofofidentity", new String[] { "/users/%s/ProofOfIdentity", RequestType.GET }); + put("users_getproofofaddress", new String[] { "/users/%s/ProofOfAddress", RequestType.GET }); + put("users_getproofofregistration", new String[] { "/users/%s/ProofOfRegistration", RequestType.GET }); + put("users_getshareholderdeclaration", new String[] { "/users/%s/ShareholderDeclaration", RequestType.GET }); + put("users_getbankaccount", new String[] { "/users/%s/bankaccounts/%s", RequestType.GET }); + put("users_getpaymentcards", new String[] { "/users/%s/payment-cards/%s", RequestType.GET }); + put("users_savenaturals", new String[] { "/users/natural/%s", RequestType.PUT }); + put("users_savelegals", new String[] { "/users/legal/%s", RequestType.PUT }); + + put("users_allcards", new String[] { "/users/%s/cards", RequestType.GET }); + put("users_alltransactions", new String[] { "/users/%s/transactions", RequestType.GET }); + + put("users_createkycdocument", new String[] { "/users/%s/KYC/documents", RequestType.POST }); + put("users_getkycdocument", new String[] { "/users/%s/KYC/documents/%s", RequestType.GET }); + put("users_savekycdocument", new String[] { "/users/%s/KYC/documents/%s", RequestType.PUT }); + put("users_createkycpage", new String[] { "/users/%s/KYC/documents/%s/pages", RequestType.POST }); + + put("wallets_create", new String[] { "/wallets", RequestType.POST }); + put("wallets_allrecurringpayinorders", new String[] { "/wallets/%s/recurring-pay-in-orders", RequestType.GET }); + put("wallets_alltransactions", new String[] { "/wallets/%s/transactions", RequestType.GET }); + put("wallets_alltransactionspage", new String[] { "/wallets/%s/transactions/pages/%s", RequestType.GET }); + put("wallets_get", new String[] { "/wallets/%s", RequestType.GET }); + put("wallets_save", new String[] { "/wallets/%s", RequestType.PUT }); + + }}; + + /** + * Creates new API instance. + * @param root Root/parent instance that holds the OAuthToken and Configuration instance + */ + public ApiBase(MangoPayApi root) { + _root = root; + } + + /** + * Gets the URL of REST Mango Pay API. + * @param key The method key to get URL of. + * @return The URL string of given method. + */ + protected String getRequestUrl(String key) throws Exception { + String result = ""; + try { + result = this.methods.get(key)[0]; + } catch (Exception ex) { + throw new Exception("Unknown method key: " + key); + } + return result; + } + + /** + * Gets the HTTP request verb. + * @param key The method key. + * @return One of the HTTP verbs: GET, PUT or POST. + */ + protected String getRequestType(String key) { + return this.methods.get(key)[1]; + } + + /** + * Creates the Dto instance. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param entity Dto instance that is going to be sent. + * @param entityId Entity identifier. + * @param secondEntityId Second entity identifier. + * @return The Dto instance returned from API. + */ + protected T createObject(Class classOfT, String methodKey, T entity, String entityId, String secondEntityId) throws Exception { + + String urlMethod; + + if (entityId.length() == 0) + urlMethod = this.getRequestUrl(methodKey); + else if (secondEntityId.length() == 0) + urlMethod = String.format(this.getRequestUrl(methodKey), entityId); + else + urlMethod = String.format(this.getRequestUrl(methodKey), entityId, secondEntityId); + + RestTool rest = new RestTool(this._root, true); + T result = rest.request(classOfT, urlMethod, this.getRequestType(methodKey), null, null, entity); + + return result; + + } + /** + * Creates the Dto instance. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param entity Dto instance that is going to be sent. + * @param entityId Entity identifier. + * @return The Dto instance returned from API. + */ + protected T createObject(Class classOfT, String methodKey, T entity, String entityId) throws Exception { + return createObject(classOfT, methodKey, entity, entityId, ""); + } + /** + * Creates the Dto instance. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param entity Dto instance that is going to be sent. + * @return The Dto instance returned from API. + */ + protected T createObject(Class classOfT, String methodKey, T entity) throws Exception { + return createObject(classOfT, methodKey, entity, ""); + } + + /** + * Gets the Dto instance from API. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param entityId Entity identifier. + * @param secondEntityId Entity identifier for the second entity. + * @return The Dto instance returned from API. + */ + protected T getObject(Class classOfT, String methodKey, String entityId, String secondEntityId) throws Exception { + + String urlMethod = String.format(this.getRequestUrl(methodKey), entityId, secondEntityId); + + RestTool rest = new RestTool(this._root, true); + T response = rest.request(classOfT, urlMethod, this.getRequestType(methodKey)); + + return response; + } + + /** + * Gets the Dto instance from API. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param entityId Entity identifier. + * @return The Dto instance returned from API. + */ + protected T getObject(Class classOfT, String methodKey, String entityId) throws Exception { + return getObject(classOfT, methodKey, entityId, ""); + } + + /** + * Gets the array of Dto instances from API. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param pagination Pagination object. + * @param entityId Entity identifier. + * @param additionalUrlParams Collection of key-value pairs of request + parameters. + * @return The array of Dto instances returned + from API. + */ + protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination, String entityId, Map additionalUrlParams) throws Exception { + + String urlMethod = ""; + + if (entityId.length() > 0) + urlMethod = String.format(this.getRequestUrl(methodKey), entityId); + else + urlMethod = this.getRequestUrl(methodKey); + + if (pagination == null) { + pagination = new Pagination(); + } + + RestTool rest = new RestTool(this._root, true); + + return rest.requestList(classOfT, classOfTItem, urlMethod, this.getRequestType(methodKey), null, pagination, additionalUrlParams); + + } + /** + * Gets the array of Dto instances from API. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param pagination Pagination object. + * @param entityId Entity identifier. + * @return The array of Dto instances returned + from API. + */ + protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination, String entityId) throws Exception { + return getList(classOfT, classOfTItem, methodKey, pagination, entityId, null); + } + /** + * Gets the array of Dto instances from API. + * @param + * @param classOfT The class on behalf of which the request is + being called. + * @param methodKey Relevant method key. + * @param pagination Pagination object. + * @return The array of Dto instances returned + from API. + */ + protected List getList(Class classOfT, Class classOfTItem, String methodKey, Pagination pagination) throws Exception { + return getList(classOfT, classOfTItem, methodKey, pagination, ""); + } + + /** + * Saves the Dto instance. + * @param methodKey Relevant method key. + * @param entity Dto instance that is going to be sent. + * @return The Dto instance returned from API. + */ + protected T updateObject(Class classOfT, String methodKey, T entity) throws Exception { + return updateObject(classOfT, methodKey, entity, ""); + } + + protected T updateObject(Class classOfT, String methodKey, T entity, String entityId) throws Exception { + + if (entity instanceof EntityBase) { + + String urlMethod; + + if (entityId.length() == 0) + urlMethod = String.format(this.getRequestUrl(methodKey), ((EntityBase)entity).Id); + else { + String ggg = this.getRequestUrl(methodKey); + urlMethod = String.format(this.getRequestUrl(methodKey), entityId, ((EntityBase)entity).Id); + } + + + RestTool rest = new RestTool(this._root, true); + return rest.request(classOfT, urlMethod, this.getRequestType(methodKey), null, null, entity); + } else { + return null; + } + } +} diff --git a/src/com/mangopay/core/ApiCardPreAuthorizations.java b/src/com/mangopay/core/ApiCardPreAuthorizations.java new file mode 100644 index 00000000..72ae08c0 --- /dev/null +++ b/src/com/mangopay/core/ApiCardPreAuthorizations.java @@ -0,0 +1,44 @@ +package com.mangopay.core; + +import com.mangopay.MangoPayApi; +import com.mangopay.entities.CardPreAuthorization; + +/** + * API for card pre-authorizations. + */ +public class ApiCardPreAuthorizations extends ApiBase { + + /** + * @param root Root/parent instance that holds the OAuthToken and Configuration instance. + */ + public ApiCardPreAuthorizations(MangoPayApi root) { super(root); } + + /** + * Creates new pre-authorization object. + * @param cardPreAuthorization PreAuthorization object to be created. + * @return PreAuthorization object returned from API. + * @throws Exception + */ + public CardPreAuthorization create(CardPreAuthorization cardPreAuthorization) throws Exception { + return this.createObject(CardPreAuthorization.class, "preauthorization_create", cardPreAuthorization); + } + + /** + * Gets pre-authorization object. + * @param cardPreAuthorizationId PreAuthorization identifier. + * @return Card registration instance returned from API. + * @throws Exception + */ + public CardPreAuthorization get(String cardPreAuthorizationId) throws Exception { + return this.getObject(CardPreAuthorization.class, "preauthorization_get", cardPreAuthorizationId); + } + /** + * Updates pre-authorization object. + * @param cardPreAuthorization PreAuthorization object to be updated. + * @return PreAuthorization object returned from API. + * @throws Exception + */ + public CardPreAuthorization update(CardPreAuthorization cardPreAuthorization) throws Exception { + return this.updateObject(CardPreAuthorization.class, "preauthorization_save", cardPreAuthorization); + } +} diff --git a/src/com/mangopay/core/ApiHooks.java b/src/com/mangopay/core/ApiHooks.java new file mode 100644 index 00000000..3384dd84 --- /dev/null +++ b/src/com/mangopay/core/ApiHooks.java @@ -0,0 +1,63 @@ +package com.mangopay.core; + +import com.mangopay.MangoPayApi; +import com.mangopay.entities.Hook; +import java.util.List; + +/** + * API for Hooks. + */ +public class ApiHooks extends ApiBase { + + /** + * @param root Root/parent instance that holds the OAuthToken and Configuration instance + */ + public ApiHooks(MangoPayApi root) { super(root); } + + /** + * Creates new hook. + * @param Hook hook + * @return Hook Hook object returned from API. + */ + public Hook create(Hook hook) throws Exception { + return this.createObject(Hook.class, "hooks_create", hook); + } + + /** + * Gets hook. + * @param type $hookId Hook identifier + * @return \MangoPay\Hook Wallet object returned from API + */ + public Hook get(String hookId) throws Exception { + return this.getObject(Hook.class, "hooks_get", hookId); + } + + /** + * Saves hook. + * @param type $hook Hook object to save + * @return \MangoPay\Hook Hook object returned from API + */ + public Hook update(Hook hook) throws Exception { + return this.updateObject(Hook.class, "hooks_save", hook); + } + + /** + * Gets all hooks. + * @param pagination + * @return List of Hook objects returned from API. + * @throws Exception + */ + public List getAll(Pagination pagination) throws Exception { + return this.getList(Hook[].class, Hook.class, "hooks_all", pagination); + } + + /** + * Gets all hooks. + * @return List of Hook objects returned from API. + * @throws Exception + */ + public List getAll() throws Exception { + return this.getAll(null); + } + +} diff --git a/src/com/mangopay/core/ApiUsers.java b/src/com/mangopay/core/ApiUsers.java index 0fd79bab..2d89a457 100644 --- a/src/com/mangopay/core/ApiUsers.java +++ b/src/com/mangopay/core/ApiUsers.java @@ -1,205 +1,242 @@ -package com.mangopay.core; - -import com.mangopay.MangoPayApi; -import com.mangopay.entities.*; -import org.apache.commons.codec.binary.Base64;; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.apache.commons.codec.binary.StringUtils; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.apache.commons.codec.binary.StringUtils; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -/** - * API for Users. - */ -public class ApiUsers extends ApiBase { - - /** - * @param root Root/parent instance that holds the OAuthToken and Configuration instance - */ - public ApiUsers(MangoPayApi root) { super(root); } - - /** - * Gets user by its identifier. - * @param userId User identifier. - * @return User instance returned from API, which is either of - UserNatural or UserLegal type. - * @throws Exception - */ - public User get(String userId) throws Exception { - return this.getObject(User.class, "users_get", userId); - } - - /** - * Creates new user. - * @param user User object to be created. - * @return User instance returned from API, which is either of - UserNatural or UserLegal type. - * @throws Exception - */ - public User create(User user) throws Exception { - - User response = null; - - if (user instanceof UserNatural) - response = this.createObject(UserNatural.class, "users_createnaturals", (UserNatural)user); - else if (user instanceof UserLegal) - response = this.createObject(UserLegal.class, "users_createlegals", (UserLegal)user); - else - throw new Exception("Unsupported user entity type."); - - return response; - } - - /** - * Gets page of users. - * @param pagination Pagination object. - * @return Collection of User instances. - * @throws Exception - */ - public List getAll(Pagination pagination) throws Exception { - return this.getList(User[].class, User.class, "users_all", pagination); - } - - /** - * Gets first page of users. - * @return Collection of User instances. - * @throws Exception - */ - public List getAll() throws Exception { - return getAll(null); - } - - /** - * Gets natural user by its identifier, - * @param userId UserNatural identifier. - * @return UserNatural object returned from API. - * @throws Exception - */ - public UserNatural getNatural(String userId) throws Exception { - return this.getObject(UserNatural.class, "users_getnaturals", userId); - } - - /** - * Gets legal user by its identifier. - * @param userId UserLegal identifier. - * @return UserLegal object returned from API. - * @throws Exception - */ - public UserLegal getLegal(String userId) throws Exception { - return this.getObject(UserLegal.class, "users_getlegals", userId); - } - - /** - * Updates the user. - * @param user Instance of UserNatural or UserLegal class to be - updated. - * @return Updated User object returned from API. - * @throws Exception - */ - public User update(User user) throws Exception { - - String methodKey = ""; - if (user instanceof UserNatural) - methodKey = "users_savenaturals"; - else if (user instanceof UserLegal) - methodKey = "users_savelegals"; - else - throw new Exception("Unsupported user entity type."); - - return this.updateObject(User.class, methodKey, user); - } - - /** - * Creates bank account for user. - * @param userId User identifier to create bank account for. - * @param bankAccount Bank account object. - * @return Created bank account object returned by API. - * @throws Exception - */ - public BankAccount createBankAccount(String userId, BankAccount bankAccount) throws Exception { - return this.createObject(BankAccount.class, "users_createbankaccounts", bankAccount, userId); - } - - /** - * Gets all bank accounts of user. - * @param userId User identifier to get bank accounts of. - * @param pagination Pagination object. - * @return Collection of bank accounts of user. - * @throws Exception - */ - public List getBankAccounts(String userId, Pagination pagination) throws Exception { - return this.getList(BankAccount[].class, BankAccount.class, "users_allbankaccount", pagination, userId); - } - - /** - * Gets first page of all bank accounts of user. - * @param userId User identifier to get bank accounts of. - * @return Collection of bank accounts of user. - * @throws Exception - */ - public List getBankAccounts(String userId) throws Exception { - return getBankAccounts(userId, null); - } - - /** - * Gets bank account of user. - * @param userId User identifier. - * @param bankAccountId Bank account identifier. - * @return Bank account object returned by API. - * @throws Exception - */ - public BankAccount getBankAccount(String userId, String bankAccountId) throws Exception { - return this.getObject(BankAccount.class, "users_getbankaccount", userId, bankAccountId); - } - - public void createKycPage(String userId, String kycDocumentId, byte[] binaryData) throws Exception { - KycPage kycPage = new KycPage(); - - String fileContent = new String(Base64.encodeBase64(binaryData)); - - kycPage.File = fileContent; - - try - { - this.createObject(KycPage.class, "users_createkycpage", kycPage, userId, kycDocumentId); - } - catch (Exception ex) - { - Exception e = ex; - } - } - - public void createKycPage(String userId, String kycDocumentId, String filePath) throws Exception { - byte[] fileArray; - Path path = Paths.get(filePath); - fileArray = Files.readAllBytes(path); - - createKycPage(userId, kycDocumentId, fileArray); - } - - public KycDocument createKycDocument(String userId, KycDocumentType type) throws Exception { - KycDocument kycDocument = new KycDocument(); - kycDocument.Type = type.name(); - - return this.createObject(KycDocument.class, "users_createkycdocument", kycDocument, userId); - } - - public KycDocument getKycDocument(String userId, String kycDocumentId) throws Exception { - return this.getObject(KycDocument.class, "users_getkycdocument", userId, kycDocumentId); - } - - public KycDocument updateKycDocument(String userId, KycDocument kycDocument) throws Exception { - return this.updateObject(KycDocument.class, "users_savekycdocument", kycDocument, userId); - } -} +package com.mangopay.core; + +import com.mangopay.MangoPayApi; +import com.mangopay.entities.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import org.apache.commons.codec.binary.Base64; + + +/** + * API for Users. + */ +public class ApiUsers extends ApiBase { + + /** + * @param root Root/parent instance that holds the OAuthToken and Configuration instance + */ + public ApiUsers(MangoPayApi root) { super(root); } + + /** + * Gets user by its identifier. + * @param userId User identifier. + * @return User instance returned from API, which is either of + UserNatural or UserLegal type. + * @throws Exception + */ + public User get(String userId) throws Exception { + return this.getObject(User.class, "users_get", userId); + } + + /** + * Creates new user. + * @param user User object to be created. + * @return User instance returned from API, which is either of + UserNatural or UserLegal type. + * @throws Exception + */ + public User create(User user) throws Exception { + + User response = null; + + if (user instanceof UserNatural) + response = this.createObject(UserNatural.class, "users_createnaturals", (UserNatural)user); + else if (user instanceof UserLegal) + response = this.createObject(UserLegal.class, "users_createlegals", (UserLegal)user); + else + throw new Exception("Unsupported user entity type."); + + return response; + } + + /** + * Gets page of users. + * @param pagination Pagination object. + * @return Collection of User instances. + * @throws Exception + */ + public List getAll(Pagination pagination) throws Exception { + return this.getList(User[].class, User.class, "users_all", pagination); + } + + /** + * Gets first page of users. + * @return Collection of User instances. + * @throws Exception + */ + public List getAll() throws Exception { + return getAll(null); + } + + /** + * Gets natural user by its identifier, + * @param userId UserNatural identifier. + * @return UserNatural object returned from API. + * @throws Exception + */ + public UserNatural getNatural(String userId) throws Exception { + return this.getObject(UserNatural.class, "users_getnaturals", userId); + } + + /** + * Gets legal user by its identifier. + * @param userId UserLegal identifier. + * @return UserLegal object returned from API. + * @throws Exception + */ + public UserLegal getLegal(String userId) throws Exception { + return this.getObject(UserLegal.class, "users_getlegals", userId); + } + + /** + * Updates the user. + * @param user Instance of UserNatural or UserLegal class to be + updated. + * @return Updated User object returned from API. + * @throws Exception + */ + public User update(User user) throws Exception { + + String methodKey = ""; + if (user instanceof UserNatural) + methodKey = "users_savenaturals"; + else if (user instanceof UserLegal) + methodKey = "users_savelegals"; + else + throw new Exception("Unsupported user entity type."); + + return this.updateObject(User.class, methodKey, user); + } + + /** + * Creates bank account for user. + * @param userId User identifier to create bank account for. + * @param bankAccount Bank account object. + * @return Created bank account object returned by API. + * @throws Exception + */ + public BankAccount createBankAccount(String userId, BankAccount bankAccount) throws Exception { + String type = this.getBankAccountType(bankAccount); + return this.createObject(BankAccount.class, "users_createbankaccounts_" + type, bankAccount, userId); + } + + /** + * Gets all bank accounts of user. + * @param userId User identifier to get bank accounts of. + * @param pagination Pagination object. + * @return Collection of bank accounts of user. + * @throws Exception + */ + public List getBankAccounts(String userId, Pagination pagination) throws Exception { + return this.getList(BankAccount[].class, BankAccount.class, "users_allbankaccount", pagination, userId); + } + + /** + * Gets first page of all bank accounts of user. + * @param userId User identifier to get bank accounts of. + * @return Collection of bank accounts of user. + * @throws Exception + */ + public List getBankAccounts(String userId) throws Exception { + return getBankAccounts(userId, null); + } + + /** + * Gets bank account of user. + * @param userId User identifier. + * @param bankAccountId Bank account identifier. + * @return Bank account object returned by API. + * @throws Exception + */ + public BankAccount getBankAccount(String userId, String bankAccountId) throws Exception { + return this.getObject(BankAccount.class, "users_getbankaccount", userId, bankAccountId); + } + + /** + * Gets transactions for user. + * @param userId User identifier. + * @param pagination Pagination object. + * @param filter Filter object. + * @return Collection of transactions of user. + * @throws Exception + */ + public List getTransactions(String userId, Pagination pagination, FilterTransactions filter) throws Exception { + return this.getList(Transaction[].class, Transaction.class, "users_alltransactions", pagination, userId, filter.getValues()); + } + + /** + * Gets all cards for user. + * @param userId User identifier. + * @param pagination Pagination object. + * @return Collection of user's cards. + * @throws Exception + */ + public List getCards(String userId, Pagination pagination) throws Exception { + return this.getList(Card[].class, Card.class, "users_allcards", pagination, userId); + } + + /** + * Creates KycPage from byte array. + * @param userId User identifier. + * @param kycDocumentId Kyc document identifier. + * @param binaryData The byte array the KycPage will be created from. + * @throws Exception + */ + public void createKycPage(String userId, String kycDocumentId, byte[] binaryData) throws Exception { + KycPage kycPage = new KycPage(); + + String fileContent = new String(Base64.encodeBase64(binaryData)); + + kycPage.File = fileContent; + + try + { + this.createObject(KycPage.class, "users_createkycpage", kycPage, userId, kycDocumentId); + } + catch (Exception ex) + { + Exception e = ex; + } + } + + /** + * Creates KycPage from file. + * @param userId User identifier. + * @param kycDocumentId Kyc document identifier. + * @param filePath Path to the file the KycPage will be created from. + * @throws Exception + */ + public void createKycPage(String userId, String kycDocumentId, String filePath) throws Exception { + byte[] fileArray; + Path path = Paths.get(filePath); + fileArray = Files.readAllBytes(path); + + createKycPage(userId, kycDocumentId, fileArray); + } + + public KycDocument createKycDocument(String userId, KycDocumentType type) throws Exception { + KycDocument kycDocument = new KycDocument(); + kycDocument.Type = type.name(); + + return this.createObject(KycDocument.class, "users_createkycdocument", kycDocument, userId); + } + + public KycDocument getKycDocument(String userId, String kycDocumentId) throws Exception { + return this.getObject(KycDocument.class, "users_getkycdocument", userId, kycDocumentId); + } + + public KycDocument updateKycDocument(String userId, KycDocument kycDocument) throws Exception { + return this.updateObject(KycDocument.class, "users_savekycdocument", kycDocument, userId); + } + + private String getBankAccountType(BankAccount bankAccount) throws Exception { + + if (bankAccount.Details == null) + throw new Exception("Details is not defined."); + + String className = bankAccount.Details.getClass().getSimpleName().replace("BankAccountDetails", ""); + return className.toLowerCase(); + } +} diff --git a/src/com/mangopay/core/BankAccountDetailsCA.java b/src/com/mangopay/core/BankAccountDetailsCA.java new file mode 100644 index 00000000..f5fbc2dc --- /dev/null +++ b/src/com/mangopay/core/BankAccountDetailsCA.java @@ -0,0 +1,28 @@ +package com.mangopay.core; + +/** + * Class represents CA type of bank account. + */ +public class BankAccountDetailsCA extends Dto implements IBankAccountDetails { + + /** + * Bank name. + */ + public String BankName; + + /** + * Institution number. + */ + public String InstitutionNumber; + + /** + * Branch code. + */ + public String BranchCode; + + /** + * Account number. + */ + public String AccountNumber; + +} diff --git a/src/com/mangopay/core/BankAccountDetailsGB.java b/src/com/mangopay/core/BankAccountDetailsGB.java new file mode 100644 index 00000000..394f8852 --- /dev/null +++ b/src/com/mangopay/core/BankAccountDetailsGB.java @@ -0,0 +1,18 @@ +package com.mangopay.core; + +/** + * Class represents GB type of bank account. + */ +public class BankAccountDetailsGB extends Dto implements IBankAccountDetails { + + /** + * Account number. + */ + public String AccountNumber; + + /** + * Sort code. + */ + public String SortCode; + +} diff --git a/src/com/mangopay/core/BankAccountDetailsIBAN.java b/src/com/mangopay/core/BankAccountDetailsIBAN.java new file mode 100644 index 00000000..6a5233e3 --- /dev/null +++ b/src/com/mangopay/core/BankAccountDetailsIBAN.java @@ -0,0 +1,18 @@ +package com.mangopay.core; + +/** + * Class represents IBAN type of bank account. + */ +public class BankAccountDetailsIBAN extends Dto implements IBankAccountDetails { + + /** + * IBAN number. + */ + public String IBAN; + + /** + * BIC. + */ + public String BIC; + +} diff --git a/src/com/mangopay/core/BankAccountDetailsOTHER.java b/src/com/mangopay/core/BankAccountDetailsOTHER.java new file mode 100644 index 00000000..8a1732b2 --- /dev/null +++ b/src/com/mangopay/core/BankAccountDetailsOTHER.java @@ -0,0 +1,29 @@ +package com.mangopay.core; + +/** + * Class represents OTHER type of bank account. + */ +public class BankAccountDetailsOTHER extends Dto implements IBankAccountDetails { + + /** + * Type. + */ + public String Type; + + /** + * The Country associate to the BankAccount, + * ISO 3166-1 alpha-2 format is expected. + */ + public String Country; + + /** + * Valid BIC format. + */ + public String BIC; + + /** + * Account number. + */ + public String AccountNumber; + +} diff --git a/src/com/mangopay/core/BankAccountDetailsUS.java b/src/com/mangopay/core/BankAccountDetailsUS.java new file mode 100644 index 00000000..9eba913a --- /dev/null +++ b/src/com/mangopay/core/BankAccountDetailsUS.java @@ -0,0 +1,18 @@ +package com.mangopay.core; + +/** + * Class represents US type of bank account. + */ +public class BankAccountDetailsUS extends Dto implements IBankAccountDetails { + + /** + * Account number. + */ + public String AccountNumber; + + /** + * ABA + */ + public String ABA; + +} diff --git a/src/com/mangopay/core/IBankAccountDetails.java b/src/com/mangopay/core/IBankAccountDetails.java new file mode 100644 index 00000000..cae4379e --- /dev/null +++ b/src/com/mangopay/core/IBankAccountDetails.java @@ -0,0 +1,6 @@ +package com.mangopay.core; + +/** + * Marker interface for classes with bank account details. + */ +public interface IBankAccountDetails { } diff --git a/src/com/mangopay/core/KycDocumentType.java b/src/com/mangopay/core/KycDocumentType.java index 00d51a45..153e440e 100644 --- a/src/com/mangopay/core/KycDocumentType.java +++ b/src/com/mangopay/core/KycDocumentType.java @@ -1,9 +1,12 @@ -package com.mangopay.core; - -/** - * KYC document type enumeration. - */ -public enum KycDocumentType { - IDENTITY_PROOF, - REGISTRATION_PROOF -} +package com.mangopay.core; + +/** + * KYC document type enumeration. + */ +public enum KycDocumentType { + IDENTITY_PROOF, + REGISTRATION_PROOF, + ARTICLES_OF_ASSOCIATION, + SHAREHOLDER_DECLARATION, + ADDRESS_PROOF +} diff --git a/src/com/mangopay/core/PayInExecutionDetailsDirect.java b/src/com/mangopay/core/PayInExecutionDetailsDirect.java index 1e04b3b6..06fa1c7d 100644 --- a/src/com/mangopay/core/PayInExecutionDetailsDirect.java +++ b/src/com/mangopay/core/PayInExecutionDetailsDirect.java @@ -1,23 +1,23 @@ -package com.mangopay.core; - -/** - * Class represents Web type for execution option in PayIn entity - */ -public class PayInExecutionDetailsDirect extends Dto implements IPayInExecutionDetails { - - /** - * SecureMode { DEFAULT, FORCE } - */ - public String SecureMode; - - /** - * CardId - */ - public String CardId; - - /** - * SecureModeReturnURL - */ - public String SecureModeReturnURL; - -} +package com.mangopay.core; + +/** + * Class representing the Web type for execution option in PayIn entity. + */ +public class PayInExecutionDetailsDirect extends Dto implements IPayInExecutionDetails { + + /** + * CardId. + */ + public String CardId; + + /** + * SecureMode { DEFAULT, FORCE } + */ + public String SecureMode; + + /** + * SecureModeReturnURL. + */ + public String SecureModeReturnURL; + +} diff --git a/src/com/mangopay/core/PayInPaymentDetailsBankWire.java b/src/com/mangopay/core/PayInPaymentDetailsBankWire.java new file mode 100644 index 00000000..ec050f54 --- /dev/null +++ b/src/com/mangopay/core/PayInPaymentDetailsBankWire.java @@ -0,0 +1,49 @@ +package com.mangopay.core; + +import com.mangopay.entities.BankAccount; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +/** + * Class representing the BankWire type for mean of payment in PayIn entity. + */ +public class PayInPaymentDetailsBankWire extends Dto implements IPayInPaymentDetails { + + /** + * Declared debited funds. + */ + public Money DeclaredDebitedFunds; + + /** + * Declared fees. + */ + public Money DeclaredFees; + + /** + * Bank account details. + */ + public BankAccount BankAccount; + + /** + * Wire reference. + */ + public String WireReference; + + /** + * Gets map which property is an object and what type of object. + * To be overridden in child class if has any sub objects. + * @return Collection of field name-field type pairs. + */ + @Override + public Map getSubObjects() { + + HashMap result = new HashMap<>(); + + result.put("DeclaredDebitedFunds", Money.class); + result.put("DeclaredFees", Money.class); + result.put("BankAccount", BankAccount.class); + + return result; + } +} diff --git a/src/com/mangopay/core/PayInPaymentDetailsCard.java b/src/com/mangopay/core/PayInPaymentDetailsCard.java index 4dac3310..1e575b14 100644 --- a/src/com/mangopay/core/PayInPaymentDetailsCard.java +++ b/src/com/mangopay/core/PayInPaymentDetailsCard.java @@ -1,12 +1,17 @@ package com.mangopay.core; /** - * Class represents Card type for mean of payment in PayIn entity + * Class representing the Card type for mean of payment in PayIn entity. */ public class PayInPaymentDetailsCard extends Dto implements IPayInPaymentDetails { /** - * CardType { CB_VISA_MASTERCARD, AMEX } + * Card type { CB_VISA_MASTERCARD, AMEX } */ public String CardType; + + /** + * Card identifier. + */ + public String CardId; } diff --git a/src/com/mangopay/core/PayInPaymentDetailsPreAuthorized.java b/src/com/mangopay/core/PayInPaymentDetailsPreAuthorized.java new file mode 100644 index 00000000..4af298de --- /dev/null +++ b/src/com/mangopay/core/PayInPaymentDetailsPreAuthorized.java @@ -0,0 +1,13 @@ +package com.mangopay.core; + +/** + * Class representing the Web type for execution option in PayIn entity. + */ +public class PayInPaymentDetailsPreAuthorized extends Dto implements IPayInPaymentDetails { + + /** + * The identifier of the Preauthorization object. + */ + public String PreauthorizationId; + +} diff --git a/src/com/mangopay/core/PayOutPaymentDetailsBankWire.java b/src/com/mangopay/core/PayOutPaymentDetailsBankWire.java index 1071fe09..6b6cf55c 100644 --- a/src/com/mangopay/core/PayOutPaymentDetailsBankWire.java +++ b/src/com/mangopay/core/PayOutPaymentDetailsBankWire.java @@ -1,7 +1,7 @@ package com.mangopay.core; /** - * Class representing BankWire type for mean of payment in PayOut entity + * Class representing the BankWire type for mean of payment in PayOut entity. */ public class PayOutPaymentDetailsBankWire extends Dto implements IPayOutPaymentDetails { @@ -11,8 +11,7 @@ public class PayOutPaymentDetailsBankWire extends Dto implements IPayOutPaymentD public String BankAccountId; /** - * Communication. + * Communication */ public String Communication; - } diff --git a/src/com/mangopay/core/RestTool.java b/src/com/mangopay/core/RestTool.java index 9cf5ce97..b24cd4ed 100644 --- a/src/com/mangopay/core/RestTool.java +++ b/src/com/mangopay/core/RestTool.java @@ -1,966 +1,976 @@ -package com.mangopay.core; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.mangopay.MangoPayApi; -import com.mangopay.entities.PayIn; -import com.mangopay.entities.PayOut; -import com.mangopay.entities.User; -import com.mangopay.entities.UserLegal; -import com.mangopay.entities.UserNatural; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; - -/** - * Class to prepare HTTP request, call the request and decode the response - */ -public class RestTool { - - /** - * Root/parent instance that holds the OAuthToken and Configuration instance - */ - private MangoPayApi _root; - - /** - * Variable to switch on/off log debugging - */ - private Boolean _debugMode; - - /** - * Variable to flag that in request authentication data are required - */ - private Boolean _authRequired; - - /** - * Array with HTTP header to send with request - */ - private Map _requestHttpHeaders; - - /** - * - */ - private HttpURLConnection _connection; - - /** - * Request type for current request - */ - private String _requestType; - - /** - * Key-value collection pass in the request - */ - private Map _requestData; - - /** - * Code get from response - */ - private int _responseCode; - - /** - * Pagination object - */ - private Pagination _pagination; - - /** - * Creates new RestTool object. - * @param root Root/parent instance that holds the OAuthToken and Configuration instance. - * @param authRequired Defines whether request authentication is required. - */ - public RestTool(MangoPayApi root, Boolean authRequired) throws Exception { - this._root = root; - this._authRequired = authRequired; - this._debugMode = this._root.Config.DebugMode; - } - - /** - * - * @param httpHeader - */ - public void addRequestHttpHeader(Map httpHeader) { - - if (this._requestHttpHeaders == null) - this._requestHttpHeaders = new HashMap<>(); - - this._requestHttpHeaders.putAll(httpHeader); - } - - /** - * - * @param key - * @param value - */ - public void addRequestHttpHeader(final String key, final String value) { - addRequestHttpHeader(new HashMap(){{ - put(key, value); - }}); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting single - * Dto instances. In order to process collections of objects, - * use requestList method instead. - * @param - * @param classOfT The class on behalf of which the request is being - called. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term, one of the GET, PUT or POST. - * @param requestData Collection of key-value pairs of request - parameters. - * @param pagination Pagination object. - * @param entity Instance of Dto class that is going to be - sent in case of PUTting or POSTing. - * @return The Dto instance returned from API. - */ - public T request(Class classOfT, String urlMethod, String requestType, Map requestData, Pagination pagination, T entity) throws Exception { - - this._requestType = requestType; - this._requestData = requestData; - - T responseResult = this.doRequest(classOfT, urlMethod, pagination, entity); - - if(pagination != null){ - pagination = this._pagination; - } - - return responseResult; - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting single - * Dto instances. In order to process collections of objects, - * use requestList method instead. - * @param - * @param classOfT The class on behalf of which the request is being - called. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term, one of the GET, PUT or POST. - * @return The Dto instance returned from API. - */ - public T request(Class classOfT, String urlMethod, String requestType) throws Exception { - return request(classOfT, urlMethod, requestType, null, null, null); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting single - * Dto instances. In order to process collections of objects, - * use requestList method instead. - * @param - * @param classOfT The class on behalf of which the request is being - called. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term, one of the GET, PUT or POST. - * @param requestData Collection of key-value pairs of request - parameters. - * @return The Dto instance returned from API. - */ - public T request(Class classOfT, String urlMethod, String requestType, Map requestData) throws Exception { - return request(classOfT, urlMethod, requestType, requestData, null, null); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting single - * Dto instances. In order to process collections of objects, - * use requestList method instead. - * @param - * @param classOfT The class on behalf of which the request is being - called. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term, one of the GET, PUT or POST. - * @param requestData Collection of key-value pairs of request - parameters. - * @param pagination Pagination object. - * @return The Dto instance returned from API. - */ - public T request(Class classOfT, String urlMethod, String requestType, Map requestData, Pagination pagination) throws Exception { - return request(classOfT, urlMethod, requestType, requestData, pagination, null); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting collections of - * Dto instances. In order to process single objects, - * use request method instead. - * @param - * @param classOfT The array class on behalf of which the request is - being called. - * @param classOfTItem The class of single item in array. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term. For lists should be always GET. - * @param requestData Collection of key-value pairs of request - parameters. - * @param pagination Pagination object. - * @param additionalUrlParams - * @return The collection of Dto instances returned from API. - * @throws Exception - */ - public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData, Pagination pagination, Map additionalUrlParams) throws Exception { - - this._requestType = requestType; - this._requestData = requestData; - - List responseResult = this.doRequestList(classOfT, classOfTItem, urlMethod, pagination, additionalUrlParams); - - if(pagination != null){ - pagination = this._pagination; - } - - return responseResult; - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting collections of - * Dto instances. In order to process single objects, - * use request method instead. - * @param - * @param classOfT The array class on behalf of which the request is - being called. - * @param classOfTItem The class of single item in array. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term. For lists should be always GET. - * @return The collection of Dto instances returned from API. - * @throws Exception - */ - public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType) throws Exception { - return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting collections of - * Dto instances. In order to process single objects, - * use request method instead. - * @param - * @param classOfT The array class on behalf of which the request is - being called. - * @param classOfTItem The class of single item in array. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term. For lists should be always GET. - * @param requestData Collection of key-value pairs of request - parameters. - * @return The collection of Dto instances returned from API. - * @throws Exception - */ - public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData) throws Exception { - return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, null, null); - } - - /** - * Makes a call to the MangoPay API. - *

- * This generic method handles calls targeting collections of - * Dto instances. In order to process single objects, - * use request method instead. - * @param - * @param classOfT The array class on behalf of which the request is - being called. - * @param classOfTItem The class of single item in array. - * @param urlMethod Relevant method key. - * @param requestType HTTP request term. For lists should be always GET. - * @param requestData Collection of key-value pairs of request - parameters. - * @param pagination Pagination object. - * @return The collection of Dto instances returned from API. - * @throws Exception - */ - public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData, Pagination pagination) throws Exception { - return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, pagination, null); - } - - /** - * - * @param - * @param classOfT - * @param urlMethod - * @param pagination - * @return - * @throws Exception - */ - private T doRequest(Class classOfT, String urlMethod, Pagination pagination) throws Exception { - return doRequest(classOfT, urlMethod, pagination, null); - } - - /** - * - * @param - * @param classOfT - * @param urlMethod - * @param pagination - * @param entity - * @return - * @throws Exception - */ - private T doRequest(Class classOfT, String urlMethod, Pagination pagination, T entity) throws Exception { - - T response = null; - - try { - UrlTool urlTool = new UrlTool(_root); - String restUrl = urlTool.getRestUrl(urlMethod, this._authRequired, pagination, null); - - URL url = new URL(urlTool.getFullUrl(restUrl)); - - - - if (this._debugMode) { - Logs.debug("FullUrl", urlTool.getFullUrl(restUrl)); - } - - _connection = (HttpURLConnection)url.openConnection(); - - // set request method - _connection.setRequestMethod(this._requestType); - - // set headers - Map httpHeaders = this.getHttpHeaders(restUrl); - - for (Entry entry : httpHeaders.entrySet()) { - _connection.addRequestProperty(entry.getKey(), entry.getValue()); - - if (this._debugMode) - Logs.debug("HTTP Header", entry.getKey() + ": " + entry.getValue()); - } - - // prepare to go - _connection.setUseCaches (false); - _connection.setDoInput(true); - _connection.setDoOutput(true); - - if (pagination != null) { - this._pagination = pagination; - } - - if (this._debugMode) - Logs.debug("RequestType", this._requestType); - - if (this._requestData != null || entity != null) { - - String requestBody = ""; - if (entity != null) { - HashMap requestData = buildRequestData(classOfT, entity); - - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - requestBody = gson.toJson(requestData); - } - if (this._requestData != null) { - String params = ""; - for (Entry entry : this._requestData.entrySet()) { - params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); - } - requestBody = params.replaceFirst("&", ""); - } - - if (this._debugMode) { - Logs.debug("RequestData", this._requestData); - Logs.debug("RequestBody", requestBody); - } - - try (DataOutputStream wr = new DataOutputStream(_connection.getOutputStream())) { - wr.writeBytes(requestBody); - wr.flush (); - } - } - - - // get response - this._responseCode = _connection.getResponseCode(); - InputStream is; - if (this._responseCode != 200 && this._responseCode != 204) { - is = _connection.getErrorStream(); - } else { - is = _connection.getInputStream(); - } - - StringBuffer resp; - try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { - String line; - resp = new StringBuffer(); - while((line = rd.readLine()) != null) { - resp.append(line); - } - } - String responseString = resp.toString(); - - if (this._debugMode) { - if (this._responseCode == 200 || this._responseCode == 204) { - Logs.debug("Response OK", responseString); - } else { - Logs.debug("Response ERROR", responseString); - } - } - - if (this._responseCode == 200) { - - this.readResponseHeaders(_connection); - - response = castResponseToEntity(classOfT, new JsonParser().parse(responseString).getAsJsonObject()); - - if (this._debugMode) Logs.debug("Response object", response.toString()); - } - - this.checkResponseCode(responseString); - - } - catch (Exception ex) { - //ex.printStackTrace(); - if (this._debugMode) Logs.debug("EXCEPTION", Arrays.toString(ex.getStackTrace())); - throw ex; - } - - return response; - } - - /** - * - * @param conn - */ - private void readResponseHeaders(HttpURLConnection conn) { - for (Map.Entry> k : conn.getHeaderFields().entrySet()) { - for (String v : k.getValue()){ - - if (this._debugMode) Logs.debug("Response header", k.getKey() + ":" + v); - - if (k.getKey() == null) continue; - - if (k.getKey().equals("X-Number-Of-Pages")) { - this._pagination.TotalPages = Integer.parseInt(v); - } - if (k.getKey().equals("X-Number-Of-Items")) { - this._pagination.TotalItems = Integer.parseInt(v); - } - if (k.getKey().equals("Link")) { - String linkValue = v; - String[] links = linkValue.split(","); - - if (links != null && links.length > 0) { - for (String link : links) { - link = link.replaceAll(Matcher.quoteReplacement("<\""), ""); - link = link.replaceAll(Matcher.quoteReplacement("\">"), ""); - link = link.replaceAll(Matcher.quoteReplacement(" rel=\""), ""); - link = link.replaceAll(Matcher.quoteReplacement("\""), ""); - - String[] oneLink = link.split(";"); - - if (oneLink != null && oneLink.length > 1) { - if (oneLink[0] != null && oneLink[1] != null) { - this._pagination.Links = oneLink; - } - } - } - } - } - } - } - } - - /** - * - * @param - * @param classOfT - * @param entity - * @return - */ - private HashMap buildRequestData(Class classOfT, T entity) { - HashMap result = new HashMap<>(); - - ArrayList readOnlyProperties = entity.getReadOnlyProperties(); - - String fieldName = ""; - for (Field f : entity.getClass().getFields()) { - - boolean isList = false; - for (Class i : f.getType().getInterfaces()) { - if (i.getName().equals("java.util.List")) { - isList = true; - break; - } - } - - fieldName = f.getName(); - - boolean isReadOnly = false; - for (String s : readOnlyProperties) { - if (s.equals(fieldName)) { - isReadOnly = true; - break; - } - } - if (isReadOnly) continue; - - - if (canReadSubRequestData(classOfT, fieldName)) { - HashMap subRequestData = new HashMap<>(); - - try { - Method m = RestTool.class.getDeclaredMethod("buildRequestData", Class.class, Dto.class); - subRequestData = (HashMap)m.invoke(this, f.getType(), f.get(entity)); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { - Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, ex); - } - - for (Entry e : subRequestData.entrySet()) { - result.put(e.getKey(), e.getValue()); - } - } else { - try { - if (!isList) { - result.put(fieldName, f.get(entity)); - } - else { - result.put(fieldName, ((List)f.get(entity)).toArray()); - } - } catch (IllegalArgumentException | IllegalAccessException ex) { - continue; - } - } - - } - - return result; - } - - /** - * - * @param - * @param classOfT - * @param fieldName - * @return - */ - private Boolean canReadSubRequestData(Class classOfT, String fieldName) { - - if (classOfT.getName().equals(PayIn.class.getName()) && - (fieldName.equals("PaymentDetails") || fieldName.equals("ExecutionDetails"))) { - return true; - } - - if (classOfT.getName().equals(PayOut.class.getName()) && fieldName.equals("MeanOfPaymentDetails")) { - return true; - } - - return false; - - } - - /** - * - * @param - * @param classOfT - * @param response - * @return - * @throws Exception - */ - private T castResponseToEntity(Class classOfT, JsonObject response) throws Exception { - return castResponseToEntity(classOfT, response, false); - } - - /** - * - * @param - * @param classOfT - * @param response - * @param asDependentObject - * @return - * @throws Exception - */ - private T castResponseToEntity(Class classOfT, JsonObject response, boolean asDependentObject) throws Exception { - - try { - - if (_debugMode) { - Logs.debug("Entity type", classOfT.getName()); - } - - T result = null; - - if (classOfT.getName().equals(User.class.getName())) { - for (Entry entry : response.entrySet()) { - - if (entry.getKey().equals("PersonType")) { - switch (entry.getValue().getAsString()) { - case User.Types.Natural: - result = (T) new UserNatural(); - break; - case User.Types.Legal: - result = (T) new UserLegal(); - break; - default: - throw new Exception(String.format("Unknown type of user: %s", entry.getValue().getAsString())); - } - } - - } - } else { - result = classOfT.newInstance(); - } - - Map subObjects = ((Dto)result).getSubObjects(); - Map>>> dependentObjects = ((Dto)result).getDependentObjects(); - - //for (Field f : classOfT.getFields()) { - for (Field f : result.getClass().getFields()) { - String name = f.getName(); - - boolean isList = false; - for (Class i : f.getType().getInterfaces()) { - if (i.getName().equals("java.util.List")) { - isList = true; - break; - } - } - - // does this field have dependent objects? - if (!asDependentObject && dependentObjects.containsKey(name)) { - Map>> allowedTypes = dependentObjects.get(name); - - for (Entry entry : response.entrySet()) { - if (entry.getKey().equals(name)) { - String paymentTypeDef = entry.getValue().getAsString(); - - if (allowedTypes.containsKey(paymentTypeDef)) { - Map> targetObjectsDef = allowedTypes.get(paymentTypeDef); - - for (Entry> e : targetObjectsDef.entrySet()) { - - Field targetField = classOfT.getDeclaredField(e.getKey()); - - if (isList) { - targetField.set(result, Arrays.asList(castResponseToEntity(e.getValue(), response, true))); - } else { - targetField.set(result, castResponseToEntity(e.getValue(), response, true)); - } - } - } - - break; - } - } - - //continue; - } - - for (Entry entry : response.entrySet()) { - - if (entry.getKey().equals(name)) { - - // is sub object? - if (subObjects.containsKey(name)) { - f.set(result, castResponseToEntity(f.getType(), entry.getValue().getAsJsonObject())); - break; - } - - String fieldTypeName = f.getType().getName(); - boolean fieldIsArray = false; - for (Class i : f.getType().getInterfaces()) { - if (i.getName().equals("java.util.List")) { - fieldIsArray = true; - break; - } - } - - if (_debugMode) { - Logs.debug("Recognized field", String.format("[%s] %s%s", name, fieldTypeName, fieldIsArray ? "[]" : "")); - } - - if (fieldIsArray) { - ParameterizedType genericType = (ParameterizedType) f.getGenericType(); - Class genericTypeClass = (Class) genericType.getActualTypeArguments()[0]; - - if (entry.getValue().isJsonArray()) { - JsonArray ja = entry.getValue().getAsJsonArray(); - Iterator i = ja.iterator(); - Class classOfList = Class.forName(fieldTypeName); - Method addMethod = classOfList.getDeclaredMethod("add", Object.class); - Method toArrayMethod = classOfList.getDeclaredMethod("add", Object.class); - Object o = classOfList.newInstance(); - while (i.hasNext()) { - JsonElement e = i.next(); - - if (genericTypeClass.getName().equals(String.class.getName())) { - addMethod.invoke(o, e.getAsJsonPrimitive().getAsString()); - } else if (genericTypeClass.getName().equals(int.class.getName())) { - addMethod.invoke(o, e.getAsJsonPrimitive().getAsInt()); - } else if (genericTypeClass.getName().equals(long.class.getName())) { - addMethod.invoke(o, e.getAsJsonPrimitive().getAsLong()); - } else if (genericTypeClass.getName().equals(Double.class.getName())) { - addMethod.invoke(o, e.getAsJsonPrimitive().getAsDouble()); - } - } - f.set(result, o); - } - } else { - if (!entry.getValue().isJsonNull()) { - if (fieldTypeName.equals(int.class.getName())) { - f.setInt(result, entry.getValue().getAsInt()); - } else if (fieldTypeName.equals(long.class.getName())) { - f.setLong(result, entry.getValue().getAsLong()); - } else if (fieldTypeName.equals(Double.class.getName())) { - f.set(result, entry.getValue().getAsDouble()); - } else if (fieldTypeName.equals(String.class.getName())) { - f.set(result, entry.getValue().getAsString()); - } - } - - break; - } - } - - } - - } - - return result; - -// } catch (InstantiationException | IllegalAccessException ex) { -// Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, ex); -// throw new Exception("Cannot cast response to entity object. Wrong entity class name"); - } catch (Exception e) { - Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, e); - throw new Exception(e); - } - - } - - /** - * - * @param - * @param classOfT - * @param classOfTItem - * @param urlMethod - * @param pagination - * @return - * @throws Exception - */ - private List doRequestList(Class classOfT, Class classOfTItem, String urlMethod, Pagination pagination) throws Exception { - return doRequestList(classOfT, classOfTItem, urlMethod, pagination, null); - } - - /** - * - * @param - * @param classOfT - * @param classOfTItem - * @param urlMethod - * @param pagination - * @param additionalUrlParams - * @return - * @throws Exception - */ - private List doRequestList(Class classOfT, Class classOfTItem, String urlMethod, Pagination pagination, Map additionalUrlParams) throws Exception { - - List response = new ArrayList<>(); - - try { - UrlTool urlTool = new UrlTool(_root); - String restUrl = urlTool.getRestUrl(urlMethod, this._authRequired, pagination, additionalUrlParams); - - URL url = new URL(urlTool.getFullUrl(restUrl)); - - - - if (this._debugMode) - Logs.debug("FullUrl", urlTool.getFullUrl(restUrl)); - - _connection = (HttpURLConnection)url.openConnection(); - - // set request method - _connection.setRequestMethod(this._requestType); - - // set headers - Map httpHeaders = this.getHttpHeaders(restUrl); - - for (Entry entry : httpHeaders.entrySet()) { - _connection.addRequestProperty(entry.getKey(), entry.getValue()); - - if (this._debugMode) - Logs.debug("HTTP Header", entry.getKey() + ": " + entry.getValue()); - } - - // prepare to go - _connection.setUseCaches (false); - _connection.setDoInput(true); - _connection.setDoOutput(true); - - if (pagination != null) { - this._pagination = pagination; - } - - if (this._debugMode) - Logs.debug("RequestType", this._requestType); - - if (this._requestData != null) { - - String requestBody; - String params = ""; - for (Entry entry : this._requestData.entrySet()) { - params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); - } - requestBody = params.replaceFirst("&", ""); - - try (DataOutputStream wr = new DataOutputStream (_connection.getOutputStream())) { - wr.writeBytes(requestBody); - wr.flush(); - } - - if (this._debugMode) { - Logs.debug("RequestData", this._requestData); - Logs.debug("RequestBody", requestBody); - } - } - - - //Get Response - this._responseCode = _connection.getResponseCode(); - InputStream is; - if (this._responseCode != 200) { - is = _connection.getErrorStream(); - } else { - is = _connection.getInputStream(); - } - - StringBuffer resp; - try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { - String line; - resp = new StringBuffer(); - while((line = rd.readLine()) != null) { - resp.append(line); - resp.append('\r'); - } - } - String responseString = resp.toString(); - - if (this._debugMode) { - if (this._responseCode == 200) { - Logs.debug("Response OK", responseString); - } else { - Logs.debug("Response ERROR", responseString); - } - } - - if (this._responseCode == 200) { - - this.readResponseHeaders(_connection); - - JsonArray ja = new JsonParser().parse(responseString).getAsJsonArray(); - - for (int x = 0; x < ja.size(); x++) { - JsonObject jo = ja.get(x).getAsJsonObject(); - T toAdd = castResponseToEntity(classOfTItem, jo); - response.add(toAdd); - } - - if (this._debugMode) { - Logs.debug("Response object", response.toString()); - Logs.debug("Elements count", response.size()); - } - } - - this.checkResponseCode(responseString); - - } - catch (Exception ex) { - //ex.printStackTrace(); - if (this._debugMode) Logs.debug("EXCEPTION", Arrays.toString(ex.getStackTrace())); - throw ex; - } - - return response; - - } - - /** - * Gets HTTP header to use in request. - * @param restUrl The REST API URL. - * @return Array containing HTTP headers. - */ - private Map getHttpHeaders(String restUrl) throws Exception { - // return if already created... - if (this._requestHttpHeaders != null) - return this._requestHttpHeaders; - - // ...or initialize with default headers - Map httpHeaders = new HashMap<>(); - - // content type - httpHeaders.put("Content-Type", "application/json"); - - // AuthenticationHelper http header - if (this._authRequired) { - AuthenticationHelper authHlp = new AuthenticationHelper(_root); - httpHeaders.putAll(authHlp.getHttpHeaderKey()); - } - - return httpHeaders; - } - - /** - * Checks response HTTP code. - * @throws ResponseException If response code is not 200 (OK) - */ - private void checkResponseCode(String message) throws ResponseException { - - if (this._responseCode != 200 && this._responseCode != 204) { - - HashMap responseCodes = new HashMap() {{ - put(206, "PartialContent"); - put(400, "Bad request"); - put(401, "Unauthorized"); - put(403, "Prohibition to use the method"); - put(404, "Not found"); - put(405, "Method not allowed"); - put(413, "Request entity too large"); - put(422, "Unprocessable entity"); - put(500, "Internal server error"); - put(501, "Not implemented"); - }}; - - String errorMsg = ""; - if (responseCodes.containsKey(this._responseCode)) { - errorMsg = responseCodes.get(this._responseCode); - } else { - errorMsg = "Unknown response error"; - } - - if (message != null) { - errorMsg += ". " + message; - } - - throw new ResponseException(errorMsg); - } - } - -} +package com.mangopay.core; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.mangopay.MangoPayApi; +import com.mangopay.entities.BankAccount; +import com.mangopay.entities.PayIn; +import com.mangopay.entities.PayOut; +import com.mangopay.entities.User; +import com.mangopay.entities.UserLegal; +import com.mangopay.entities.UserNatural; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; + +/** + * Class to prepare HTTP request, call the request and decode the response + */ +public class RestTool { + + /** + * Root/parent instance that holds the OAuthToken and Configuration instance + */ + private MangoPayApi _root; + + /** + * Variable to switch on/off log debugging + */ + private Boolean _debugMode; + + /** + * Variable to flag that in request authentication data are required + */ + private Boolean _authRequired; + + /** + * Array with HTTP header to send with request + */ + private Map _requestHttpHeaders; + + /** + * + */ + private HttpURLConnection _connection; + + /** + * Request type for current request + */ + private String _requestType; + + /** + * Key-value collection pass in the request + */ + private Map _requestData; + + /** + * Code get from response + */ + private int _responseCode; + + /** + * Pagination object + */ + private Pagination _pagination; + + /** + * Creates new RestTool object. + * @param root Root/parent instance that holds the OAuthToken and Configuration instance. + * @param authRequired Defines whether request authentication is required. + */ + public RestTool(MangoPayApi root, Boolean authRequired) throws Exception { + this._root = root; + this._authRequired = authRequired; + this._debugMode = this._root.Config.DebugMode; + } + + /** + * + * @param httpHeader + */ + public void addRequestHttpHeader(Map httpHeader) { + + if (this._requestHttpHeaders == null) + this._requestHttpHeaders = new HashMap<>(); + + this._requestHttpHeaders.putAll(httpHeader); + } + + /** + * + * @param key + * @param value + */ + public void addRequestHttpHeader(final String key, final String value) { + addRequestHttpHeader(new HashMap(){{ + put(key, value); + }}); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting single + * Dto instances. In order to process collections of objects, + * use requestList method instead. + * @param + * @param classOfT The class on behalf of which the request is being + called. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term, one of the GET, PUT or POST. + * @param requestData Collection of key-value pairs of request + parameters. + * @param pagination Pagination object. + * @param entity Instance of Dto class that is going to be + sent in case of PUTting or POSTing. + * @return The Dto instance returned from API. + */ + public T request(Class classOfT, String urlMethod, String requestType, Map requestData, Pagination pagination, T entity) throws Exception { + + this._requestType = requestType; + this._requestData = requestData; + + T responseResult = this.doRequest(classOfT, urlMethod, pagination, entity); + + if(pagination != null){ + pagination = this._pagination; + } + + return responseResult; + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting single + * Dto instances. In order to process collections of objects, + * use requestList method instead. + * @param + * @param classOfT The class on behalf of which the request is being + called. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term, one of the GET, PUT or POST. + * @return The Dto instance returned from API. + */ + public T request(Class classOfT, String urlMethod, String requestType) throws Exception { + return request(classOfT, urlMethod, requestType, null, null, null); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting single + * Dto instances. In order to process collections of objects, + * use requestList method instead. + * @param + * @param classOfT The class on behalf of which the request is being + called. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term, one of the GET, PUT or POST. + * @param requestData Collection of key-value pairs of request + parameters. + * @return The Dto instance returned from API. + */ + public T request(Class classOfT, String urlMethod, String requestType, Map requestData) throws Exception { + return request(classOfT, urlMethod, requestType, requestData, null, null); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting single + * Dto instances. In order to process collections of objects, + * use requestList method instead. + * @param + * @param classOfT The class on behalf of which the request is being + called. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term, one of the GET, PUT or POST. + * @param requestData Collection of key-value pairs of request + parameters. + * @param pagination Pagination object. + * @return The Dto instance returned from API. + */ + public T request(Class classOfT, String urlMethod, String requestType, Map requestData, Pagination pagination) throws Exception { + return request(classOfT, urlMethod, requestType, requestData, pagination, null); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting collections of + * Dto instances. In order to process single objects, + * use request method instead. + * @param + * @param classOfT The array class on behalf of which the request is + being called. + * @param classOfTItem The class of single item in array. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term. For lists should be always GET. + * @param requestData Collection of key-value pairs of request + parameters. + * @param pagination Pagination object. + * @param additionalUrlParams + * @return The collection of Dto instances returned from API. + * @throws Exception + */ + public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData, Pagination pagination, Map additionalUrlParams) throws Exception { + + this._requestType = requestType; + this._requestData = requestData; + + List responseResult = this.doRequestList(classOfT, classOfTItem, urlMethod, pagination, additionalUrlParams); + + if(pagination != null){ + pagination = this._pagination; + } + + return responseResult; + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting collections of + * Dto instances. In order to process single objects, + * use request method instead. + * @param + * @param classOfT The array class on behalf of which the request is + being called. + * @param classOfTItem The class of single item in array. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term. For lists should be always GET. + * @return The collection of Dto instances returned from API. + * @throws Exception + */ + public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType) throws Exception { + return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting collections of + * Dto instances. In order to process single objects, + * use request method instead. + * @param + * @param classOfT The array class on behalf of which the request is + being called. + * @param classOfTItem The class of single item in array. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term. For lists should be always GET. + * @param requestData Collection of key-value pairs of request + parameters. + * @return The collection of Dto instances returned from API. + * @throws Exception + */ + public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData) throws Exception { + return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, null, null); + } + + /** + * Makes a call to the MangoPay API. + *

+ * This generic method handles calls targeting collections of + * Dto instances. In order to process single objects, + * use request method instead. + * @param + * @param classOfT The array class on behalf of which the request is + being called. + * @param classOfTItem The class of single item in array. + * @param urlMethod Relevant method key. + * @param requestType HTTP request term. For lists should be always GET. + * @param requestData Collection of key-value pairs of request + parameters. + * @param pagination Pagination object. + * @return The collection of Dto instances returned from API. + * @throws Exception + */ + public List requestList(Class classOfT, Class classOfTItem, String urlMethod, String requestType, Map requestData, Pagination pagination) throws Exception { + return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, pagination, null); + } + + /** + * + * @param + * @param classOfT + * @param urlMethod + * @param pagination + * @return + * @throws Exception + */ + private T doRequest(Class classOfT, String urlMethod, Pagination pagination) throws Exception { + return doRequest(classOfT, urlMethod, pagination, null); + } + + /** + * + * @param + * @param classOfT + * @param urlMethod + * @param pagination + * @param entity + * @return + * @throws Exception + */ + private T doRequest(Class classOfT, String urlMethod, Pagination pagination, T entity) throws Exception { + + T response = null; + + try { + UrlTool urlTool = new UrlTool(_root); + String restUrl = urlTool.getRestUrl(urlMethod, this._authRequired, pagination, null); + + URL url = new URL(urlTool.getFullUrl(restUrl)); + + + + if (this._debugMode) { + Logs.debug("FullUrl", urlTool.getFullUrl(restUrl)); + } + + _connection = (HttpURLConnection)url.openConnection(); + + // set request method + _connection.setRequestMethod(this._requestType); + + // set headers + Map httpHeaders = this.getHttpHeaders(restUrl); + + for (Entry entry : httpHeaders.entrySet()) { + _connection.addRequestProperty(entry.getKey(), entry.getValue()); + + if (this._debugMode) + Logs.debug("HTTP Header", entry.getKey() + ": " + entry.getValue()); + } + + // prepare to go + _connection.setUseCaches (false); + _connection.setDoInput(true); + _connection.setDoOutput(true); + + if (pagination != null) { + this._pagination = pagination; + } + + if (this._debugMode) + Logs.debug("RequestType", this._requestType); + + if (this._requestData != null || entity != null) { + + String requestBody = ""; + if (entity != null) { + HashMap requestData = buildRequestData(classOfT, entity); + + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + requestBody = gson.toJson(requestData); + } + if (this._requestData != null) { + String params = ""; + for (Entry entry : this._requestData.entrySet()) { + params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); + } + requestBody = params.replaceFirst("&", ""); + } + + if (this._debugMode) { + Logs.debug("RequestData", this._requestData); + Logs.debug("RequestBody", requestBody); + } + + try (DataOutputStream wr = new DataOutputStream(_connection.getOutputStream())) { + wr.writeBytes(requestBody); + wr.flush (); + } + } + + + // get response + this._responseCode = _connection.getResponseCode(); + InputStream is; + if (this._responseCode != 200 && this._responseCode != 204) { + is = _connection.getErrorStream(); + } else { + is = _connection.getInputStream(); + } + + StringBuffer resp; + try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { + String line; + resp = new StringBuffer(); + while((line = rd.readLine()) != null) { + resp.append(line); + } + } + String responseString = resp.toString(); + + if (this._debugMode) { + if (this._responseCode == 200 || this._responseCode == 204) { + Logs.debug("Response OK", responseString); + } else { + Logs.debug("Response ERROR", responseString); + } + } + + if (this._responseCode == 200) { + + this.readResponseHeaders(_connection); + + response = castResponseToEntity(classOfT, new JsonParser().parse(responseString).getAsJsonObject()); + + if (this._debugMode) Logs.debug("Response object", response.toString()); + } + + this.checkResponseCode(responseString); + + } + catch (Exception ex) { + //ex.printStackTrace(); + if (this._debugMode) Logs.debug("EXCEPTION", Arrays.toString(ex.getStackTrace())); + throw ex; + } + + return response; + } + + /** + * + * @param conn + */ + private void readResponseHeaders(HttpURLConnection conn) { + for (Map.Entry> k : conn.getHeaderFields().entrySet()) { + for (String v : k.getValue()){ + + if (this._debugMode) Logs.debug("Response header", k.getKey() + ":" + v); + + if (k.getKey() == null) continue; + + if (k.getKey().equals("X-Number-Of-Pages")) { + this._pagination.TotalPages = Integer.parseInt(v); + } + if (k.getKey().equals("X-Number-Of-Items")) { + this._pagination.TotalItems = Integer.parseInt(v); + } + if (k.getKey().equals("Link")) { + String linkValue = v; + String[] links = linkValue.split(","); + + if (links != null && links.length > 0) { + for (String link : links) { + link = link.replaceAll(Matcher.quoteReplacement("<\""), ""); + link = link.replaceAll(Matcher.quoteReplacement("\">"), ""); + link = link.replaceAll(Matcher.quoteReplacement(" rel=\""), ""); + link = link.replaceAll(Matcher.quoteReplacement("\""), ""); + + String[] oneLink = link.split(";"); + + if (oneLink != null && oneLink.length > 1) { + if (oneLink[0] != null && oneLink[1] != null) { + this._pagination.Links = oneLink; + } + } + } + } + } + } + } + } + + /** + * + * @param + * @param classOfT + * @param entity + * @return + */ + private HashMap buildRequestData(Class classOfT, T entity) { + HashMap result = new HashMap<>(); + + ArrayList readOnlyProperties = entity.getReadOnlyProperties(); + + String fieldName = ""; + for (Field f : entity.getClass().getFields()) { + + boolean isList = false; + for (Class i : f.getType().getInterfaces()) { + if (i.getName().equals("java.util.List")) { + isList = true; + break; + } + } + + fieldName = f.getName(); + + boolean isReadOnly = false; + for (String s : readOnlyProperties) { + if (s.equals(fieldName)) { + isReadOnly = true; + break; + } + } + if (isReadOnly) continue; + + + if (canReadSubRequestData(classOfT, fieldName)) { + HashMap subRequestData = new HashMap<>(); + + try { + Method m = RestTool.class.getDeclaredMethod("buildRequestData", Class.class, Dto.class); + subRequestData = (HashMap)m.invoke(this, f.getType(), f.get(entity)); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { + Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, ex); + } + + for (Entry e : subRequestData.entrySet()) { + result.put(e.getKey(), e.getValue()); + } + } else { + try { + if (!isList) { + result.put(fieldName, f.get(entity)); + } + else { + result.put(fieldName, ((List)f.get(entity)).toArray()); + } + } catch (IllegalArgumentException | IllegalAccessException ex) { + continue; + } + } + + } + + return result; + } + + /** + * + * @param + * @param classOfT + * @param fieldName + * @return + */ + private Boolean canReadSubRequestData(Class classOfT, String fieldName) { + + if (classOfT.getName().equals(PayIn.class.getName()) && + (fieldName.equals("PaymentDetails") || fieldName.equals("ExecutionDetails"))) { + return true; + } + + if (classOfT.getName().equals(PayOut.class.getName()) && fieldName.equals("MeanOfPaymentDetails")) { + return true; + } + + if (classOfT.getName().equals(BankAccount.class.getName()) && fieldName.equals("Details")) { + return true; + } + + return false; + + } + + /** + * + * @param + * @param classOfT + * @param response + * @return + * @throws Exception + */ + private T castResponseToEntity(Class classOfT, JsonObject response) throws Exception { + return castResponseToEntity(classOfT, response, false); + } + + /** + * + * @param + * @param classOfT + * @param response + * @param asDependentObject + * @return + * @throws Exception + */ + private T castResponseToEntity(Class classOfT, JsonObject response, boolean asDependentObject) throws Exception { + + try { + + if (_debugMode) { + Logs.debug("Entity type", classOfT.getName()); + } + + T result = null; + + if (classOfT.getName().equals(User.class.getName())) { + for (Entry entry : response.entrySet()) { + + if (entry.getKey().equals("PersonType")) { + switch (entry.getValue().getAsString()) { + case User.Types.Natural: + result = (T) new UserNatural(); + break; + case User.Types.Legal: + result = (T) new UserLegal(); + break; + default: + throw new Exception(String.format("Unknown type of user: %s", entry.getValue().getAsString())); + } + } + + } + } else { + result = classOfT.newInstance(); + } + + Map subObjects = ((Dto)result).getSubObjects(); + Map>>> dependentObjects = ((Dto)result).getDependentObjects(); + + //for (Field f : classOfT.getFields()) { + for (Field f : result.getClass().getFields()) { + String name = f.getName(); + + boolean isList = false; + for (Class i : f.getType().getInterfaces()) { + if (i.getName().equals("java.util.List")) { + isList = true; + break; + } + } + + // does this field have dependent objects? + if (!asDependentObject && dependentObjects.containsKey(name)) { + Map>> allowedTypes = dependentObjects.get(name); + + for (Entry entry : response.entrySet()) { + if (entry.getKey().equals(name)) { + String paymentTypeDef = entry.getValue().getAsString(); + + if (allowedTypes.containsKey(paymentTypeDef)) { + Map> targetObjectsDef = allowedTypes.get(paymentTypeDef); + + for (Entry> e : targetObjectsDef.entrySet()) { + + Field targetField = classOfT.getDeclaredField(e.getKey()); + + if (isList) { + targetField.set(result, Arrays.asList(castResponseToEntity(e.getValue(), response, true))); + } else { + targetField.set(result, castResponseToEntity(e.getValue(), response, true)); + } + } + } + + break; + } + } + + //continue; + } + + for (Entry entry : response.entrySet()) { + + if (entry.getKey().equals(name)) { + + // is sub object? + if (subObjects.containsKey(name)) { + if (entry.getValue() instanceof JsonNull) { + f.set(result, null); + } + else { + f.set(result, castResponseToEntity(f.getType(), entry.getValue().getAsJsonObject())); + } + break; + } + + String fieldTypeName = f.getType().getName(); + boolean fieldIsArray = false; + for (Class i : f.getType().getInterfaces()) { + if (i.getName().equals("java.util.List")) { + fieldIsArray = true; + break; + } + } + + if (_debugMode) { + Logs.debug("Recognized field", String.format("[%s] %s%s", name, fieldTypeName, fieldIsArray ? "[]" : "")); + } + + if (fieldIsArray) { + ParameterizedType genericType = (ParameterizedType) f.getGenericType(); + Class genericTypeClass = (Class) genericType.getActualTypeArguments()[0]; + + if (entry.getValue().isJsonArray()) { + JsonArray ja = entry.getValue().getAsJsonArray(); + Iterator i = ja.iterator(); + Class classOfList = Class.forName(fieldTypeName); + Method addMethod = classOfList.getDeclaredMethod("add", Object.class); + Method toArrayMethod = classOfList.getDeclaredMethod("add", Object.class); + Object o = classOfList.newInstance(); + while (i.hasNext()) { + JsonElement e = i.next(); + + if (genericTypeClass.getName().equals(String.class.getName())) { + addMethod.invoke(o, e.getAsJsonPrimitive().getAsString()); + } else if (genericTypeClass.getName().equals(int.class.getName())) { + addMethod.invoke(o, e.getAsJsonPrimitive().getAsInt()); + } else if (genericTypeClass.getName().equals(long.class.getName())) { + addMethod.invoke(o, e.getAsJsonPrimitive().getAsLong()); + } else if (genericTypeClass.getName().equals(Double.class.getName())) { + addMethod.invoke(o, e.getAsJsonPrimitive().getAsDouble()); + } + } + f.set(result, o); + } + } else { + if (!entry.getValue().isJsonNull()) { + if (fieldTypeName.equals(int.class.getName())) { + f.setInt(result, entry.getValue().getAsInt()); + } else if (fieldTypeName.equals(long.class.getName())) { + f.setLong(result, entry.getValue().getAsLong()); + } else if (fieldTypeName.equals(Double.class.getName())) { + f.set(result, entry.getValue().getAsDouble()); + } else if (fieldTypeName.equals(String.class.getName())) { + f.set(result, entry.getValue().getAsString()); + } + } + + break; + } + } + + } + + } + + return result; + +// } catch (InstantiationException | IllegalAccessException ex) { +// Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, ex); +// throw new Exception("Cannot cast response to entity object. Wrong entity class name"); + } catch (Exception e) { + Logger.getLogger(RestTool.class.getName()).log(Level.SEVERE, null, e); + //throw new Exception(e); + throw e; + } + + } + + /** + * + * @param + * @param classOfT + * @param classOfTItem + * @param urlMethod + * @param pagination + * @return + * @throws Exception + */ + private List doRequestList(Class classOfT, Class classOfTItem, String urlMethod, Pagination pagination) throws Exception { + return doRequestList(classOfT, classOfTItem, urlMethod, pagination, null); + } + + /** + * + * @param + * @param classOfT + * @param classOfTItem + * @param urlMethod + * @param pagination + * @param additionalUrlParams + * @return + * @throws Exception + */ + private List doRequestList(Class classOfT, Class classOfTItem, String urlMethod, Pagination pagination, Map additionalUrlParams) throws Exception { + + List response = new ArrayList<>(); + + try { + UrlTool urlTool = new UrlTool(_root); + String restUrl = urlTool.getRestUrl(urlMethod, this._authRequired, pagination, additionalUrlParams); + + URL url = new URL(urlTool.getFullUrl(restUrl)); + + if (this._debugMode) + Logs.debug("FullUrl", urlTool.getFullUrl(restUrl)); + + _connection = (HttpURLConnection)url.openConnection(); + + // set request method + _connection.setRequestMethod(this._requestType); + + // set headers + Map httpHeaders = this.getHttpHeaders(restUrl); + + for (Entry entry : httpHeaders.entrySet()) { + _connection.addRequestProperty(entry.getKey(), entry.getValue()); + + if (this._debugMode) + Logs.debug("HTTP Header", entry.getKey() + ": " + entry.getValue()); + } + + // prepare to go + _connection.setUseCaches (false); + _connection.setDoInput(true); + _connection.setDoOutput(true); + + if (pagination != null) { + this._pagination = pagination; + } + + if (this._debugMode) + Logs.debug("RequestType", this._requestType); + + if (this._requestData != null) { + + String requestBody; + String params = ""; + for (Entry entry : this._requestData.entrySet()) { + params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); + } + requestBody = params.replaceFirst("&", ""); + + try (DataOutputStream wr = new DataOutputStream (_connection.getOutputStream())) { + wr.writeBytes(requestBody); + wr.flush(); + } + + if (this._debugMode) { + Logs.debug("RequestData", this._requestData); + Logs.debug("RequestBody", requestBody); + } + } + + + //Get Response + this._responseCode = _connection.getResponseCode(); + InputStream is; + if (this._responseCode != 200) { + is = _connection.getErrorStream(); + } else { + is = _connection.getInputStream(); + } + + StringBuffer resp; + try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { + String line; + resp = new StringBuffer(); + while((line = rd.readLine()) != null) { + resp.append(line); + resp.append('\r'); + } + } + String responseString = resp.toString(); + + if (this._debugMode) { + if (this._responseCode == 200) { + Logs.debug("Response OK", responseString); + } else { + Logs.debug("Response ERROR", responseString); + } + } + + if (this._responseCode == 200) { + + this.readResponseHeaders(_connection); + + JsonArray ja = new JsonParser().parse(responseString).getAsJsonArray(); + + for (int x = 0; x < ja.size(); x++) { + JsonObject jo = ja.get(x).getAsJsonObject(); + T toAdd = castResponseToEntity(classOfTItem, jo); + response.add(toAdd); + } + + if (this._debugMode) { + Logs.debug("Response object", response.toString()); + Logs.debug("Elements count", response.size()); + } + } + + this.checkResponseCode(responseString); + + } + catch (Exception ex) { + //ex.printStackTrace(); + if (this._debugMode) Logs.debug("EXCEPTION", Arrays.toString(ex.getStackTrace())); + throw ex; + } + + return response; + + } + + /** + * Gets HTTP header to use in request. + * @param restUrl The REST API URL. + * @return Array containing HTTP headers. + */ + private Map getHttpHeaders(String restUrl) throws Exception { + // return if already created... + if (this._requestHttpHeaders != null) + return this._requestHttpHeaders; + + // ...or initialize with default headers + Map httpHeaders = new HashMap<>(); + + // content type + httpHeaders.put("Content-Type", "application/json"); + + // AuthenticationHelper http header + if (this._authRequired) { + AuthenticationHelper authHlp = new AuthenticationHelper(_root); + httpHeaders.putAll(authHlp.getHttpHeaderKey()); + } + + return httpHeaders; + } + + /** + * Checks response HTTP code. + * @throws ResponseException If response code is not 200 (OK) + */ + private void checkResponseCode(String message) throws ResponseException { + + if (this._responseCode != 200 && this._responseCode != 204) { + + HashMap responseCodes = new HashMap() {{ + put(206, "PartialContent"); + put(400, "Bad request"); + put(401, "Unauthorized"); + put(403, "Prohibition to use the method"); + put(404, "Not found"); + put(405, "Method not allowed"); + put(413, "Request entity too large"); + put(422, "Unprocessable entity"); + put(500, "Internal server error"); + put(501, "Not implemented"); + }}; + + String errorMsg = ""; + if (responseCodes.containsKey(this._responseCode)) { + errorMsg = responseCodes.get(this._responseCode); + } else { + errorMsg = "Unknown response error"; + } + + if (message != null) { + errorMsg += ". " + message; + } + + throw new ResponseException(errorMsg); + } + } + +} diff --git a/src/com/mangopay/entities/BankAccount.java b/src/com/mangopay/entities/BankAccount.java index 938c9b8a..505580b4 100644 --- a/src/com/mangopay/entities/BankAccount.java +++ b/src/com/mangopay/entities/BankAccount.java @@ -1,7 +1,15 @@ package com.mangopay.entities; +import com.mangopay.core.BankAccountDetailsCA; +import com.mangopay.core.BankAccountDetailsGB; +import com.mangopay.core.BankAccountDetailsIBAN; +import com.mangopay.core.BankAccountDetailsOTHER; +import com.mangopay.core.BankAccountDetailsUS; import com.mangopay.core.EntityBase; +import com.mangopay.core.IBankAccountDetails; import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; /** * Bank Account entity. @@ -29,14 +37,45 @@ public class BankAccount extends EntityBase { public String OwnerAddress; /** - * IBAN number. + * One of BankAccountDetails implementations, depending on Type. */ - public String IBAN; + public IBankAccountDetails Details; /** - * BIC. + * Gets the structure that maps which property depends on other property. + * @return */ - public String BIC; + @Override + public Map>>> getDependentObjects() { + + return new HashMap>>>(){{ + put("Type", new HashMap>>() + {{ + put("IBAN", new HashMap>() {{ + put("Details", BankAccountDetailsIBAN.class); + }} + ); + put("GB", new HashMap>() {{ + put("Details", BankAccountDetailsGB.class); + }} + ); + put("US", new HashMap>() {{ + put("Details", BankAccountDetailsUS.class); + }} + ); + put("CA", new HashMap>() {{ + put("Details", BankAccountDetailsCA.class); + }} + ); + put("OTHER", new HashMap>() {{ + put("Details", BankAccountDetailsOTHER.class); + }} + ); + // ...and more in future... + }} + ); + }}; + } /** * Gets the collection of read-only fields names @@ -48,6 +87,7 @@ public ArrayList getReadOnlyProperties() { ArrayList result = super.getReadOnlyProperties(); result.add("UserId"); + result.add("Type"); return result; } diff --git a/src/com/mangopay/entities/CardPreAuthorization.java b/src/com/mangopay/entities/CardPreAuthorization.java new file mode 100644 index 00000000..06d8b270 --- /dev/null +++ b/src/com/mangopay/entities/CardPreAuthorization.java @@ -0,0 +1,123 @@ +package com.mangopay.entities; + +import com.mangopay.core.EntityBase; +import com.mangopay.core.Money; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * CardPreAuthorization entity. + */ +public class CardPreAuthorization extends EntityBase { + + /** + * The user Id of the author of the pre-authorization. + */ + public String AuthorId; + + /** + * Represents the amount debited on the bank account + * of the Author. DebitedFunds = Fees + CreditedFunds + * (amount received on wallet) + */ + public Money DebitedFunds; + + /** + * Status of the PreAuthorization: { CREATED, SUCCEEDED, FAILED } + */ + public String Status; + + /** + * The status of the payment after the PreAuthorization: + * { WAITING, CANCELED, EXPIRED, VALIDATED } + */ + public String PaymentStatus; + + /** + * The PreAuthorization result code. + */ + public String ResultCode; + + /** + * The PreAuthorization result Message explaining the result code. + */ + public String ResultMessage; + + /** + * How the PreAuthorization has been executed. + * Only on value for now: CARD + */ + public String ExecutionType; + + /** + * The SecureMode correspond to '3D secure' for CB Visa and MasterCard + * or 'Amex Safe Key' for American Express. + * This field lets you activate it manually. + */ + public String SecureMode; + + /** + * The ID of the registered card (Got through CardRegistration object). + */ + public String CardId; + + /** + * Boolean. The value is 'true' if the SecureMode was used. + */ + public String SecureModeNeeded; + + /** + * This is the URL where to redirect users to proceed + * to 3D secure validation. + */ + public String SecureModeRedirectUrl; + + /** + * This is the URL where users are automatically redirected + * after 3D secure validation (if activated). + */ + public String SecureModeReturnURL; + + /** + * The date when the payment is processed (UNIX timestamp). + */ + public Long ExpirationDate; + + /** + * The Id of the associated PayIn. + */ + public String PayInId; + + /** + * Gets map which property is an object and what type of object. + * To be overridden in child class if has any sub objects. + * @return Collection of field name-field type pairs. + */ + @Override + public Map getSubObjects() { + + HashMap result = new HashMap<>(); + + result.put("DebitedFunds", Money.class); + + return result; + } + + /** + * Gets the collection of read-only fields names. + * @return List of field names. + */ + @Override + public ArrayList getReadOnlyProperties() { + + ArrayList result = super.getReadOnlyProperties(); + + result.add("Status"); + result.add("ResultCode"); + result.add("ResultMessage"); + + return result; + } +} diff --git a/src/com/mangopay/entities/Hook.java b/src/com/mangopay/entities/Hook.java new file mode 100644 index 00000000..c64f65d1 --- /dev/null +++ b/src/com/mangopay/entities/Hook.java @@ -0,0 +1,31 @@ +package com.mangopay.entities; + +import com.mangopay.core.EntityBase; +import com.mangopay.core.EventType; + +/** + * Hooks and Notifications entity. + */ +public class Hook extends EntityBase { + + /** + * This is the URL where you receive notification for each EventType. + */ + public String Url; + + /** + * Status { ENABLED, DISABLED } + */ + public String Status; + + /** + * Validity { VALID, INVALID } + */ + public String Validity; + + /** + * Event type. + */ + public EventType EventType; + +} diff --git a/src/com/mangopay/entities/KycDocument.java b/src/com/mangopay/entities/KycDocument.java index 07fe0f72..5e81ceb1 100644 --- a/src/com/mangopay/entities/KycDocument.java +++ b/src/com/mangopay/entities/KycDocument.java @@ -1,24 +1,25 @@ -package com.mangopay.entities; - -import com.mangopay.core.EntityBase; - -/** - * KYC document entity. - */ -public class KycDocument extends EntityBase { - - /** - * Possible values: { IDENTITY_PROOF, REGISTRATION_PROOF } - */ - public String Type; - - /** - * Possible values: { CREATED, VALIDATION_ASKED, VALIDATED, REFUSED } - */ - public String Status; - - public String RefusedReasonType; - - public String RefusedReasonMessage; - -} +package com.mangopay.entities; + +import com.mangopay.core.EntityBase; + +/** + * KYC document entity. + */ +public class KycDocument extends EntityBase { + + /** + * Possible values: { IDENTITY_PROOF, REGISTRATION_PROOF, + * ARTICLES_OF_ASSOCIATION, SHAREHOLDER_DECLARATION, ADDRESS_PROOF } + */ + public String Type; + + /** + * Possible values: { CREATED, VALIDATION_ASKED, VALIDATED, REFUSED } + */ + public String Status; + + public String RefusedReasonType; + + public String RefusedReasonMessage; + +} diff --git a/src/com/mangopay/entities/PayIn.java b/src/com/mangopay/entities/PayIn.java index 11d00e3d..4140541d 100644 --- a/src/com/mangopay/entities/PayIn.java +++ b/src/com/mangopay/entities/PayIn.java @@ -1,84 +1,92 @@ -package com.mangopay.entities; - -import com.mangopay.core.*; -import java.util.*; - -/** - * PayIn entity. - */ -public class PayIn extends Transaction { - - /** - * Credited wallet identifier. - */ - public String CreditedWalletId; - - /** - * PaymentType {CARD, BANK_WIRE, AUTOMATIC_DEBIT, DIRECT_DEBIT } - */ - public String PaymentType; - - /** - * One of PayInPaymentDetails implementations, depending on PaymentType. - */ - public IPayInPaymentDetails PaymentDetails; - - /** - * ExecutionType { WEB, TOKEN, DIRECT, PREAUTHORIZED, RECURRING_ORDER_EXECUTION } - */ - public String ExecutionType; - - /** - * One of PayInExecutionDetails implementations, depending on ExecutionType. - */ - public IPayInExecutionDetails ExecutionDetails; - - /** - * Gets the structure that maps which property depends on other property. - * To be overridden in child class if has any dependent objects. - * @return - */ - @Override - public Map>>> getDependentObjects() { - - return new HashMap>>>(){{ - put("PaymentType", new HashMap>>() - {{ - put("CARD", new HashMap>() {{ - put("PaymentDetails", PayInPaymentDetailsCard.class); - }} - ); - // ...and more in future... - }} - ); - put("ExecutionType", new HashMap>>() - {{ - put("WEB", new HashMap>() {{ - put("ExecutionDetails", PayInExecutionDetailsWeb.class); - }} - ); - put("DIRECT", new HashMap>() {{ - put("ExecutionDetails", PayInExecutionDetailsDirect.class); - }} - ); - // ...and more in future... - }} - ); - }}; - } - - /** - * Gets the collection of read-only fields names - * @return List of field names. - */ - @Override - public ArrayList getReadOnlyProperties() { - - ArrayList result = super.getReadOnlyProperties(); - - result.add("PaymentType"); - result.add("ExecutionType"); - - return result; - } -} +package com.mangopay.entities; + +import com.mangopay.core.*; +import java.util.*; + +/** + * PayIn entity. + */ +public class PayIn extends Transaction { + + /** + * Credited wallet identifier. + */ + public String CreditedWalletId; + + /** + * PaymentType {CARD, BANK_WIRE, AUTOMATIC_DEBIT, DIRECT_DEBIT } + */ + public String PaymentType; + + /** + * One of PayInPaymentDetails implementations, depending on PaymentType. + */ + public IPayInPaymentDetails PaymentDetails; + + /** + * ExecutionType { WEB, TOKEN, DIRECT, PREAUTHORIZED, RECURRING_ORDER_EXECUTION } + */ + public String ExecutionType; + + /** + * One of PayInExecutionDetails implementations, depending on ExecutionType. + */ + public IPayInExecutionDetails ExecutionDetails; + + /** + * Gets the structure that maps which property depends on other property. + * To be overridden in child class if has any dependent objects. + * @return + */ + @Override + public Map>>> getDependentObjects() { + + return new HashMap>>>(){{ + put("PaymentType", new HashMap>>() + {{ + put("CARD", new HashMap>() {{ + put("PaymentDetails", PayInPaymentDetailsCard.class); + }} + ); + put("PREAUTHORIZED", new HashMap>() {{ + put("PaymentDetails", PayInPaymentDetailsPreAuthorized.class); + }} + ); + put("BANK_WIRE", new HashMap>() {{ + put("PaymentDetails", PayInPaymentDetailsBankWire.class); + }} + ); + // ...and more in future... + }} + ); + put("ExecutionType", new HashMap>>() + {{ + put("WEB", new HashMap>() {{ + put("ExecutionDetails", PayInExecutionDetailsWeb.class); + }} + ); + put("DIRECT", new HashMap>() {{ + put("ExecutionDetails", PayInExecutionDetailsDirect.class); + }} + ); + // ...and more in future... + }} + ); + }}; + } + + /** + * Gets the collection of read-only fields names + * @return List of field names. + */ + @Override + public ArrayList getReadOnlyProperties() { + + ArrayList result = super.getReadOnlyProperties(); + + result.add("PaymentType"); + result.add("ExecutionType"); + + return result; + } +} diff --git a/src/com/mangopay/entities/Transaction.java b/src/com/mangopay/entities/Transaction.java index 03b31647..eaaf8a2a 100644 --- a/src/com/mangopay/entities/Transaction.java +++ b/src/com/mangopay/entities/Transaction.java @@ -46,6 +46,11 @@ public class Transaction extends EntityBase { */ public String ResultCode; + /** + * The PreAuthorization result Message explaining the result code. + */ + public String ResultMessage; + /** * ExecutionDate (UNIX timestamp). */ diff --git a/src/com/mangopay/entities/UserLegal.java b/src/com/mangopay/entities/UserLegal.java index 4d777889..120ad0a5 100644 --- a/src/com/mangopay/entities/UserLegal.java +++ b/src/com/mangopay/entities/UserLegal.java @@ -1,95 +1,94 @@ -package com.mangopay.entities; - -import com.mangopay.core.NoUpdate; -import java.util.ArrayList; - -/** - * UserLegal entity. - */ -public class UserLegal extends User { - - /** - * Name of this user. - */ - public String Name; - - /** - * Allowed types for legal user. - */ - public static class LegalPersonTypes { - public static final String Business = "BUSINESS"; - public static final String Organization = "ASSOCIATION"; - } - - /** - * Type for legal user. One of LegalPersonTypes constants. - */ - public String LegalPersonType; - - /** - */ - public String HeadquartersAddress; - - /** - */ - public String LegalRepresentativeFirstName; - - /** - */ - public String LegalRepresentativeLastName; - - /** - */ - public String LegalRepresentativeAddress; - - /** - */ - public String LegalRepresentativeEmail; - - /** - */ - public long LegalRepresentativeBirthday; - - /** - */ - public String LegalRepresentativeNationality; - - /** - */ - public String LegalRepresentativeCountryOfResidence; - - /** - */ - public String Statute; - - /** - */ - public String ProofOfRegistration; - - /** - */ - public String ShareholderDeclaration; - - /** - * Creates new instance of UserLegal class. - */ - public UserLegal() { - PersonType = Types.Legal; - } - - /** - * Gets the collection of read-only fields names - * @return List of field names. - */ - @Override - public ArrayList getReadOnlyProperties() { - - ArrayList result = super.getReadOnlyProperties(); - - result.add("Statute"); - result.add("ProofOfRegistration"); - result.add("ShareholderDeclaration"); - - return result; - } -} +package com.mangopay.entities; + +import java.util.ArrayList; + +/** + * UserLegal entity. + */ +public class UserLegal extends User { + + /** + * Name of this user. + */ + public String Name; + + /** + * Allowed types for legal user. + */ + public static class LegalPersonTypes { + public static final String Business = "BUSINESS"; + public static final String Organization = "ASSOCIATION"; + } + + /** + * Type for legal user. One of LegalPersonTypes constants. + */ + public String LegalPersonType; + + /** + */ + public String HeadquartersAddress; + + /** + */ + public String LegalRepresentativeFirstName; + + /** + */ + public String LegalRepresentativeLastName; + + /** + */ + public String LegalRepresentativeAddress; + + /** + */ + public String LegalRepresentativeEmail; + + /** + */ + public long LegalRepresentativeBirthday; + + /** + */ + public String LegalRepresentativeNationality; + + /** + */ + public String LegalRepresentativeCountryOfResidence; + + /** + */ + public String Statute; + + /** + */ + public String ProofOfRegistration; + + /** + */ + public String ShareholderDeclaration; + + /** + * Creates new instance of UserLegal class. + */ + public UserLegal() { + PersonType = Types.Legal; + } + + /** + * Gets the collection of read-only fields names + * @return List of field names. + */ + @Override + public ArrayList getReadOnlyProperties() { + + ArrayList result = super.getReadOnlyProperties(); + + result.add("Statute"); + result.add("ProofOfRegistration"); + result.add("ShareholderDeclaration"); + + return result; + } +} diff --git a/test/com/mangopay/core/ApiCardPreAuthorizationsTest.java b/test/com/mangopay/core/ApiCardPreAuthorizationsTest.java new file mode 100644 index 00000000..1d2554a9 --- /dev/null +++ b/test/com/mangopay/core/ApiCardPreAuthorizationsTest.java @@ -0,0 +1,48 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.mangopay.core; + +import com.mangopay.entities.CardPreAuthorization; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * ApiCardPreAuthorizations test methods. + */ +public class ApiCardPreAuthorizationsTest extends BaseTest { + + @Test + public void test_CardPreAuthorization_Create() throws Exception { + CardPreAuthorization cardPreAuthorization = this.getJohnsCardPreAuthorization(); + + assertTrue(!"".equals(cardPreAuthorization.Id)); + assertEquals(cardPreAuthorization.Status, "SUCCEEDED"); + assertEquals(cardPreAuthorization.PaymentStatus, "WAITING"); + assertEquals(cardPreAuthorization.ExecutionType, "DIRECT"); + assertNull(cardPreAuthorization.PayInId); + } + + @Test + public void test_CardPreAuthorization_Get() throws Exception { + CardPreAuthorization cardPreAuthorization = this.getJohnsCardPreAuthorization(); + + CardPreAuthorization getCardPreAuthorization = this._api.CardPreAuthorizations.get(cardPreAuthorization.Id); + + assertEquals(cardPreAuthorization.Id, getCardPreAuthorization.Id); + assertEquals(getCardPreAuthorization.ResultCode, "000000"); + } + + @Test + public void test_CardPreAuthorization_Update() throws Exception { + CardPreAuthorization cardPreAuthorization = this.getJohnsCardPreAuthorization(); + cardPreAuthorization.PaymentStatus = "CANCELED "; + + CardPreAuthorization resultCardPreAuthorization = this._api.CardPreAuthorizations.update(cardPreAuthorization); + + assertEquals(resultCardPreAuthorization.Status, "SUCCEEDED"); + assertEquals(resultCardPreAuthorization.PaymentStatus, "CANCELED"); + } + +} diff --git a/test/com/mangopay/core/ApiHooksTest.java b/test/com/mangopay/core/ApiHooksTest.java new file mode 100644 index 00000000..61064629 --- /dev/null +++ b/test/com/mangopay/core/ApiHooksTest.java @@ -0,0 +1,68 @@ +package com.mangopay.core; + +import com.mangopay.entities.*; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * ApiHooks test methods. + */ +public class ApiHooksTest extends BaseTest { + + @Test + public void test_Hooks_Create() { + try { + Hook hook = this.getJohnsHook(); + assertTrue(hook.Id.length() > 0); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Hooks_Get() { + try { + Hook hook = this.getJohnsHook(); + Hook getHook = this._api.Hooks.get(hook.Id); + + assertEquals(getHook.Id, hook.Id); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Hooks_Update() { + try { + Hook hook = this.getJohnsHook(); + hook.Url = "http://test123.com"; + + Hook saveHook = this._api.Hooks.update(hook); + + assertEquals(saveHook.Id, hook.Id); + assertEquals(saveHook.Url, "http://test123.com"); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Hooks_All() { + try { + Hook hook = this.getJohnsHook(); + Pagination pagination = new Pagination(1, 1); + + List list = this._api.Hooks.getAll(pagination); + + assertTrue(list.get(0) instanceof Hook); + assertEquals(hook.Id, list.get(0).Id); + assertEquals(pagination.Page, 1); + assertEquals(pagination.ItemsPerPage, 1); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + +} diff --git a/test/com/mangopay/core/ApiPayInsTest.java b/test/com/mangopay/core/ApiPayInsTest.java index fc4701b3..473c1ad3 100644 --- a/test/com/mangopay/core/ApiPayInsTest.java +++ b/test/com/mangopay/core/ApiPayInsTest.java @@ -1,114 +1,263 @@ -package com.mangopay.core; - -import com.mangopay.entities.PayIn; -import com.mangopay.entities.Refund; -import com.mangopay.entities.UserNatural; -import com.mangopay.entities.Wallet; -import java.util.logging.Level; -import java.util.logging.Logger; -import static org.junit.Assert.*; -import org.junit.Test; - -/** - * API PayIns test methods - */ -public class ApiPayInsTest extends BaseTest { - - @Test - public void test_PayIns_Create_CardWeb() { - PayIn payIn = null; - try { - payIn = this.getJohnsPayInCardWeb(); - } catch (Exception ex) { - Logger.getLogger(ApiPayInsTest.class.getName()).log(Level.SEVERE, null, ex); - } - - assertTrue(payIn.Id.length() > 0); - assertTrue(payIn.PaymentType.equals("CARD")); - assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); - assertTrue(payIn.ExecutionType.equals("WEB")); - assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsWeb); - } - - @Test - public void test_PayIns_Get_CardWeb() throws Exception { - PayIn payIn = null; - try { - payIn = this.getJohnsPayInCardWeb(); - } catch (Exception ex) { - Logger.getLogger(ApiPayInsTest.class.getName()).log(Level.SEVERE, null, ex); - } - - PayIn getPayIn = this._api.PayIns.get(payIn.Id); - - assertTrue(payIn.Id.equals(getPayIn.Id)); - assertTrue(payIn.PaymentType.equals("CARD")); - assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); - assertTrue(payIn.ExecutionType.equals("WEB")); - assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsWeb); - - assertEqualInputProps(payIn, getPayIn); - - assertTrue(getPayIn.Status.equals("CREATED")); - assertTrue(getPayIn.ExecutionDate == null); - - assertNotNull(((PayInExecutionDetailsWeb)getPayIn.ExecutionDetails).RedirectURL); - assertNotNull(((PayInExecutionDetailsWeb)getPayIn.ExecutionDetails).ReturnURL); - } - - @Test - public void test_PayIns_Create_CardDirect() throws Exception { - Wallet johnWallet = this.getJohnsWalletWithMoney(); - Wallet beforeWallet = this._api.Wallets.get(johnWallet.Id); - - PayIn payIn = this.getNewPayInCardDirect(); - Wallet wallet = this._api.Wallets.get(johnWallet.Id); - UserNatural user = this.getJohn(); - - assertTrue(payIn.Id.length() > 0); - assertEquals(wallet.Id, payIn.CreditedWalletId); - assertEquals("CARD", payIn.PaymentType); - assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); - assertEquals("DIRECT", payIn.ExecutionType); - assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); - assertTrue(payIn.DebitedFunds instanceof Money); - assertTrue(payIn.CreditedFunds instanceof Money); - assertTrue(payIn.Fees instanceof Money); - assertEquals(user.Id, payIn.AuthorId); - assertTrue(wallet.Balance.Amount == beforeWallet.Balance.Amount + payIn.CreditedFunds.Amount); - assertEquals("SUCCEEDED", payIn.Status); - assertEquals("PAYIN", payIn.Type); - } - - @Test - public void test_PayIns_Get_CardDirect() throws Exception { - PayIn payIn = this.getNewPayInCardDirect(); - - PayIn getPayIn = this._api.PayIns.get(payIn.Id); - - assertTrue(payIn.Id.equals(getPayIn.Id)); - assertTrue(payIn.PaymentType.equals("CARD")); - assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); - assertTrue(payIn.ExecutionType.equals("DIRECT")); - assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); - this.assertEqualInputProps(payIn, getPayIn); - assertNotNull(((PayInExecutionDetailsDirect)getPayIn.ExecutionDetails).CardId); - } - - @Test - public void test_PayIns_CreateRefund_CardDirect() throws Exception { - PayIn payIn = this.getNewPayInCardDirect(); - Wallet wallet = this.getJohnsWalletWithMoney(); - Wallet walletBefore = this._api.Wallets.get(wallet.Id); - - Refund refund = this.getNewRefundForPayIn(payIn); - Wallet walletAfter = this._api.Wallets.get(wallet.Id); - - assertTrue(refund.Id.length() > 0); - assertTrue(refund.DebitedFunds.Amount.equals(payIn.DebitedFunds.Amount)); - assertTrue(walletBefore.Balance.Amount.equals(walletAfter.Balance.Amount + payIn.DebitedFunds.Amount)); - assertEquals("PAYOUT", refund.Type); - assertEquals("REFUND", refund.Nature); - } - -} +package com.mangopay.core; + +import com.mangopay.entities.BankAccount; +import com.mangopay.entities.CardPreAuthorization; +import com.mangopay.entities.PayIn; +import com.mangopay.entities.Refund; +import com.mangopay.entities.UserNatural; +import com.mangopay.entities.Wallet; +import java.util.logging.Level; +import java.util.logging.Logger; +import junit.framework.Assert; +import static org.junit.Assert.*; +import org.junit.Test; + +/** + * API PayIns test methods + */ +public class ApiPayInsTest extends BaseTest { + + @Test + public void test_PayIns_Create_CardWeb() { + try { + PayIn payIn = null; + payIn = this.getJohnsPayInCardWeb(); + + assertTrue(payIn.Id.length() > 0); + assertTrue(payIn.PaymentType.equals("CARD")); + assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); + assertTrue(payIn.ExecutionType.equals("WEB")); + assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsWeb); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_Get_CardWeb() { + try { + PayIn payIn = null; + payIn = this.getJohnsPayInCardWeb(); + + PayIn getPayIn = this._api.PayIns.get(payIn.Id); + + assertTrue(payIn.Id.equals(getPayIn.Id)); + assertTrue(payIn.PaymentType.equals("CARD")); + assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); + assertTrue(payIn.ExecutionType.equals("WEB")); + assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsWeb); + + assertEqualInputProps(payIn, getPayIn); + + assertTrue(getPayIn.Status.equals("CREATED")); + assertTrue(getPayIn.ExecutionDate == null); + + assertNotNull(((PayInExecutionDetailsWeb)getPayIn.ExecutionDetails).RedirectURL); + assertNotNull(((PayInExecutionDetailsWeb)getPayIn.ExecutionDetails).ReturnURL); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_Create_CardDirect() { + try { + Wallet johnWallet = this.getJohnsWalletWithMoney(); + Wallet beforeWallet = this._api.Wallets.get(johnWallet.Id); + + PayIn payIn = this.getNewPayInCardDirect(); + Wallet wallet = this._api.Wallets.get(johnWallet.Id); + UserNatural user = this.getJohn(); + + assertTrue(payIn.Id.length() > 0); + assertEquals(wallet.Id, payIn.CreditedWalletId); + assertEquals("CARD", payIn.PaymentType); + assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); + assertEquals("DIRECT", payIn.ExecutionType); + assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); + assertTrue(payIn.DebitedFunds instanceof Money); + assertTrue(payIn.CreditedFunds instanceof Money); + assertTrue(payIn.Fees instanceof Money); + assertEquals(user.Id, payIn.AuthorId); + assertTrue(wallet.Balance.Amount == beforeWallet.Balance.Amount + payIn.CreditedFunds.Amount); + assertEquals("SUCCEEDED", payIn.Status); + assertEquals("PAYIN", payIn.Type); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_Get_CardDirect() { + try { + PayIn payIn = this.getNewPayInCardDirect(); + + PayIn getPayIn = this._api.PayIns.get(payIn.Id); + + assertTrue(payIn.Id.equals(getPayIn.Id)); + assertTrue(payIn.PaymentType.equals("CARD")); + assertTrue(payIn.PaymentDetails instanceof PayInPaymentDetailsCard); + assertTrue(payIn.ExecutionType.equals("DIRECT")); + assertTrue(payIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); + this.assertEqualInputProps(payIn, getPayIn); + assertNotNull(((PayInPaymentDetailsCard)getPayIn.PaymentDetails).CardId); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_CreateRefund_CardDirect() { + try { + PayIn payIn = this.getNewPayInCardDirect(); + Wallet wallet = this.getJohnsWalletWithMoney(); + Wallet walletBefore = this._api.Wallets.get(wallet.Id); + + Refund refund = this.getNewRefundForPayIn(payIn); + Wallet walletAfter = this._api.Wallets.get(wallet.Id); + + assertTrue(refund.Id.length() > 0); + assertTrue(refund.DebitedFunds.Amount.equals(payIn.DebitedFunds.Amount)); + assertTrue(walletBefore.Balance.Amount.equals(walletAfter.Balance.Amount + payIn.DebitedFunds.Amount)); + assertEquals("PAYOUT", refund.Type); + assertEquals("REFUND", refund.Nature); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_PreAuthorizedDirect() { + try { + CardPreAuthorization cardPreAuthorization = this.getJohnsCardPreAuthorization(); + Wallet wallet = this.getJohnsWalletWithMoney(); + UserNatural user = this.getJohn(); + + // create pay-in PRE-AUTHORIZED DIRECT + PayIn payIn = new PayIn(); + payIn.CreditedWalletId = wallet.Id; + payIn.AuthorId = user.Id; + payIn.DebitedFunds = new Money(); + payIn.DebitedFunds.Amount = 10000.0; + payIn.DebitedFunds.Currency = "EUR"; + payIn.Fees = new Money(); + payIn.Fees.Amount = 0.0; + payIn.Fees.Currency = "EUR"; + + // payment type as CARD + payIn.PaymentDetails = new PayInPaymentDetailsPreAuthorized(); + ((PayInPaymentDetailsPreAuthorized)payIn.PaymentDetails).PreauthorizationId = cardPreAuthorization.Id; + + // execution type as DIRECT + payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); + ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).SecureModeReturnURL = "http://test.com"; + + PayIn createPayIn = this._api.PayIns.create(payIn); + + assertTrue(!"".equals(createPayIn.Id)); + assertEquals(wallet.Id, createPayIn.CreditedWalletId); + assertEquals("PREAUTHORIZED", createPayIn.PaymentType); + assertTrue(createPayIn.PaymentDetails instanceof PayInPaymentDetailsPreAuthorized); + assertEquals("DIRECT", createPayIn.ExecutionType); + assertTrue(createPayIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); + assertTrue(createPayIn.DebitedFunds instanceof Money); + assertTrue(createPayIn.CreditedFunds instanceof Money); + assertTrue(createPayIn.Fees instanceof Money); + assertEquals(user.Id, createPayIn.AuthorId); + assertEquals("SUCCEEDED", createPayIn.Status); + assertEquals("PAYIN", createPayIn.Type); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_BankWireDirect_Create() { + try { + Wallet wallet = this.getJohnsWallet(); + UserNatural user = this.getJohn(); + + // create pay-in PRE-AUTHORIZED DIRECT + PayIn payIn = new PayIn(); + payIn.CreditedWalletId = wallet.Id; + payIn.AuthorId = user.Id; + + // payment type as CARD + payIn.PaymentDetails = new PayInPaymentDetailsBankWire(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds = new Money(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds.Amount = 10000.0; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds.Currency = "EUR"; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees = new Money(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees.Amount = 0.0; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees.Currency = "EUR"; + payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); + + PayIn createPayIn = this._api.PayIns.create(payIn); + + assertTrue(!"".equals(createPayIn.Id)); + assertEquals(wallet.Id, createPayIn.CreditedWalletId); + assertEquals("BANK_WIRE", createPayIn.PaymentType); + assertTrue(createPayIn.PaymentDetails instanceof PayInPaymentDetailsBankWire); + assertTrue(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).DeclaredDebitedFunds instanceof Money); + assertTrue(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).DeclaredFees instanceof Money); + assertEquals("DIRECT", createPayIn.ExecutionType); + assertTrue(createPayIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); + assertEquals(user.Id, createPayIn.AuthorId); + assertEquals("CREATED", createPayIn.Status); + assertEquals("PAYIN", createPayIn.Type); + assertNotNull(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).WireReference); + assertTrue(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).BankAccount instanceof BankAccount); + assertEquals(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).BankAccount.Type, "IBAN"); + assertTrue(((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).BankAccount.Details instanceof BankAccountDetailsIBAN); + assertNotNull(((BankAccountDetailsIBAN)((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).BankAccount.Details).IBAN); + assertNotNull(((BankAccountDetailsIBAN)((PayInPaymentDetailsBankWire)createPayIn.PaymentDetails).BankAccount.Details).BIC); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_PayIns_BankWireDirect_Get() { + try { + Wallet wallet = this.getJohnsWallet(); + UserNatural user = this.getJohn(); + + // create pay-in PRE-AUTHORIZED DIRECT + PayIn payIn = new PayIn(); + payIn.CreditedWalletId = wallet.Id; + payIn.AuthorId = user.Id; + + // payment type as CARD + payIn.PaymentDetails = new PayInPaymentDetailsBankWire(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds = new Money(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds.Amount = 10000.0; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredDebitedFunds.Currency = "EUR"; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees = new Money(); + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees.Amount = 0.0; + ((PayInPaymentDetailsBankWire)payIn.PaymentDetails).DeclaredFees.Currency = "EUR"; + payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); + PayIn createdPayIn = this._api.PayIns.create(payIn); + + PayIn getPayIn = this._api.PayIns.get(createdPayIn.Id); + + assertEquals(getPayIn.Id, createdPayIn.Id); + assertEquals("BANK_WIRE", getPayIn.PaymentType); + assertTrue(getPayIn.PaymentDetails instanceof PayInPaymentDetailsBankWire); + assertTrue(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).DeclaredDebitedFunds instanceof Money); + assertTrue(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).DeclaredFees instanceof Money); + assertEquals("DIRECT", getPayIn.ExecutionType); + assertTrue(getPayIn.ExecutionDetails instanceof PayInExecutionDetailsDirect); + assertEquals(user.Id, getPayIn.AuthorId); + assertEquals("PAYIN", getPayIn.Type); + assertNotNull(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).WireReference); + assertTrue(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).BankAccount instanceof BankAccount); + assertEquals(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).BankAccount.Type, "IBAN"); + assertTrue(((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).BankAccount.Details instanceof BankAccountDetailsIBAN); + assertNotNull(((BankAccountDetailsIBAN)((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).BankAccount.Details).IBAN); + assertNotNull(((BankAccountDetailsIBAN)((PayInPaymentDetailsBankWire)getPayIn.PaymentDetails).BankAccount.Details).BIC); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + + } +} diff --git a/test/com/mangopay/core/ApiUsersTest.java b/test/com/mangopay/core/ApiUsersTest.java index 12cdf06c..c656bda8 100644 --- a/test/com/mangopay/core/ApiUsersTest.java +++ b/test/com/mangopay/core/ApiUsersTest.java @@ -1,242 +1,383 @@ -package com.mangopay.core; - -import com.mangopay.entities.*; -import java.net.URL; -import java.nio.file.Path; -import java.util.Calendar; -import java.util.List; -import java.util.Locale; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * ApiUsers test methods - */ -public class ApiUsersTest extends BaseTest { - - @Test - public void test_Users_CreateNatural() throws Exception { - UserNatural john = this.getJohn(); - assertTrue(john.Id.length() > 0); - assertTrue(john.PersonType.equals(User.Types.Natural)); - } - - @Test - public void test_Users_CreateLegal() throws Exception { - UserLegal matrix = this.getMatrix(); - assertTrue(matrix.Id.length() > 0); - assertTrue(matrix.PersonType.equals(User.Types.Legal)); - } - - @Test - public void test_Users_CreateLegal_FailsIfRequiredPropsNotProvided() throws Exception { - UserLegal user = new UserLegal(); - - User ret = null; - - try { - ret = this._api.Users.create(user); - - assertTrue("CreateLegal() should throw an exception when required props are not provided", false); - } - catch (ResponseException ex) { - assertNull(ret); - } - } - - @Test - public void test_Users_CreateLegal_PassesIfRequiredPropsProvided() throws Exception { - UserLegal user = new UserLegal(); - user.Name = "SomeOtherSampleOrg"; - user.LegalPersonType = "BUSINESS"; - user.LegalRepresentativeFirstName = "RepFName"; - user.LegalRepresentativeLastName = "RepLName"; - Calendar c = Calendar.getInstance(); - c.set(1975, 12, 21, 0, 0, 0); - user.LegalRepresentativeBirthday = c.getTimeInMillis() / 1000; - user.LegalRepresentativeNationality = "FR"; - user.LegalRepresentativeCountryOfResidence = "FR"; - user.Email = "email@email.org"; - - User ret = null; - - ret = this._api.Users.create(user); - - assertTrue("Created successfully after required props set", ret.Id.length() > 0); - - assertEqualInputProps(user, ret); - } - - @Test - public void test_Users_GetNatural() throws Exception { - UserNatural john = this.getJohn(); - - User user1 = this._api.Users.get(john.Id); - UserNatural user2 = this._api.Users.getNatural(john.Id); - - assertTrue(user1.PersonType.equals(User.Types.Natural)); - assertTrue(user1.Id.equals(john.Id)); - assertTrue(user2.PersonType.equals(User.Types.Natural)); - assertTrue(user2.Id.equals(john.Id)); - - //assertIdentical(user1, john); - //assertIdentical(user2, john); - assertEqualInputProps(user1, john); - } - - @Test - public void test_Users_GetNatural_FailsForLegalUser() throws Exception { - UserLegal matrix = this.getMatrix(); - - UserNatural user = null; - try { - user = this._api.Users.getNatural(matrix.Id); - - assertTrue("GetUser() should throw an exception when called with legal user id", false); - } - catch (ResponseException ex) { - assertNull(user); - } - } - - @Test - public void test_Users_GetLegal_FailsForNaturalUser() throws Exception { - UserNatural john = this.getJohn(); - - User user = null; - try { - user = this._api.Users.getLegal(john.Id); - - assertTrue("GetLegal() should throw an exception when called with natural user id", false); - } catch (ResponseException ex) { - assertNull(user); - } - } - - @Test - public void test_Users_GetLegal() throws Exception { - UserLegal matrix = this.getMatrix(); - - User user1 = this._api.Users.get(matrix.Id); - User user2 = this._api.Users.getLegal(matrix.Id); - -// assertEquals(user1, matrix); -// assertEquals(user2, matrix); - assertEqualInputProps((UserLegal)user1, matrix); - assertEqualInputProps((UserLegal)user2, matrix); - } - - @Test - public void test_Users_Save_Natural() throws Exception { - UserNatural john = this.getJohn(); - john.LastName += " - CHANGED"; - - User userSaved = this._api.Users.update(john); - User userFetched = this._api.Users.get(john.Id); - - assertEqualInputProps(userSaved, john); - assertEqualInputProps(userFetched, john); - } - - @Test - public void test_Users_Save_Legal() throws Exception { - UserLegal matrix = this.getMatrix(); - matrix.LegalRepresentativeLastName += " - CHANGED"; - - User userSaved = this._api.Users.update(matrix); - User userFetched = this._api.Users.get(matrix.Id); - - assertEqualInputProps(userSaved, matrix); - assertEqualInputProps(userFetched, matrix); - } - - @Test - public void test_Users_CreateBankAccount() throws Exception { - UserNatural john = this.getJohn(); - BankAccount account = this.getJohnsAccount(); - - assertTrue(account.Id.length() > 0); - assertTrue(account.UserId.equals(john.Id)); - } - - @Test - public void test_Users_BankAccount() throws Exception { - UserNatural john = this.getJohn(); - BankAccount account = this.getJohnsAccount(); - - BankAccount accountFetched = this._api.Users.getBankAccount(john.Id, account.Id); - - assertEqualInputProps(account, accountFetched); - } - - @Test - public void test_Users_BankAccounts() throws Exception { - UserNatural john = this.getJohn(); - BankAccount account = this.getJohnsAccount(); - Pagination pagination = new Pagination(1, 12); - - List list = this._api.Users.getBankAccounts(john.Id, pagination); - - assertTrue(list.get(0) instanceof BankAccount); - assertTrue(account.Id.equals(list.get(0).Id)); - assertEqualInputProps(account, list.get(0)); - assertTrue(pagination.Page == 1); - assertTrue(pagination.ItemsPerPage == 12); - } - - - @Test - public void test_Users_CreateKycDocument() throws Exception { - KycDocument kycDocument = this.getJohnsKycDocument(); - - assertNotNull(kycDocument); - assertTrue(kycDocument.Status.equals("CREATED")); - } - - @Test - public void test_Users_SaveKycDocument() throws Exception { - UserNatural john = this.getJohn(); - KycDocument kycDocument = this.getJohnsKycDocument(); - - //Calendar c = Calendar.getInstance(); - //Long currTime = c.getTimeInMillis() / 1000; - //kycDocument.Tag = currTime.toString(); - kycDocument.Status = "VALIDATION_ASKED"; - - KycDocument result = this._api.Users.updateKycDocument(john.Id, kycDocument); - - assertNotNull(result); - assertTrue(kycDocument.Type.equals(result.Type)); - assertTrue(kycDocument.Status.equals("VALIDATION_ASKED")); - //assertNotNull(result.Tag); - //assertTrue(result.Tag.equals(currTime.toString())); - } - - @Test - public void test_Users_GetKycDocument() throws Exception { - UserNatural john = this.getJohn(); - KycDocument kycDocument = this.getJohnsKycDocument(); - - KycDocument result = this._api.Users.getKycDocument(john.Id, kycDocument.Id); - - assertNotNull(result); - assertTrue(kycDocument.Id.equals(result.Id)); - assertTrue(kycDocument.Type.equals(result.Type)); - assertTrue(kycDocument.Status.equals(result.Status)); - assertTrue(kycDocument.CreationDate == result.CreationDate); - } - - @Test - public void test_Users_CreateKycPage() throws Exception { - UserNatural john = this.getJohn(); - KycDocument kycDocument = this.getJohnsKycDocument(); - - this._api.Users.createKycPage(john.Id, kycDocument.Id, "Test KYC page".getBytes()); - - URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); - String filePath = url.toString() + "/com/mangopay/core/TestKycPageFile.txt"; - filePath = filePath.replace("file:/", "").replace("//", "/").replace("/", "\\"); - - this._api.Users.createKycPage(john.Id, kycDocument.Id, filePath); - } +package com.mangopay.core; + +import com.mangopay.entities.*; +import java.net.URL; +import java.nio.file.AccessDeniedException; +import java.nio.file.NoSuchFileException; +import java.util.Calendar; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * ApiUsers test methods + */ +public class ApiUsersTest extends BaseTest { + + @Test + public void test_Users_CreateNatural() throws Exception { + UserNatural john = this.getJohn(); + assertTrue(john.Id.length() > 0); + assertTrue(john.PersonType.equals(User.Types.Natural)); + } + + @Test + public void test_Users_CreateLegal() throws Exception { + UserLegal matrix = this.getMatrix(); + assertTrue(matrix.Id.length() > 0); + assertTrue(matrix.PersonType.equals(User.Types.Legal)); + } + + @Test + public void test_Users_CreateLegal_FailsIfRequiredPropsNotProvided() throws Exception { + UserLegal user = new UserLegal(); + + User ret = null; + + try { + ret = this._api.Users.create(user); + + assertTrue("CreateLegal() should throw an exception when required props are not provided", false); + } + catch (ResponseException ex) { + assertNull(ret); + } + } + + @Test + public void test_Users_CreateLegal_PassesIfRequiredPropsProvided() throws Exception { + UserLegal user = new UserLegal(); + user.Name = "SomeOtherSampleOrg"; + user.LegalPersonType = "BUSINESS"; + user.LegalRepresentativeFirstName = "RepFName"; + user.LegalRepresentativeLastName = "RepLName"; + Calendar c = Calendar.getInstance(); + c.set(1975, 12, 21, 0, 0, 0); + user.LegalRepresentativeBirthday = c.getTimeInMillis() / 1000; + user.LegalRepresentativeNationality = "FR"; + user.LegalRepresentativeCountryOfResidence = "FR"; + user.Email = "email@email.org"; + + User ret = null; + + ret = this._api.Users.create(user); + + assertTrue("Created successfully after required props set", ret.Id.length() > 0); + + assertEqualInputProps(user, ret); + } + + @Test + public void test_Users_GetNatural() throws Exception { + UserNatural john = this.getJohn(); + + User user1 = this._api.Users.get(john.Id); + UserNatural user2 = this._api.Users.getNatural(john.Id); + + assertTrue(user1.PersonType.equals(User.Types.Natural)); + assertTrue(user1.Id.equals(john.Id)); + assertTrue(user2.PersonType.equals(User.Types.Natural)); + assertTrue(user2.Id.equals(john.Id)); + + //assertIdentical(user1, john); + //assertIdentical(user2, john); + assertEqualInputProps(user1, john); + } + + @Test + public void test_Users_GetNatural_FailsForLegalUser() throws Exception { + UserLegal matrix = this.getMatrix(); + + UserNatural user = null; + try { + user = this._api.Users.getNatural(matrix.Id); + + assertTrue("GetUser() should throw an exception when called with legal user id", false); + } + catch (ResponseException ex) { + assertNull(user); + } + } + + @Test + public void test_Users_GetLegal_FailsForNaturalUser() throws Exception { + UserNatural john = this.getJohn(); + + User user = null; + try { + user = this._api.Users.getLegal(john.Id); + + assertTrue("GetLegal() should throw an exception when called with natural user id", false); + } catch (ResponseException ex) { + assertNull(user); + } + } + + @Test + public void test_Users_GetLegal() throws Exception { + UserLegal matrix = this.getMatrix(); + + User user1 = this._api.Users.get(matrix.Id); + User user2 = this._api.Users.getLegal(matrix.Id); + +// assertEquals(user1, matrix); +// assertEquals(user2, matrix); + assertEqualInputProps((UserLegal)user1, matrix); + assertEqualInputProps((UserLegal)user2, matrix); + } + + @Test + public void test_Users_Save_Natural() throws Exception { + UserNatural john = this.getJohn(); + john.LastName += " - CHANGED"; + + User userSaved = this._api.Users.update(john); + User userFetched = this._api.Users.get(john.Id); + + assertEqualInputProps(userSaved, john); + assertEqualInputProps(userFetched, john); + } + + @Test + public void test_Users_Save_Legal() throws Exception { + UserLegal matrix = this.getMatrix(); + matrix.LegalRepresentativeLastName += " - CHANGED"; + + User userSaved = this._api.Users.update(matrix); + User userFetched = this._api.Users.get(matrix.Id); + + assertEqualInputProps(userSaved, matrix); + assertEqualInputProps(userFetched, matrix); + } + + @Test + public void test_Users_CreateBankAccount_IBAN() { + try { + UserNatural john = this.getJohn(); + BankAccount account = this.getJohnsAccount(); + + assertTrue(account.Id.length() > 0); + assertEquals(account.UserId, john.Id); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Users_CreateBankAccount_GB() { + try { + UserNatural john = this.getJohn(); + BankAccount account = new BankAccount(); + account.OwnerName = john.FirstName + " " + john.LastName; + account.OwnerAddress = john.Address; + account.Details = new BankAccountDetailsGB(); + ((BankAccountDetailsGB)account.Details).AccountNumber = "234234234234"; + ((BankAccountDetailsGB)account.Details).SortCode = "234334"; + + BankAccount createAccount = this._api.Users.createBankAccount(john.Id, account); + + assertTrue(createAccount.Id.length() > 0); + assertTrue(createAccount.UserId.equals(john.Id)); + assertTrue(createAccount.Type.equals("GB")); + assertTrue(((BankAccountDetailsGB)createAccount.Details).AccountNumber.equals("234234234234")); + assertTrue(((BankAccountDetailsGB)createAccount.Details).SortCode.equals("234334")); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Users_CreateBankAccount_US() { + try { + UserNatural john = this.getJohn(); + BankAccount account = new BankAccount(); + account.OwnerName = john.FirstName + " " + john.LastName; + account.OwnerAddress = john.Address; + account.Details = new BankAccountDetailsUS(); + ((BankAccountDetailsUS)account.Details).AccountNumber = "234234234234"; + ((BankAccountDetailsUS)account.Details).ABA = "234334789"; + + BankAccount createAccount = this._api.Users.createBankAccount(john.Id, account); + + assertTrue(createAccount.Id.length() > 0); + assertTrue(createAccount.UserId.equals(john.Id)); + assertTrue(createAccount.Type.equals("US")); + assertTrue(((BankAccountDetailsUS)createAccount.Details).AccountNumber.equals("234234234234")); + assertTrue(((BankAccountDetailsUS)createAccount.Details).ABA.equals("234334789")); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Users_CreateBankAccount_CA() { + try { + UserNatural john = this.getJohn(); + BankAccount account = new BankAccount(); + account.OwnerName = john.FirstName + " " + john.LastName; + account.OwnerAddress = john.Address; + account.Details = new BankAccountDetailsCA(); + ((BankAccountDetailsCA)account.Details).BankName = "TestBankName"; + ((BankAccountDetailsCA)account.Details).BranchCode = "12345"; + ((BankAccountDetailsCA)account.Details).AccountNumber = "234234234234"; + ((BankAccountDetailsCA)account.Details).InstitutionNumber = "123"; + + BankAccount createAccount = this._api.Users.createBankAccount(john.Id, account); + + assertTrue(createAccount.Id.length() > 0); + assertTrue(createAccount.UserId.equals(john.Id)); + assertTrue(createAccount.Type.equals("CA")); + assertTrue(((BankAccountDetailsCA)createAccount.Details).AccountNumber.equals("234234234234")); + assertTrue(((BankAccountDetailsCA)createAccount.Details).BankName.equals("TestBankName")); + assertTrue(((BankAccountDetailsCA)createAccount.Details).BranchCode.equals("12345")); + assertTrue(((BankAccountDetailsCA)createAccount.Details).InstitutionNumber.equals("123")); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Users_CreateBankAccount_OTHER() { + try { + UserNatural john = this.getJohn(); + BankAccount account = new BankAccount(); + account.OwnerName = john.FirstName + " " + john.LastName; + account.OwnerAddress = john.Address; + account.Details = new BankAccountDetailsOTHER(); + ((BankAccountDetailsOTHER)account.Details).Type = "OTHER"; + ((BankAccountDetailsOTHER)account.Details).Country = "FR"; + ((BankAccountDetailsOTHER)account.Details).AccountNumber = "234234234234"; + ((BankAccountDetailsOTHER)account.Details).BIC = "BINAADADXXX"; + + BankAccount createAccount = this._api.Users.createBankAccount(john.Id, account); + + assertTrue(createAccount.Id.length() > 0); + assertTrue(createAccount.UserId.equals(john.Id)); + assertTrue(createAccount.Type.equals("OTHER")); + assertTrue(((BankAccountDetailsOTHER)createAccount.Details).Type.equals("OTHER")); + assertTrue(((BankAccountDetailsOTHER)createAccount.Details).Country.equals("FR")); + assertTrue(((BankAccountDetailsOTHER)createAccount.Details).AccountNumber.equals("234234234234")); + assertTrue(((BankAccountDetailsOTHER)createAccount.Details).BIC.equals("BINAADADXXX")); + } catch (Exception ex) { + Assert.fail(ex.getMessage()); + } + } + + @Test + public void test_Users_CreateBankAccount() throws Exception { + UserNatural john = this.getJohn(); + BankAccount account = this.getJohnsAccount(); + + assertTrue(account.Id.length() > 0); + assertTrue(account.UserId.equals(john.Id)); + } + + @Test + public void test_Users_BankAccount() throws Exception { + UserNatural john = this.getJohn(); + BankAccount account = this.getJohnsAccount(); + + BankAccount accountFetched = this._api.Users.getBankAccount(john.Id, account.Id); + + assertEqualInputProps(account, accountFetched); + } + + @Test + public void test_Users_BankAccounts() throws Exception { + UserNatural john = this.getJohn(); + BankAccount account = this.getJohnsAccount(); + Pagination pagination = new Pagination(1, 12); + + List list = this._api.Users.getBankAccounts(john.Id, pagination); + + assertTrue(list.get(0) instanceof BankAccount); + assertTrue(account.Id.equals(list.get(0).Id)); + assertEqualInputProps(account, list.get(0)); + assertTrue(pagination.Page == 1); + assertTrue(pagination.ItemsPerPage == 12); + } + + + @Test + public void test_Users_CreateKycDocument() throws Exception { + KycDocument kycDocument = this.getJohnsKycDocument(); + + assertNotNull(kycDocument); + assertTrue(kycDocument.Status.equals("CREATED")); + } + + @Test + public void test_Users_SaveKycDocument() throws Exception { + UserNatural john = this.getJohn(); + KycDocument kycDocument = this.getJohnsKycDocument(); + + //Calendar c = Calendar.getInstance(); + //Long currTime = c.getTimeInMillis() / 1000; + //kycDocument.Tag = currTime.toString(); + kycDocument.Status = "VALIDATION_ASKED"; + + KycDocument result = this._api.Users.updateKycDocument(john.Id, kycDocument); + + assertNotNull(result); + assertTrue(kycDocument.Type.equals(result.Type)); + assertTrue(kycDocument.Status.equals("VALIDATION_ASKED")); + //assertNotNull(result.Tag); + //assertTrue(result.Tag.equals(currTime.toString())); + } + + @Test + public void test_Users_GetKycDocument() throws Exception { + UserNatural john = this.getJohn(); + KycDocument kycDocument = this.getJohnsKycDocument(); + + KycDocument result = this._api.Users.getKycDocument(john.Id, kycDocument.Id); + + assertNotNull(result); + assertTrue(kycDocument.Id.equals(result.Id)); + assertTrue(kycDocument.Type.equals(result.Type)); + assertTrue(kycDocument.Status.equals(result.Status)); + assertTrue(kycDocument.CreationDate == result.CreationDate); + } + + @Test + public void test_Users_CreateKycPage() throws Exception { + UserNatural john = this.getJohn(); + KycDocument kycDocument = this.getJohnsKycDocument(); + + this._api.Users.createKycPage(john.Id, kycDocument.Id, "Test KYC page".getBytes()); + + URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); + String filePath = url.toString() + "/com/mangopay/core/TestKycPageFile.txt"; + filePath = filePath.replace("file:/", "").replace("//", "/").replace("/", "\\"); + + this._api.Users.createKycPage(john.Id, kycDocument.Id, filePath); + } + + @Test + public void test_Users_AllCards() throws Exception { + UserNatural john = this.getJohn(); + PayIn payIn = this.getNewPayInCardDirect(); + Pagination pagination = new Pagination(1, 1); + Card card = this._api.Cards.get(((PayInPaymentDetailsCard)payIn.PaymentDetails).CardId); + List cards = this._api.Users.getCards(john.Id, pagination); + + assertTrue(cards.size() == 1); + assertTrue(cards.get(0).CardType != null); + assertTrue(cards.get(0).Currency != null); + assertEqualInputProps(cards.get(0), card); + } + + @Test + public void test_Users_Transactions() throws Exception { + UserNatural john = this.getJohn(); + Transfer transfer = this.getNewTransfer(); + Pagination pagination = new Pagination(1, 1); + + List transactions = this._api.Users.getTransactions(john.Id, pagination, new FilterTransactions()); + + assertTrue(transactions.size() > 0); + assertTrue(transactions.get(0).Type != null); + assertTrue(transactions.get(0).Status != null); + } } \ No newline at end of file diff --git a/test/com/mangopay/core/BaseTest.java b/test/com/mangopay/core/BaseTest.java index 4ab2334a..768ad2c0 100644 --- a/test/com/mangopay/core/BaseTest.java +++ b/test/com/mangopay/core/BaseTest.java @@ -1,583 +1,727 @@ -package com.mangopay.core; - -import com.mangopay.*; -import com.mangopay.entities.*; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Calendar; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import static org.junit.Assert.*; - -@Ignore("Just a base class for tests: nothing to test here") -public abstract class BaseTest { - - protected MangoPayApi _api; - - private static UserNatural _john; - private static UserLegal _matrix; - private static BankAccount _johnsAccount; - private static Wallet _johnsWallet; - private static Wallet _johnsWalletWithMoney; - private static PayIn _johnsPayInCardWeb; - private static PayInPaymentDetailsCard _payInPaymentDetailsCard; - private static PayInExecutionDetailsWeb _payInExecutionDetailsWeb; - private static PayOut _johnsPayOutBankWire; - private static CardRegistration _johnsCardRegistration; - private static KycDocument _johnsKycDocument; - - public BaseTest() { - this._api = buildNewMangoPayApi(); - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - protected final MangoPayApi buildNewMangoPayApi() { - MangoPayApi api = new MangoPayApi(); - - // use test client credentails - api.Config.ClientId = "sdk-unit-tests"; - api.Config.ClientPassword = "cqFfFrWfCcb7UadHNxx2C9Lo6Djw8ZduLi7J9USTmu8bhxxpju"; - api.Config.DebugMode = true; - - // register storage strategy for tests - api.OAuthTokenManager.registerCustomStorageStrategy(new DefaultStorageStrategyForTests()); - - return api; - } - - protected UserNatural getJohn() throws Exception { - if (BaseTest._john == null) { - Calendar c = Calendar.getInstance(); - c.set(1975, 12, 21, 0, 0, 0); - - UserNatural user = new UserNatural(); - user.FirstName = "John"; - user.LastName = "Doe"; - user.Email = "john.doe@sample.org"; - user.Address = "Some Address"; - user.Birthday = c.getTimeInMillis() / 1000; - user.Nationality = "FR"; - user.CountryOfResidence = "FR"; - user.Occupation = "programmer"; - user.IncomeRange = 3; - - BaseTest._john = (UserNatural)this._api.Users.create(user); - } - return BaseTest._john; - } - - protected UserLegal getMatrix() throws Exception { - if (BaseTest._matrix == null) { - UserNatural john = this.getJohn(); - UserLegal user = new UserLegal(); - user.Name = "MartixSampleOrg"; - user.LegalPersonType = "BUSINESS"; - user.HeadquartersAddress = "Some Address"; - user.LegalRepresentativeFirstName = john.FirstName; - user.LegalRepresentativeLastName = john.LastName; - user.LegalRepresentativeAddress = john.Address; - user.LegalRepresentativeEmail = john.Email; - user.LegalRepresentativeBirthday = john.Birthday; - user.LegalRepresentativeNationality = john.Nationality; - user.LegalRepresentativeCountryOfResidence = john.CountryOfResidence; - - Calendar c = Calendar.getInstance(); - c.set(1975, 12, 21, 0, 0, 0); - user.LegalRepresentativeBirthday = c.getTimeInMillis() / 1000; - user.Email = john.Email; - - BaseTest._matrix = (UserLegal)this._api.Users.create(user); - } - return BaseTest._matrix; - } - - protected BankAccount getJohnsAccount() throws Exception { - if (BaseTest._johnsAccount == null) { - UserNatural john = this.getJohn(); - BankAccount account = new BankAccount(); - account.Type = "IBAN"; - account.OwnerName = john.FirstName + " " + john.LastName; - account.OwnerAddress = john.Address; - account.IBAN = "FR76 1790 6000 3200 0833 5232 973"; - account.BIC = "BINAADADXXX"; - BaseTest._johnsAccount = this._api.Users.createBankAccount(john.Id, account); - } - return BaseTest._johnsAccount; - } - - protected Wallet getJohnsWallet() throws Exception { - if (BaseTest._johnsWallet == null) { - UserNatural john = this.getJohn(); - - Wallet wallet = new Wallet(); - wallet.Owners = new ArrayList<>(); - wallet.Owners.add(john.Id); - - wallet.Currency = "EUR"; - wallet.Description = "WALLET IN EUR"; - - BaseTest._johnsWallet = this._api.Wallets.create(wallet); - - if (BaseTest._johnsWallet.Balance.Amount == null) { - BaseTest._johnsWallet.Balance.Amount = 0.0; - } - } - - return BaseTest._johnsWallet; - } - - /** - * Creates wallet for John, loaded with 10k EUR (John's got lucky) if not - * created yet, or returns an existing one. - * @return Wallet instance loaded with 10k EUR. - */ - protected Wallet getJohnsWalletWithMoney() throws Exception { - return getJohnsWalletWithMoney(10000); - } - - /** - * Creates wallet for John, if not created yet, or returns an existing one. - * @param amount Initial wallet's money amount. - * @return Wallet entity instance. - */ - protected Wallet getJohnsWalletWithMoney(double amount) throws Exception { - - if (BaseTest._johnsWalletWithMoney == null) { - - UserNatural john = this.getJohn(); - - // create wallet with money - Wallet wallet = new Wallet(); - wallet.Owners = new ArrayList<>(); - wallet.Owners.add(john.Id); - wallet.Currency = "EUR"; - wallet.Description = "WALLET IN EUR WITH MONEY"; - - BaseTest._johnsWalletWithMoney = this._api.Wallets.create(wallet); - - CardRegistration cardRegistration = new CardRegistration(); - cardRegistration.UserId = BaseTest._johnsWalletWithMoney.Owners.get(0); - cardRegistration.Currency = "EUR"; - cardRegistration = this._api.CardRegistrations.create(cardRegistration); - - cardRegistration.RegistrationData = this.getPaylineCorrectRegistartionData(cardRegistration); - cardRegistration = this._api.CardRegistrations.update(cardRegistration); - - Card card = this._api.Cards.get(cardRegistration.CardId); - - // create pay-in CARD DIRECT - PayIn payIn = new PayIn(); - payIn.CreditedWalletId = BaseTest._johnsWalletWithMoney.Id; - payIn.AuthorId = cardRegistration.UserId; - payIn.DebitedFunds = new Money(); - payIn.DebitedFunds.Amount = amount; - payIn.DebitedFunds.Currency = "EUR"; - payIn.Fees = new Money(); - payIn.Fees.Amount = 0.0; - payIn.Fees.Currency = "EUR"; - - // payment type as CARD - payIn.PaymentDetails = new PayInPaymentDetailsCard(); - if (card.CardType.equals("CB") || card.CardType.equals("VISA") || card.CardType.equals("MASTERCARD")) - ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "CB_VISA_MASTERCARD"; - else if (card.CardType.equals("AMEX")) - ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "AMEX"; - - // execution type as DIRECT - payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); - ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).CardId = card.Id; - ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).SecureModeReturnURL = "http://test.com"; - // create Pay-In - this._api.PayIns.create(payIn); - } - - return this._api.Wallets.get(BaseTest._johnsWalletWithMoney.Id); - } - - private PayInPaymentDetailsCard getPayInPaymentDetailsCard() { - if (BaseTest._payInPaymentDetailsCard == null) { - BaseTest._payInPaymentDetailsCard = new PayInPaymentDetailsCard(); - BaseTest._payInPaymentDetailsCard.CardType = "AMEX"; - } - - return BaseTest._payInPaymentDetailsCard; - } - - private PayInExecutionDetailsWeb getPayInExecutionDetailsWeb() { - if (BaseTest._payInExecutionDetailsWeb == null) { - BaseTest._payInExecutionDetailsWeb = new PayInExecutionDetailsWeb(); - BaseTest._payInExecutionDetailsWeb.TemplateURL = "https://TemplateURL.com"; - BaseTest._payInExecutionDetailsWeb.SecureMode = "DEFAULT"; - BaseTest._payInExecutionDetailsWeb.Culture = "fr"; - BaseTest._payInExecutionDetailsWeb.ReturnURL = "https://test.com"; - } - - return BaseTest._payInExecutionDetailsWeb; - } - - protected PayIn getJohnsPayInCardWeb() throws Exception { - if (BaseTest._johnsPayInCardWeb == null) { - Wallet wallet = this.getJohnsWallet(); - UserNatural user = this.getJohn(); - - PayIn payIn = new PayIn(); - payIn.AuthorId = user.Id; - payIn.CreditedUserId = user.Id; - payIn.DebitedFunds = new Money(); - payIn.DebitedFunds.Currency = "EUR"; - payIn.DebitedFunds.Amount = 1000.0; - payIn.Fees = new Money(); - payIn.Fees.Currency = "EUR"; - payIn.Fees.Amount = 5.0; - payIn.CreditedWalletId = wallet.Id; - payIn.PaymentDetails = this.getPayInPaymentDetailsCard(); - payIn.ExecutionDetails = this.getPayInExecutionDetailsWeb(); - - BaseTest._johnsPayInCardWeb = this._api.PayIns.create(payIn); - } - - return BaseTest._johnsPayInCardWeb; - } - - /** - * Creates Pay-In Card Direct object - * @return PayIn - */ - protected PayIn getNewPayInCardDirect() throws Exception { - - Wallet wallet = this.getJohnsWalletWithMoney(); - UserNatural user = this.getJohn(); - - CardRegistration cardRegistration = new CardRegistration(); - cardRegistration.UserId = user.Id; - cardRegistration.Currency = "EUR"; - cardRegistration = this._api.CardRegistrations.create(cardRegistration); - cardRegistration.RegistrationData = this.getPaylineCorrectRegistartionData(cardRegistration); - cardRegistration = this._api.CardRegistrations.update(cardRegistration); - - Card card = this._api.Cards.get(cardRegistration.CardId); - - // create pay-in CARD DIRECT - PayIn payIn = new PayIn(); - payIn.CreditedWalletId = wallet.Id; - payIn.AuthorId = user.Id; - payIn.DebitedFunds = new Money(); - payIn.DebitedFunds.Amount = 10000.0; - payIn.DebitedFunds.Currency = "EUR"; - payIn.Fees = new Money(); - payIn.Fees.Amount = 0.0; - payIn.Fees.Currency = "EUR"; - - // payment type as CARD - payIn.PaymentDetails = new PayInPaymentDetailsCard(); - if (card.CardType.equals("CB") || card.CardType.equals("VISA") || card.CardType.equals("MASTERCARD")) - ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "CB_VISA_MASTERCARD"; - else if (card.CardType.equals("AMEX")) - ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "AMEX"; - - // execution type as DIRECT - payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); - ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).CardId = card.Id; - ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).SecureModeReturnURL = "http://test.com"; - - return this._api.PayIns.create(payIn); - } - - protected PayOut getJohnsPayOutBankWire() throws Exception { - if (BaseTest._johnsPayOutBankWire == null) { - Wallet wallet = this.getJohnsWallet(); - UserNatural user = this.getJohn(); - BankAccount account = this.getJohnsAccount(); - - PayOut payOut = new PayOut(); - payOut.Tag = "DefaultTag"; - payOut.AuthorId = user.Id; - payOut.CreditedUserId = user.Id; - payOut.DebitedFunds = new Money(); - payOut.DebitedFunds.Currency = "EUR"; - payOut.DebitedFunds.Amount = 10.0; - payOut.Fees = new Money(); - payOut.Fees.Currency = "EUR"; - payOut.Fees.Amount = 5.0; - - payOut.DebitedWalletId = wallet.Id; - payOut.MeanOfPaymentDetails = new PayOutPaymentDetailsBankWire(); - ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).BankAccountId = account.Id; - ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).Communication = "Communication text"; - - BaseTest._johnsPayOutBankWire = this._api.PayOuts.create(payOut); - } - - return BaseTest._johnsPayOutBankWire; - } - - protected Transfer getNewTransfer() throws Exception { - Wallet walletWithMoney = this.getJohnsWalletWithMoney(); - UserNatural user = this.getJohn(); - - Wallet wallet = new Wallet(); - wallet.Owners = new ArrayList<>(); - wallet.Owners.add(user.Id); - wallet.Currency = "EUR"; - wallet.Description = "WALLET IN EUR FOR TRANSFER"; - wallet = this._api.Wallets.create(wallet); - - Transfer transfer = new Transfer(); - transfer.Tag = "DefaultTag"; - transfer.AuthorId = user.Id; - transfer.CreditedUserId = user.Id; - transfer.DebitedFunds = new Money(); - transfer.DebitedFunds.Currency = "EUR"; - transfer.DebitedFunds.Amount = 100.0; - transfer.Fees = new Money(); - transfer.Fees.Currency = "EUR"; - transfer.Fees.Amount = 0.0; - - transfer.DebitedWalletId = walletWithMoney.Id; - transfer.CreditedWalletId = wallet.Id; - - return this._api.Transfers.create(transfer); - } - - /** - * Creates refund object for transfer. - */ - protected Refund getNewRefundForTransfer(Transfer transfer) throws Exception { - UserNatural user = this.getJohn(); - - Refund refund = new Refund(); - refund.DebitedWalletId = transfer.DebitedWalletId; - refund.CreditedWalletId = transfer.CreditedWalletId; - refund.AuthorId = user.Id; - refund.DebitedFunds = new Money(); - refund.DebitedFunds.Amount = transfer.DebitedFunds.Amount; - refund.DebitedFunds.Currency = transfer.DebitedFunds.Currency; - refund.Fees = new Money(); - refund.Fees.Amount = transfer.Fees.Amount; - refund.Fees.Currency = transfer.Fees.Currency; - - return this._api.Transfers.createRefund(transfer.Id, refund); - } - - /** - * Creates refund object for PayIn. - * @return Created Refund entity. - */ - protected Refund getNewRefundForPayIn(PayIn payIn) throws Exception { - UserNatural user = this.getJohn(); - - Refund refund = new Refund(); - refund.CreditedWalletId = payIn.CreditedWalletId; - refund.AuthorId = user.Id; - refund.DebitedFunds = new Money(); - refund.DebitedFunds.Amount = payIn.DebitedFunds.Amount; - refund.DebitedFunds.Currency = payIn.DebitedFunds.Currency; - refund.Fees = new Money(); - refund.Fees.Amount = payIn.Fees.Amount; - refund.Fees.Currency = payIn.Fees.Currency; - - return this._api.PayIns.createRefund(payIn.Id, refund); - } - - /** - * Creates card registration object. - * @return CardRegistration instance returned from API. - */ - protected CardRegistration getJohnsCardRegistration() throws Exception { - if (BaseTest._johnsCardRegistration == null) { - UserNatural user = this.getJohn(); - - CardRegistration cardRegistration = new CardRegistration(); - cardRegistration.UserId = user.Id; - cardRegistration.Currency = "EUR"; - - BaseTest._johnsCardRegistration = this._api.CardRegistrations.create(cardRegistration); - } - - return BaseTest._johnsCardRegistration; - } - - protected KycDocument getJohnsKycDocument() throws Exception { - if (BaseTest._johnsKycDocument == null) { - String johnsId = this.getJohn().Id; - - BaseTest._johnsKycDocument = this._api.Users.createKycDocument(johnsId, KycDocumentType.IDENTITY_PROOF); - } - - return BaseTest._johnsKycDocument; - } - - /** - * Gets registration data from Payline service. - * @param cardRegistration - * @return Registration data. - */ - protected String getPaylineCorrectRegistartionData(CardRegistration cardRegistration) throws MalformedURLException, IOException, Exception { - - String data = "data=" + cardRegistration.PreregistrationData + - "&accessKeyRef=" + cardRegistration.AccessKey + - "&cardNumber=4970100000000154" + - "&cardExpirationDate=1214" + - "&cardCvx=123"; - - URL url = new URL(cardRegistration.CardRegistrationURL); - HttpURLConnection connection = (HttpURLConnection)url.openConnection(); - - connection.setRequestMethod("POST"); - connection.setUseCaches (false); - connection.setDoInput(true); - connection.setDoOutput(true); - - try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { - wr.writeBytes(data); - wr.flush (); - } - - int responseCode = connection.getResponseCode(); - InputStream is; - if (responseCode != 200) { - is = connection.getErrorStream(); - } else { - is = connection.getInputStream(); - } - - StringBuffer resp; - try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { - String line; - resp = new StringBuffer(); - while((line = rd.readLine()) != null) { - resp.append(line); - } - } - String responseString = resp.toString(); - - if (responseCode == 200) - return responseString; - else - throw new Exception(responseString); - } - - protected void assertEqualInputProps(T entity1, T entity2) throws Exception { - - if (entity1 instanceof UserNatural) { - assertEquals(((UserNatural)entity1).Tag, ((UserNatural)entity2).Tag); - assertEquals(((UserNatural)entity1).PersonType, ((UserNatural)entity2).PersonType); - assertEquals(((UserNatural)entity1).FirstName, ((UserNatural)entity2).FirstName); - assertEquals(((UserNatural)entity1).LastName, ((UserNatural)entity2).LastName); - assertEquals(((UserNatural)entity1).Email, ((UserNatural)entity2).Email); - assertEquals(((UserNatural)entity1).Address, ((UserNatural)entity2).Address); - assertEquals(((UserNatural)entity1).Birthday, ((UserNatural)entity2).Birthday); - assertEquals(((UserNatural)entity1).Nationality, ((UserNatural)entity2).Nationality); - assertEquals(((UserNatural)entity1).CountryOfResidence, ((UserNatural)entity2).CountryOfResidence); - assertEquals(((UserNatural)entity1).Occupation, ((UserNatural)entity2).Occupation); - assertEquals(((UserNatural)entity1).IncomeRange, ((UserNatural)entity2).IncomeRange); - - } else if (entity1 instanceof UserLegal) { - assertEquals(((UserLegal)entity1).Tag, ((UserLegal)entity2).Tag); - assertEquals(((UserLegal)entity1).PersonType, ((UserLegal)entity2).PersonType); - assertEquals(((UserLegal)entity1).Name, ((UserLegal)entity2).Name); - assertEquals(((UserLegal)entity1).HeadquartersAddress, ((UserLegal)entity2).HeadquartersAddress); - assertEquals(((UserLegal)entity1).LegalRepresentativeFirstName, ((UserLegal)entity2).LegalRepresentativeFirstName); - assertEquals(((UserLegal)entity1).LegalRepresentativeLastName, ((UserLegal)entity2).LegalRepresentativeLastName); - assertEquals("***** TEMPORARY API ISSUE: RETURNED OBJECT MISSES THIS PROP AFTER CREATION *****", ((UserLegal)entity1).LegalRepresentativeAddress, ((UserLegal)entity2).LegalRepresentativeAddress); - assertEquals(((UserLegal)entity1).LegalRepresentativeEmail, ((UserLegal)entity2).LegalRepresentativeEmail); - //assertEquals("***** TEMPORARY API ISSUE: RETURNED OBJECT HAS THIS PROP CHANGED FROM TIMESTAMP INTO ISO STRING AFTER CREATION *****", ((UserLegal)entity1).LegalRepresentativeBirthday, ((UserLegal)entity2).LegalRepresentativeBirthday); - assertEquals(((UserLegal)entity1).LegalRepresentativeBirthday, ((UserLegal)entity2).LegalRepresentativeBirthday); - assertEquals(((UserLegal)entity1).LegalRepresentativeNationality, ((UserLegal)entity2).LegalRepresentativeNationality); - assertEquals(((UserLegal)entity1).LegalRepresentativeCountryOfResidence, ((UserLegal)entity2).LegalRepresentativeCountryOfResidence); - - } else if (entity1 instanceof BankAccount) { - assertEquals(((BankAccount)entity1).Tag, ((BankAccount)entity2).Tag); - assertEquals(((BankAccount)entity1).UserId, ((BankAccount)entity2).UserId); - assertEquals(((BankAccount)entity1).Type, ((BankAccount)entity2).Type); - assertEquals(((BankAccount)entity1).OwnerName, ((BankAccount)entity2).OwnerName); - assertEquals(((BankAccount)entity1).OwnerAddress, ((BankAccount)entity2).OwnerAddress); - assertEquals(((BankAccount)entity1).IBAN, ((BankAccount)entity2).IBAN); - assertEquals(((BankAccount)entity1).BIC, ((BankAccount)entity2).BIC); - - } else if (entity1 instanceof PayIn) { - assertEquals(((PayIn)entity1).Tag, ((PayIn)entity2).Tag); - assertEquals(((PayIn)entity1).AuthorId, ((PayIn)entity2).AuthorId); - assertEquals(((PayIn)entity1).CreditedUserId, ((PayIn)entity2).CreditedUserId); - - assertEqualInputProps(((PayIn)entity1).DebitedFunds, ((PayIn)entity2).DebitedFunds); - assertEqualInputProps(((PayIn)entity1).CreditedFunds, ((PayIn)entity2).CreditedFunds); - assertEqualInputProps(((PayIn)entity1).Fees, ((PayIn)entity2).Fees); - - } else if (entity1 instanceof PayInPaymentDetailsCard) { - assertEquals(((PayInPaymentDetailsCard)entity1).CardType, ((PayInPaymentDetailsCard)entity2).CardType); - - } else if (entity1 instanceof PayInExecutionDetailsWeb) { - assertEquals(((PayInExecutionDetailsWeb)entity1).TemplateURL, ((PayInExecutionDetailsWeb)entity2).TemplateURL); - assertEquals(((PayInExecutionDetailsWeb)entity1).Culture, ((PayInExecutionDetailsWeb)entity2).Culture); - assertEquals(((PayInExecutionDetailsWeb)entity1).SecureMode, ((PayInExecutionDetailsWeb)entity2).SecureMode); - assertEquals(((PayInExecutionDetailsWeb)entity1).RedirectURL, ((PayInExecutionDetailsWeb)entity2).RedirectURL); - assertEquals(((PayInExecutionDetailsWeb)entity1).ReturnURL, ((PayInExecutionDetailsWeb)entity2).ReturnURL); - - } else if (entity1 instanceof PayOut) { - assertEquals(((PayOut)entity1).Tag, ((PayOut)entity2).Tag); - assertEquals(((PayOut)entity1).AuthorId, ((PayOut)entity2).AuthorId); - assertEquals(((PayOut)entity1).CreditedUserId, ((PayOut)entity2).CreditedUserId); - - assertEqualInputProps(((PayOut)entity1).DebitedFunds, ((PayOut)entity2).DebitedFunds); - assertEqualInputProps(((PayOut)entity1).CreditedFunds, ((PayOut)entity2).CreditedFunds); - assertEqualInputProps(((PayOut)entity1).Fees, ((PayOut)entity2).Fees); - assertEqualInputProps(((PayOut)entity1).MeanOfPaymentDetails, ((PayOut)entity2).MeanOfPaymentDetails); - - } else if (entity1 instanceof Transfer) { - assertEquals(((Transfer)entity1).Tag, ((Transfer)entity2).Tag); - assertEquals(((Transfer)entity1).AuthorId, ((Transfer)entity2).AuthorId); - assertEquals(((Transfer)entity1).CreditedUserId, ((Transfer)entity2).CreditedUserId); - - assertEqualInputProps(((Transfer)entity1).DebitedFunds, ((Transfer)entity2).DebitedFunds); - assertEqualInputProps(((Transfer)entity1).CreditedFunds, ((Transfer)entity2).CreditedFunds); - assertEqualInputProps(((Transfer)entity1).Fees, ((Transfer)entity2).Fees); - - } else if (entity1 instanceof PayOutPaymentDetailsBankWire) { - assertEquals(((PayOutPaymentDetailsBankWire)entity1).BankAccountId, ((PayOutPaymentDetailsBankWire)entity2).BankAccountId); - assertEquals(((PayOutPaymentDetailsBankWire)entity1).Communication, ((PayOutPaymentDetailsBankWire)entity2).Communication); - - } else if (entity1 instanceof Transaction) { - assertEquals(((Transaction)entity1).Tag, ((Transaction)entity2).Tag); - - assertEqualInputProps(((Transaction)entity1).DebitedFunds, ((Transaction)entity2).DebitedFunds); - assertEqualInputProps(((Transaction)entity1).Fees, ((Transaction)entity2).Fees); - assertEqualInputProps(((Transaction)entity1).CreditedFunds, ((Transaction)entity2).CreditedFunds); - - assertEquals(((Transaction)entity1).Status, ((Transaction)entity2).Status); - - } else if (entity1 instanceof Money) { - assertEquals(((Money)entity1).Currency, ((Money)entity2).Currency); - assertEquals(((Money)entity1).Amount, ((Money)entity2).Amount); - } else { - throw new Exception("Unsupported type"); - } - - } - -} +package com.mangopay.core; + +import com.mangopay.*; +import com.mangopay.entities.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import static org.junit.Assert.*; + +@Ignore("Just a base class for tests: nothing to test here") +public abstract class BaseTest { + + protected MangoPayApi _api; + + private static UserNatural _john; + private static UserLegal _matrix; + private static BankAccount _johnsAccount; + private static Wallet _johnsWallet; + private static Wallet _johnsWalletWithMoney; + private static PayIn _johnsPayInCardWeb; + private static PayInPaymentDetailsCard _payInPaymentDetailsCard; + private static PayInExecutionDetailsWeb _payInExecutionDetailsWeb; + private static PayOut _johnsPayOutBankWire; + private static CardRegistration _johnsCardRegistration; + private static KycDocument _johnsKycDocument; + private static PayOut _johnsPayOutForCardDirect; + private static Hook _johnsHook; + + public BaseTest() { + this._api = buildNewMangoPayApi(); + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + protected final MangoPayApi buildNewMangoPayApi() { + MangoPayApi api = new MangoPayApi(); + + // use test client credentails + api.Config.ClientId = "sdk-unit-tests"; + api.Config.ClientPassword = "cqFfFrWfCcb7UadHNxx2C9Lo6Djw8ZduLi7J9USTmu8bhxxpju"; + api.Config.DebugMode = true; + + // register storage strategy for tests + api.OAuthTokenManager.registerCustomStorageStrategy(new DefaultStorageStrategyForTests()); + + return api; + } + + protected UserNatural getJohn() throws Exception { + if (BaseTest._john == null) { + Calendar c = Calendar.getInstance(); + c.set(1975, 12, 21, 0, 0, 0); + + UserNatural user = new UserNatural(); + user.FirstName = "John"; + user.LastName = "Doe"; + user.Email = "john.doe@sample.org"; + user.Address = "Some Address"; + user.Birthday = c.getTimeInMillis() / 1000; + user.Nationality = "FR"; + user.CountryOfResidence = "FR"; + user.Occupation = "programmer"; + user.IncomeRange = 3; + + BaseTest._john = (UserNatural)this._api.Users.create(user); + } + return BaseTest._john; + } + + protected UserNatural getNewJohn() throws Exception { + + Calendar c = Calendar.getInstance(); + c.set(1975, 12, 21, 0, 0, 0); + + UserNatural user = new UserNatural(); + user.FirstName = "John"; + user.LastName = "Doe"; + user.Email = "john.doe@sample.org"; + user.Address = "Some Address"; + user.Birthday = c.getTimeInMillis() / 1000; + user.Nationality = "FR"; + user.CountryOfResidence = "FR"; + user.Occupation = "programmer"; + user.IncomeRange = 3; + return (UserNatural)this._api.Users.create(user); + + } + + protected UserLegal getMatrix() throws Exception { + if (BaseTest._matrix == null) { + UserNatural john = this.getJohn(); + UserLegal user = new UserLegal(); + user.Name = "MartixSampleOrg"; + user.LegalPersonType = "BUSINESS"; + user.HeadquartersAddress = "Some Address"; + user.LegalRepresentativeFirstName = john.FirstName; + user.LegalRepresentativeLastName = john.LastName; + user.LegalRepresentativeAddress = john.Address; + user.LegalRepresentativeEmail = john.Email; + user.LegalRepresentativeBirthday = john.Birthday; + user.LegalRepresentativeNationality = john.Nationality; + user.LegalRepresentativeCountryOfResidence = john.CountryOfResidence; + + Calendar c = Calendar.getInstance(); + c.set(1975, 12, 21, 0, 0, 0); + user.LegalRepresentativeBirthday = c.getTimeInMillis() / 1000; + user.Email = john.Email; + + BaseTest._matrix = (UserLegal)this._api.Users.create(user); + } + return BaseTest._matrix; + } + + protected BankAccount getJohnsAccount() throws Exception { + if (BaseTest._johnsAccount == null) { + UserNatural john = this.getJohn(); + BankAccount account = new BankAccount(); + account.Type = "IBAN"; + account.OwnerName = john.FirstName + " " + john.LastName; + account.OwnerAddress = john.Address; + account.UserId = john.Id; + BankAccountDetailsIBAN bankAccountDetails = new BankAccountDetailsIBAN(); + bankAccountDetails.IBAN = "FR76 1790 6000 3200 0833 5232 973"; + bankAccountDetails.BIC = "BINAADADXXX"; + account.Details = bankAccountDetails; + BaseTest._johnsAccount = this._api.Users.createBankAccount(john.Id, account); + } + return BaseTest._johnsAccount; + } + + protected Wallet getJohnsWallet() throws Exception { + if (BaseTest._johnsWallet == null) { + UserNatural john = this.getJohn(); + + Wallet wallet = new Wallet(); + wallet.Owners = new ArrayList<>(); + wallet.Owners.add(john.Id); + + wallet.Currency = "EUR"; + wallet.Description = "WALLET IN EUR"; + + BaseTest._johnsWallet = this._api.Wallets.create(wallet); + + if (BaseTest._johnsWallet.Balance.Amount == null) { + BaseTest._johnsWallet.Balance.Amount = 0.0; + } + } + + return BaseTest._johnsWallet; + } + + /** + * Creates wallet for John, loaded with 10k EUR (John's got lucky) if not + * created yet, or returns an existing one. + * @return Wallet instance loaded with 10k EUR. + */ + protected Wallet getJohnsWalletWithMoney() throws Exception { + return getJohnsWalletWithMoney(10000); + } + + /** + * Creates wallet for John, if not created yet, or returns an existing one. + * @param amount Initial wallet's money amount. + * @return Wallet entity instance. + */ + protected Wallet getJohnsWalletWithMoney(double amount) throws Exception { + + if (BaseTest._johnsWalletWithMoney == null) { + + UserNatural john = this.getJohn(); + + // create wallet with money + Wallet wallet = new Wallet(); + wallet.Owners = new ArrayList<>(); + wallet.Owners.add(john.Id); + wallet.Currency = "EUR"; + wallet.Description = "WALLET IN EUR WITH MONEY"; + + BaseTest._johnsWalletWithMoney = this._api.Wallets.create(wallet); + + CardRegistration cardRegistration = new CardRegistration(); + cardRegistration.UserId = BaseTest._johnsWalletWithMoney.Owners.get(0); + cardRegistration.Currency = "EUR"; + cardRegistration = this._api.CardRegistrations.create(cardRegistration); + + cardRegistration.RegistrationData = this.getPaylineCorrectRegistartionData(cardRegistration); + cardRegistration = this._api.CardRegistrations.update(cardRegistration); + + Card card = this._api.Cards.get(cardRegistration.CardId); + + // create pay-in CARD DIRECT + PayIn payIn = new PayIn(); + payIn.CreditedWalletId = BaseTest._johnsWalletWithMoney.Id; + payIn.AuthorId = cardRegistration.UserId; + payIn.DebitedFunds = new Money(); + payIn.DebitedFunds.Amount = amount; + payIn.DebitedFunds.Currency = "EUR"; + payIn.Fees = new Money(); + payIn.Fees.Amount = 0.0; + payIn.Fees.Currency = "EUR"; + + // payment type as CARD + payIn.PaymentDetails = new PayInPaymentDetailsCard(); + if (card.CardType.equals("CB") || card.CardType.equals("VISA") || card.CardType.equals("MASTERCARD")) + ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "CB_VISA_MASTERCARD"; + else if (card.CardType.equals("AMEX")) + ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "AMEX"; + + // execution type as DIRECT + payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); + ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).CardId = card.Id; + ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).SecureModeReturnURL = "http://test.com"; + // create Pay-In + this._api.PayIns.create(payIn); + } + + return this._api.Wallets.get(BaseTest._johnsWalletWithMoney.Id); + } + + private PayInPaymentDetailsCard getPayInPaymentDetailsCard() { + if (BaseTest._payInPaymentDetailsCard == null) { + BaseTest._payInPaymentDetailsCard = new PayInPaymentDetailsCard(); + BaseTest._payInPaymentDetailsCard.CardType = "CB_VISA_MASTERCARD"; + } + + return BaseTest._payInPaymentDetailsCard; + } + + private PayInExecutionDetailsWeb getPayInExecutionDetailsWeb() { + if (BaseTest._payInExecutionDetailsWeb == null) { + BaseTest._payInExecutionDetailsWeb = new PayInExecutionDetailsWeb(); + BaseTest._payInExecutionDetailsWeb.TemplateURL = "https://TemplateURL.com"; + BaseTest._payInExecutionDetailsWeb.SecureMode = "DEFAULT"; + BaseTest._payInExecutionDetailsWeb.Culture = "fr"; + BaseTest._payInExecutionDetailsWeb.ReturnURL = "https://test.com"; + } + + return BaseTest._payInExecutionDetailsWeb; + } + + protected PayIn getJohnsPayInCardWeb() throws Exception { + if (BaseTest._johnsPayInCardWeb == null) { + Wallet wallet = this.getJohnsWallet(); + UserNatural user = this.getJohn(); + + PayIn payIn = new PayIn(); + payIn.AuthorId = user.Id; + payIn.CreditedUserId = user.Id; + payIn.DebitedFunds = new Money(); + payIn.DebitedFunds.Currency = "EUR"; + payIn.DebitedFunds.Amount = 1000.0; + payIn.Fees = new Money(); + payIn.Fees.Currency = "EUR"; + payIn.Fees.Amount = 5.0; + payIn.CreditedWalletId = wallet.Id; + payIn.PaymentDetails = this.getPayInPaymentDetailsCard(); + payIn.ExecutionDetails = this.getPayInExecutionDetailsWeb(); + + BaseTest._johnsPayInCardWeb = this._api.PayIns.create(payIn); + } + + return BaseTest._johnsPayInCardWeb; + } + +// protected PayIn getJohnsPayInBankWireDirect() throws Exception { +// Wallet wallet = this.getJohnsWallet(); +// +// PayIn payIn = new PayIn(); +// payIn.CreditedWalletId = wallet.Id; +// payIn.AuthorId = wallet.Owners.get(0); +// +// // payment type as CARD +// payIn.PaymentDetails = new PayInPaymentDetailsBankWire(); +// } + + protected PayIn getNewPayInCardDirect() throws Exception { + return getNewPayInCardDirect(null); + } + /** + * Creates Pay-In Card Direct object + * @return PayIn + */ + protected PayIn getNewPayInCardDirect(String userId) throws Exception { + + Wallet wallet = this.getJohnsWalletWithMoney(); + + if (userId == null) { + UserNatural user = this.getJohn(); + userId = user.Id; + } + + CardRegistration cardRegistration = new CardRegistration(); + cardRegistration.UserId = userId; + cardRegistration.Currency = "EUR"; + cardRegistration = this._api.CardRegistrations.create(cardRegistration); + cardRegistration.RegistrationData = this.getPaylineCorrectRegistartionData(cardRegistration); + cardRegistration = this._api.CardRegistrations.update(cardRegistration); + + Card card = this._api.Cards.get(cardRegistration.CardId); + + // create pay-in CARD DIRECT + PayIn payIn = new PayIn(); + payIn.CreditedWalletId = wallet.Id; + payIn.AuthorId = userId; + payIn.DebitedFunds = new Money(); + payIn.DebitedFunds.Amount = 10000.0; + payIn.DebitedFunds.Currency = "EUR"; + payIn.Fees = new Money(); + payIn.Fees.Amount = 0.0; + payIn.Fees.Currency = "EUR"; + + // payment type as CARD + payIn.PaymentDetails = new PayInPaymentDetailsCard(); + ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardId = card.Id; + if (card.CardType.equals("CB") || card.CardType.equals("VISA") || card.CardType.equals("MASTERCARD")) + ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "CB_VISA_MASTERCARD"; + else if (card.CardType.equals("AMEX")) + ((PayInPaymentDetailsCard)payIn.PaymentDetails).CardType = "AMEX"; + + // execution type as DIRECT + payIn.ExecutionDetails = new PayInExecutionDetailsDirect(); + ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).CardId = card.Id; + ((PayInExecutionDetailsDirect)payIn.ExecutionDetails).SecureModeReturnURL = "http://test.com"; + + return this._api.PayIns.create(payIn); + } + + protected PayOut getJohnsPayOutBankWire() throws Exception { + if (BaseTest._johnsPayOutBankWire == null) { + Wallet wallet = this.getJohnsWallet(); + UserNatural user = this.getJohn(); + BankAccount account = this.getJohnsAccount(); + + PayOut payOut = new PayOut(); + payOut.Tag = "DefaultTag"; + payOut.AuthorId = user.Id; + payOut.CreditedUserId = user.Id; + payOut.DebitedFunds = new Money(); + payOut.DebitedFunds.Currency = "EUR"; + payOut.DebitedFunds.Amount = 10.0; + payOut.Fees = new Money(); + payOut.Fees.Currency = "EUR"; + payOut.Fees.Amount = 5.0; + + payOut.DebitedWalletId = wallet.Id; + payOut.MeanOfPaymentDetails = new PayOutPaymentDetailsBankWire(); + ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).BankAccountId = account.Id; + ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).Communication = "Communication text"; + + BaseTest._johnsPayOutBankWire = this._api.PayOuts.create(payOut); + } + + return BaseTest._johnsPayOutBankWire; + } + + /** + * Creates Pay-Out Bank Wire object. + * @return PayOut + * @throws Exception + */ + protected PayOut getJohnsPayOutForCardDirect() throws Exception { + if (BaseTest._johnsPayOutForCardDirect == null) { + PayIn payIn = this.getNewPayInCardDirect(); + BankAccount account = this.getJohnsAccount(); + + PayOut payOut = new PayOut(); + payOut.Tag = "DefaultTag"; + payOut.AuthorId = payIn.AuthorId; + payOut.CreditedUserId = payIn.AuthorId; + payOut.DebitedFunds = new Money(); + payOut.DebitedFunds.Currency = "EUR"; + payOut.DebitedFunds.Amount = 10.0; + payOut.Fees = new Money(); + payOut.Fees.Currency = "EUR"; + payOut.Fees.Amount = 5.0; + + payOut.DebitedWalletId = payIn.CreditedWalletId; + payOut.MeanOfPaymentDetails = new PayOutPaymentDetailsBankWire(); + ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).BankAccountId = account.Id; + ((PayOutPaymentDetailsBankWire)payOut.MeanOfPaymentDetails).Communication = "Communication text"; + + BaseTest._johnsPayOutForCardDirect = this._api.PayOuts.create(payOut); + } + + return BaseTest._johnsPayOutForCardDirect; + } + + protected Transfer getNewTransfer() throws Exception { + Wallet walletWithMoney = this.getJohnsWalletWithMoney(); + UserNatural user = this.getJohn(); + + Wallet wallet = new Wallet(); + wallet.Owners = new ArrayList<>(); + wallet.Owners.add(user.Id); + wallet.Currency = "EUR"; + wallet.Description = "WALLET IN EUR FOR TRANSFER"; + wallet = this._api.Wallets.create(wallet); + + Transfer transfer = new Transfer(); + transfer.Tag = "DefaultTag"; + transfer.AuthorId = user.Id; + transfer.CreditedUserId = user.Id; + transfer.DebitedFunds = new Money(); + transfer.DebitedFunds.Currency = "EUR"; + transfer.DebitedFunds.Amount = 100.0; + transfer.Fees = new Money(); + transfer.Fees.Currency = "EUR"; + transfer.Fees.Amount = 0.0; + + transfer.DebitedWalletId = walletWithMoney.Id; + transfer.CreditedWalletId = wallet.Id; + + return this._api.Transfers.create(transfer); + } + + /** + * Creates refund object for transfer. + */ + protected Refund getNewRefundForTransfer(Transfer transfer) throws Exception { + UserNatural user = this.getJohn(); + + Refund refund = new Refund(); + refund.DebitedWalletId = transfer.DebitedWalletId; + refund.CreditedWalletId = transfer.CreditedWalletId; + refund.AuthorId = user.Id; + refund.DebitedFunds = new Money(); + refund.DebitedFunds.Amount = transfer.DebitedFunds.Amount; + refund.DebitedFunds.Currency = transfer.DebitedFunds.Currency; + refund.Fees = new Money(); + refund.Fees.Amount = transfer.Fees.Amount; + refund.Fees.Currency = transfer.Fees.Currency; + + return this._api.Transfers.createRefund(transfer.Id, refund); + } + + /** + * Creates refund object for PayIn. + * @return Created Refund entity. + */ + protected Refund getNewRefundForPayIn(PayIn payIn) throws Exception { + UserNatural user = this.getJohn(); + + Refund refund = new Refund(); + refund.CreditedWalletId = payIn.CreditedWalletId; + refund.AuthorId = user.Id; + refund.DebitedFunds = new Money(); + refund.DebitedFunds.Amount = payIn.DebitedFunds.Amount; + refund.DebitedFunds.Currency = payIn.DebitedFunds.Currency; + refund.Fees = new Money(); + refund.Fees.Amount = payIn.Fees.Amount; + refund.Fees.Currency = payIn.Fees.Currency; + + return this._api.PayIns.createRefund(payIn.Id, refund); + } + + /** + * Creates card registration object. + * @return CardRegistration instance returned from API. + */ + protected CardRegistration getJohnsCardRegistration() throws Exception { + if (BaseTest._johnsCardRegistration == null) { + UserNatural user = this.getJohn(); + + CardRegistration cardRegistration = new CardRegistration(); + cardRegistration.UserId = user.Id; + cardRegistration.Currency = "EUR"; + + BaseTest._johnsCardRegistration = this._api.CardRegistrations.create(cardRegistration); + } + + return BaseTest._johnsCardRegistration; + } + + /** + * Creates card registration object. + */ + protected CardPreAuthorization getJohnsCardPreAuthorization() throws Exception { + UserNatural user = this.getJohn(); + CardRegistration cardRegistration = new CardRegistration(); + cardRegistration.UserId = user.Id; + cardRegistration.Currency = "EUR"; + CardRegistration newCardRegistration = this._api.CardRegistrations.create(cardRegistration); + + String registrationData = this.getPaylineCorrectRegistartionData(newCardRegistration); + newCardRegistration.RegistrationData = registrationData; + CardRegistration getCardRegistration = this._api.CardRegistrations.update(newCardRegistration); + + CardPreAuthorization cardPreAuthorization = new CardPreAuthorization(); + cardPreAuthorization.AuthorId = user.Id; + cardPreAuthorization.DebitedFunds = new Money(); + cardPreAuthorization.DebitedFunds.Currency = "EUR"; + cardPreAuthorization.DebitedFunds.Amount = 10000.0; + cardPreAuthorization.CardId = getCardRegistration.CardId; + cardPreAuthorization.SecureModeReturnURL = "http://test.com"; + + return this._api.CardPreAuthorizations.create(cardPreAuthorization); + } + + protected KycDocument getJohnsKycDocument() throws Exception { + if (BaseTest._johnsKycDocument == null) { + String johnsId = this.getJohn().Id; + + BaseTest._johnsKycDocument = this._api.Users.createKycDocument(johnsId, KycDocumentType.IDENTITY_PROOF); + } + + return BaseTest._johnsKycDocument; + } + + /** + * Gets registration data from Payline service. + * @param cardRegistration + * @return Registration data. + */ + protected String getPaylineCorrectRegistartionData(CardRegistration cardRegistration) throws MalformedURLException, IOException, Exception { + + String data = "data=" + cardRegistration.PreregistrationData + + "&accessKeyRef=" + cardRegistration.AccessKey + + "&cardNumber=4970100000000154" + + "&cardExpirationDate=1214" + + "&cardCvx=123"; + + URL url = new URL(cardRegistration.CardRegistrationURL); + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + + connection.setRequestMethod("POST"); + connection.setUseCaches (false); + connection.setDoInput(true); + connection.setDoOutput(true); + + try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { + wr.writeBytes(data); + wr.flush (); + } + + int responseCode = connection.getResponseCode(); + InputStream is; + if (responseCode != 200) { + is = connection.getErrorStream(); + } else { + is = connection.getInputStream(); + } + + StringBuffer resp; + try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) { + String line; + resp = new StringBuffer(); + while((line = rd.readLine()) != null) { + resp.append(line); + } + } + String responseString = resp.toString(); + + if (responseCode == 200) + return responseString; + else + throw new Exception(responseString); + } + + protected Hook getJohnsHook() throws Exception { + if (BaseTest._johnsHook == null) { + + Pagination pagination = new Pagination(1, 1); + List list = this._api.Hooks.getAll(pagination); + + if (list != null && list.size() > 0 && list.get(0) != null) { + BaseTest._johnsHook = list.get(0); + } else { + Hook hook = new Hook(); + hook.EventType = EventType.PAYIN_NORMAL_CREATED; + hook.Url = "http://test.com"; + BaseTest._johnsHook = this._api.Hooks.create(hook); + } + } + + return BaseTest._johnsHook; + } + + protected void assertEqualInputProps(T entity1, T entity2) throws Exception { + + if (entity1 instanceof UserNatural) { + assertEquals(((UserNatural)entity1).Tag, ((UserNatural)entity2).Tag); + assertEquals(((UserNatural)entity1).PersonType, ((UserNatural)entity2).PersonType); + assertEquals(((UserNatural)entity1).FirstName, ((UserNatural)entity2).FirstName); + assertEquals(((UserNatural)entity1).LastName, ((UserNatural)entity2).LastName); + assertEquals(((UserNatural)entity1).Email, ((UserNatural)entity2).Email); + assertEquals(((UserNatural)entity1).Address, ((UserNatural)entity2).Address); + assertEquals(((UserNatural)entity1).Birthday, ((UserNatural)entity2).Birthday); + assertEquals(((UserNatural)entity1).Nationality, ((UserNatural)entity2).Nationality); + assertEquals(((UserNatural)entity1).CountryOfResidence, ((UserNatural)entity2).CountryOfResidence); + assertEquals(((UserNatural)entity1).Occupation, ((UserNatural)entity2).Occupation); + assertEquals(((UserNatural)entity1).IncomeRange, ((UserNatural)entity2).IncomeRange); + + } else if (entity1 instanceof UserLegal) { + assertEquals(((UserLegal)entity1).Tag, ((UserLegal)entity2).Tag); + assertEquals(((UserLegal)entity1).PersonType, ((UserLegal)entity2).PersonType); + assertEquals(((UserLegal)entity1).Name, ((UserLegal)entity2).Name); + assertEquals(((UserLegal)entity1).HeadquartersAddress, ((UserLegal)entity2).HeadquartersAddress); + assertEquals(((UserLegal)entity1).LegalRepresentativeFirstName, ((UserLegal)entity2).LegalRepresentativeFirstName); + assertEquals(((UserLegal)entity1).LegalRepresentativeLastName, ((UserLegal)entity2).LegalRepresentativeLastName); + assertEquals("***** TEMPORARY API ISSUE: RETURNED OBJECT MISSES THIS PROP AFTER CREATION *****", ((UserLegal)entity1).LegalRepresentativeAddress, ((UserLegal)entity2).LegalRepresentativeAddress); + assertEquals(((UserLegal)entity1).LegalRepresentativeEmail, ((UserLegal)entity2).LegalRepresentativeEmail); + //assertEquals("***** TEMPORARY API ISSUE: RETURNED OBJECT HAS THIS PROP CHANGED FROM TIMESTAMP INTO ISO STRING AFTER CREATION *****", ((UserLegal)entity1).LegalRepresentativeBirthday, ((UserLegal)entity2).LegalRepresentativeBirthday); + assertEquals(((UserLegal)entity1).LegalRepresentativeBirthday, ((UserLegal)entity2).LegalRepresentativeBirthday); + assertEquals(((UserLegal)entity1).LegalRepresentativeNationality, ((UserLegal)entity2).LegalRepresentativeNationality); + assertEquals(((UserLegal)entity1).LegalRepresentativeCountryOfResidence, ((UserLegal)entity2).LegalRepresentativeCountryOfResidence); + + } else if (entity1 instanceof BankAccount) { + assertEquals(((BankAccount)entity1).Tag, ((BankAccount)entity2).Tag); + assertEquals(((BankAccount)entity1).UserId, ((BankAccount)entity2).UserId); + assertEquals(((BankAccount)entity1).Type, ((BankAccount)entity2).Type); + assertEquals(((BankAccount)entity1).OwnerName, ((BankAccount)entity2).OwnerName); + assertEquals(((BankAccount)entity1).OwnerAddress, ((BankAccount)entity2).OwnerAddress); + if (((BankAccount)entity1).Type.equals("IBAN")) { + assertEquals(((BankAccountDetailsIBAN)((BankAccount)entity1).Details).IBAN, ((BankAccountDetailsIBAN)((BankAccount)entity2).Details).IBAN); + assertEquals(((BankAccountDetailsIBAN)((BankAccount)entity1).Details).BIC, ((BankAccountDetailsIBAN)((BankAccount)entity2).Details).BIC); + } else if (((BankAccount)entity1).Type.equals("GB")) { + assertEquals(((BankAccountDetailsGB)((BankAccount)entity1).Details).AccountNumber, ((BankAccountDetailsGB)((BankAccount)entity2).Details).AccountNumber); + assertEquals(((BankAccountDetailsGB)((BankAccount)entity1).Details).SortCode, ((BankAccountDetailsGB)((BankAccount)entity2).Details).SortCode); + } else if (((BankAccount)entity1).Type.equals("US")) { + assertEquals(((BankAccountDetailsUS)((BankAccount)entity1).Details).AccountNumber, ((BankAccountDetailsUS)((BankAccount)entity2).Details).AccountNumber); + assertEquals(((BankAccountDetailsUS)((BankAccount)entity1).Details).ABA, ((BankAccountDetailsUS)((BankAccount)entity2).Details).ABA); + } else if (((BankAccount)entity1).Type.equals("CA")) { + assertEquals(((BankAccountDetailsCA)((BankAccount)entity1).Details).AccountNumber, ((BankAccountDetailsCA)((BankAccount)entity2).Details).AccountNumber); + assertEquals(((BankAccountDetailsCA)((BankAccount)entity1).Details).BankName, ((BankAccountDetailsCA)((BankAccount)entity2).Details).BankName); + assertEquals(((BankAccountDetailsCA)((BankAccount)entity1).Details).InstitutionNumber, ((BankAccountDetailsCA)((BankAccount)entity2).Details).InstitutionNumber); + assertEquals(((BankAccountDetailsCA)((BankAccount)entity1).Details).BranchCode, ((BankAccountDetailsCA)((BankAccount)entity2).Details).BranchCode); + } else if (((BankAccount)entity1).Type.equals("OTHER")) { + assertEquals(((BankAccountDetailsOTHER)((BankAccount)entity1).Details).AccountNumber, ((BankAccountDetailsOTHER)((BankAccount)entity2).Details).AccountNumber); + assertEquals(((BankAccountDetailsOTHER)((BankAccount)entity1).Details).Type, ((BankAccountDetailsOTHER)((BankAccount)entity2).Details).Type); + assertEquals(((BankAccountDetailsOTHER)((BankAccount)entity1).Details).Country, ((BankAccountDetailsOTHER)((BankAccount)entity2).Details).Country); + assertEquals(((BankAccountDetailsOTHER)((BankAccount)entity1).Details).BIC, ((BankAccountDetailsOTHER)((BankAccount)entity2).Details).BIC); + } + + } else if (entity1 instanceof PayIn) { + assertEquals(((PayIn)entity1).Tag, ((PayIn)entity2).Tag); + assertEquals(((PayIn)entity1).AuthorId, ((PayIn)entity2).AuthorId); + assertEquals(((PayIn)entity1).CreditedUserId, ((PayIn)entity2).CreditedUserId); + + assertEqualInputProps(((PayIn)entity1).DebitedFunds, ((PayIn)entity2).DebitedFunds); + assertEqualInputProps(((PayIn)entity1).CreditedFunds, ((PayIn)entity2).CreditedFunds); + assertEqualInputProps(((PayIn)entity1).Fees, ((PayIn)entity2).Fees); + + } else if (entity1 instanceof Card) { + assertEquals(((Card)entity1).ExpirationDate, ((Card)entity2).ExpirationDate); + assertEquals(((Card)entity1).Alias, ((Card)entity2).Alias); + assertEquals(((Card)entity1).CardType, ((Card)entity2).CardType); + assertEquals(((Card)entity1).Currency, ((Card)entity2).Currency); + + } else if (entity1 instanceof PayInPaymentDetailsCard) { + assertEquals(((PayInPaymentDetailsCard)entity1).CardType, ((PayInPaymentDetailsCard)entity2).CardType); + + } else if (entity1 instanceof PayInExecutionDetailsWeb) { + assertEquals(((PayInExecutionDetailsWeb)entity1).TemplateURL, ((PayInExecutionDetailsWeb)entity2).TemplateURL); + assertEquals(((PayInExecutionDetailsWeb)entity1).Culture, ((PayInExecutionDetailsWeb)entity2).Culture); + assertEquals(((PayInExecutionDetailsWeb)entity1).SecureMode, ((PayInExecutionDetailsWeb)entity2).SecureMode); + assertEquals(((PayInExecutionDetailsWeb)entity1).RedirectURL, ((PayInExecutionDetailsWeb)entity2).RedirectURL); + assertEquals(((PayInExecutionDetailsWeb)entity1).ReturnURL, ((PayInExecutionDetailsWeb)entity2).ReturnURL); + + } else if (entity1 instanceof PayOut) { + assertEquals(((PayOut)entity1).Tag, ((PayOut)entity2).Tag); + assertEquals(((PayOut)entity1).AuthorId, ((PayOut)entity2).AuthorId); + assertEquals(((PayOut)entity1).CreditedUserId, ((PayOut)entity2).CreditedUserId); + + assertEqualInputProps(((PayOut)entity1).DebitedFunds, ((PayOut)entity2).DebitedFunds); + assertEqualInputProps(((PayOut)entity1).CreditedFunds, ((PayOut)entity2).CreditedFunds); + assertEqualInputProps(((PayOut)entity1).Fees, ((PayOut)entity2).Fees); + assertEqualInputProps(((PayOut)entity1).MeanOfPaymentDetails, ((PayOut)entity2).MeanOfPaymentDetails); + + } else if (entity1 instanceof Transfer) { + assertEquals(((Transfer)entity1).Tag, ((Transfer)entity2).Tag); + assertEquals(((Transfer)entity1).AuthorId, ((Transfer)entity2).AuthorId); + assertEquals(((Transfer)entity1).CreditedUserId, ((Transfer)entity2).CreditedUserId); + + assertEqualInputProps(((Transfer)entity1).DebitedFunds, ((Transfer)entity2).DebitedFunds); + assertEqualInputProps(((Transfer)entity1).CreditedFunds, ((Transfer)entity2).CreditedFunds); + assertEqualInputProps(((Transfer)entity1).Fees, ((Transfer)entity2).Fees); + + } else if (entity1 instanceof PayOutPaymentDetailsBankWire) { + assertEquals(((PayOutPaymentDetailsBankWire)entity1).BankAccountId, ((PayOutPaymentDetailsBankWire)entity2).BankAccountId); + assertEquals(((PayOutPaymentDetailsBankWire)entity1).Communication, ((PayOutPaymentDetailsBankWire)entity2).Communication); + + } else if (entity1 instanceof Transaction) { + assertEquals(((Transaction)entity1).Tag, ((Transaction)entity2).Tag); + + assertEqualInputProps(((Transaction)entity1).DebitedFunds, ((Transaction)entity2).DebitedFunds); + assertEqualInputProps(((Transaction)entity1).Fees, ((Transaction)entity2).Fees); + assertEqualInputProps(((Transaction)entity1).CreditedFunds, ((Transaction)entity2).CreditedFunds); + + assertEquals(((Transaction)entity1).Status, ((Transaction)entity2).Status); + + } else if (entity1 instanceof Money) { + assertEquals(((Money)entity1).Currency, ((Money)entity2).Currency); + assertEquals(((Money)entity1).Amount, ((Money)entity2).Amount); + } else { + throw new Exception("Unsupported type"); + } + + } + +}