diff --git a/pom.xml b/pom.xml index 4421910..d5e5fab 100644 --- a/pom.xml +++ b/pom.xml @@ -42,12 +42,12 @@ ignore wso2-nexus - http://maven.wso2.org/nexus/content/groups/wso2-public/ + https://maven.wso2.org/nexus/content/groups/wso2-public/ - 9.0.17 + 9.20.1 2.6 9.8.0 diff --git a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationConstants.java b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationConstants.java index fa01038..dc8ec59 100644 --- a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationConstants.java +++ b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationConstants.java @@ -61,7 +61,7 @@ public class StripeMonetizationConstants { " INSERT" + " INTO AM_MONETIZATION_SUBSCRIPTIONS (SUBSCRIBED_API_ID, SUBSCRIBED_APPLICATION_ID," + " TENANT_ID, SHARED_CUSTOMER_ID, SUBSCRIPTION_ID)" + - " VALUES (?,?,?,?,?)"; + " VALUES ((SELECT API_ID FROM AM_API WHERE API_UUID = ?),?,?,?,?)"; public static final String GET_BE_PLATFORM_CUSTOMER_SQL = "SELECT" + @@ -82,7 +82,9 @@ public class StripeMonetizationConstants { " ID, SUBSCRIPTION_ID" + " FROM AM_MONETIZATION_SUBSCRIPTIONS" + " WHERE" + - " SUBSCRIBED_APPLICATION_ID=? AND SUBSCRIBED_API_ID=? AND TENANT_ID=?"; + " SUBSCRIBED_APPLICATION_ID=? " + + " AND SUBSCRIBED_API_ID=(SELECT API_ID FROM AM_API WHERE API_UUID=?)" + + " AND TENANT_ID=?"; public static final String DELETE_BE_SUBSCRIPTION_SQL = "DELETE FROM AM_MONETIZATION_SUBSCRIPTIONS WHERE ID=?"; @@ -143,10 +145,12 @@ public class StripeMonetizationConstants { public static final String TIME_FILTER = "timeFilter"; public static final String API_USAGE_BY_APP_FILTER = "successAPIUsageByAppFilter"; public static final String API_NAME = "apiName"; + public static final String API_UUID = "apiId"; public static final String API_VERSION = "apiVersion"; public static final String TENANT_DOMAIN = "apiCreatorTenantDomain"; public static final String COUNT = "count"; public static final String APPLICATION_NAME = "applicationName"; public static final String APPLICATION_OWNER = "applicationOwner"; public static final String GET_USAGE_BY_APPLICATION = "getSuccessAPIsUsageByApplications"; + public static final String AT = "@"; } diff --git a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationDAO.java b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationDAO.java index e89ab5f..73300a9 100644 --- a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationDAO.java +++ b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationDAO.java @@ -628,29 +628,22 @@ public int addBESharedCustomer(MonetizationSharedCustomer sharedCustomer) throws * @param tenandId Id of the tenant * @param sharedCustomerId Id of the shared customer * @param subscriptionId Id of the Billing Engine Subscriptions + * @param apiUuid UUID of the API * @return Id of the customer record in the database * @throws StripeMonetizationException If Failed To add Billing Engine Shared Customer details */ - public void addBESubscription(APIIdentifier identifier, int applicationId, int tenandId, - int sharedCustomerId, String subscriptionId) throws StripeMonetizationException { + public void addBESubscription(APIIdentifier identifier, int applicationId, int tenandId, int sharedCustomerId, + String subscriptionId, String apiUuid) throws StripeMonetizationException { Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; - int apiId; try { conn = APIMgtDBUtil.getConnection(); conn.setAutoCommit(false); - try { - apiId = apiMgtDAO.getAPIID(identifier, conn); - } catch (APIManagementException e) { - String errorMessage = "Failed to get the ID of the API " + identifier.getApiName(); - log.error(errorMessage); - throw new StripeMonetizationException(errorMessage, e); - } String query = StripeMonetizationConstants.ADD_BE_SUBSCRIPTION_SQL; ps = conn.prepareStatement(query); - ps.setInt(1, apiId); + ps.setString(1, apiUuid); ps.setInt(2, applicationId); ps.setInt(3, tenandId); ps.setInt(4, sharedCustomerId); @@ -779,38 +772,27 @@ public void removeMonetizedSubscription(int id) throws StripeMonetizationExcepti /** * Get billing engine Subscription info * + * @param apiUuid UUID of the API * @param apiName api name - * @param apiVersion api version - * @param apiProvider api provider * @param applicationId Id of the Application * @param tenantDomain tenant domain * @return MonetizationSubscription info of Billing Engine Subscription * @throws StripeMonetizationException If Failed To get Billing Engine Subscription details */ - public MonetizedSubscription getMonetizedSubscription(String apiName, String apiVersion, String apiProvider, - int applicationId, String tenantDomain) - throws StripeMonetizationException { + public MonetizedSubscription getMonetizedSubscription(String apiUuid, String apiName, int applicationId, + String tenantDomain) throws StripeMonetizationException { Connection conn = null; PreparedStatement ps = null; ResultSet result = null; - int apiId; MonetizedSubscription monetizedSubscription = new MonetizedSubscription(); int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain); - APIIdentifier identifier = new APIIdentifier(apiProvider, apiName, apiVersion); String sqlQuery = StripeMonetizationConstants.GET_BE_SUBSCRIPTION_SQL; try { conn = APIMgtDBUtil.getConnection(); - try { - apiId = apiMgtDAO.getAPIID(identifier, conn); - } catch (APIManagementException e) { - String errorMessgae = "Failed to get ID for API : " + apiName; - log.error(errorMessgae); - throw new StripeMonetizationException(errorMessgae, e); - } ps = conn.prepareStatement(sqlQuery); ps.setInt(1, applicationId); - ps.setInt(2, apiId); + ps.setString(2, apiUuid); ps.setInt(3, tenantId); result = ps.executeQuery(); if (result.next()) { diff --git a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationImpl.java b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationImpl.java index e9918d4..8a90b14 100644 --- a/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationImpl.java +++ b/src/main/java/org.wso2.apim.monetization/impl/StripeMonetizationImpl.java @@ -71,13 +71,13 @@ import org.wso2.carbon.apimgt.persistence.dto.UserContext; import org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException; import org.wso2.carbon.apimgt.persistence.mapper.APIMapper; -import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.nio.charset.Charset; import java.sql.Connection; @@ -445,7 +445,7 @@ public boolean enableMonetization(String tenantDomain, API api, Map getMonetizedPoliciesToPlanMapping(API api) throws Mon try { String apiName = api.getId().getApiName(); Connection con = APIMgtDBUtil.getConnection(); - int apiId = ApiMgtDAO.getInstance().getAPIID(api.getId(), con); + int apiId = ApiMgtDAO.getInstance().getAPIID(api.getUuid(), con); //get billing engine product ID for that API String billingProductIdForApi = getBillingProductIdForApi(apiId); if (StringUtils.isEmpty(billingProductIdForApi)) { @@ -636,6 +636,7 @@ public Map getMonetizedPoliciesToPlanMapping(API api) throws Mon public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo lastPublishInfo) throws MonetizationException { + String apiUuid = null; String apiName = null; String apiVersion = null; String tenantDomain = null; @@ -683,6 +684,7 @@ public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo last String key = entry.getKey(); ArrayList> apiUsageDataCollection = entry.getValue(); for (LinkedTreeMap apiUsageData : apiUsageDataCollection) { + apiUuid = apiUsageData.get(StripeMonetizationConstants.API_UUID); apiName = apiUsageData.get(StripeMonetizationConstants.API_NAME); apiVersion = apiUsageData.get(StripeMonetizationConstants.API_VERSION); tenantDomain = apiUsageData.get(StripeMonetizationConstants.TENANT_DOMAIN); @@ -693,13 +695,14 @@ public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo last apiProvider = apiMgtDAO.getAPIProviderByNameAndVersion(apiName, apiVersion, tenantDomain); } catch (APIManagementException e) { throw new MonetizationException("Error while retrieving Application Id for " + - "Applictaion " + applicationName, e); + "Application " + applicationName, e); } requestCount = Long.parseLong(apiUsageData.get(StripeMonetizationConstants.COUNT)); try { //get the billing engine subscription details - MonetizedSubscription subscription = stripeMonetizationDAO.getMonetizedSubscription(apiName, - apiVersion, apiProvider, applicationId, tenantDomain); + MonetizedSubscription subscription = stripeMonetizationDAO + .getMonetizedSubscription(apiUuid, apiName, applicationId, + tenantDomain); if (subscription.getSubscriptionId() != null) { try { //start the tenant flow to get the platform key @@ -723,9 +726,8 @@ public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo last PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenantDomain, true); apiProvider = APIUtil.replaceEmailDomain(apiProvider); - APIIdentifier identifier = new APIIdentifier(apiProvider, apiName, apiVersion); APIProvider apiProvider1 = APIManagerFactory.getInstance().getAPIProvider(apiProvider); - API api = apiProvider1.getAPI(identifier); + API api = apiProvider1.getAPIbyUUID(apiUuid, tenantDomain); Map monetizationProperties = new Gson().fromJson( api.getMonetizationProperties().toString(), HashMap.class); //get api publisher's stripe key (i.e - connected account key) from monetization @@ -868,7 +870,15 @@ LinkedTreeMap>> getUsageData( try { Properties properties = new Properties(); properties.put(APIConstants.ALLOW_MULTIPLE_STATUS, APIUtil.isAllowDisplayAPIsWithMultipleStatus()); - apiPersistenceInstance = PersistenceManager.getPersistenceInstance(properties); + Map configMap = new HashMap<>(); + Map configs = APIManagerConfiguration.getPersistenceProperties(); + if (configs != null && !configs.isEmpty()) { + configMap.putAll(configs); + } + configMap.put(APIConstants.ALLOW_MULTIPLE_STATUS, + Boolean.toString(APIUtil.isAllowDisplayAPIsWithMultipleStatus())); + + apiPersistenceInstance = PersistenceManager.getPersistenceInstance(configMap, properties); List tenants = APIUtil.getAllTenantsWithSuperTenant(); for (Tenant tenant : tenants) { tenantDomains.add(tenant.getDomain()); @@ -876,7 +886,12 @@ LinkedTreeMap>> getUsageData( PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenant.getDomain(), true); - APIProvider apiProviderNew = RestApiCommonUtil.getProvider(APIUtil.getAdminUsername()); + String tenantAdminUsername = APIUtil.getAdminUsername(); + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenant.getDomain())) { + tenantAdminUsername = + APIUtil.getAdminUsername() + StripeMonetizationConstants.AT + tenant.getDomain(); + } + APIProvider apiProviderNew = APIManagerFactory.getInstance().getAPIProvider(tenantAdminUsername); List allowedAPIs = apiProviderNew.getAllAPIs(); Organization org = new Organization(tenant.getDomain()); for (API api : allowedAPIs) { @@ -939,7 +954,7 @@ public Map getCurrentUsageForSubscription(String subscriptionUUI HashMap monetizationDataMap; int apiId; if (apiIdentifier != null) { - api = apiProvider.getAPI(apiIdentifier); + api = apiProvider.getAPIbyUUID(apiIdentifier.getUUID(), apiIdentifier.getOrganization()); apiName = apiIdentifier.getApiName(); if (api.getMonetizationProperties() == null) { String errorMessage = "Monetization properties are empty for : " + apiName; @@ -952,7 +967,7 @@ public Map getCurrentUsageForSubscription(String subscriptionUUI //throw MonetizationException as it will be logged and handled by the caller throw new MonetizationException(errorMessage); } - apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, APIMgtDBUtil.getConnection()); + apiId = ApiMgtDAO.getInstance().getAPIID(api.getUuid(), APIMgtDBUtil.getConnection()); } else { apiProductIdentifier = subscribedAPI.getProductId(); apiProduct = apiProvider.getAPIProduct(apiProductIdentifier); @@ -1104,13 +1119,15 @@ public Map getTotalRevenue(API api, APIProvider apiProvider) thr Map revenueData = new HashMap(); try { //get all subscriptions for the API - List apiUsages = apiProvider.getAPIUsageByAPIId(apiIdentifier); + List apiUsages = apiProvider.getAPIUsageByAPIId(api.getUuid(), + api.getId().getOrganization()); for (SubscribedAPI subscribedAPI : apiUsages) { //get subscription UUID for each subscription int subscriptionId = subscribedAPI.getSubscriptionId(); String subscriptionUUID = stripeMonetizationDAO.getSubscriptionUUID(subscriptionId); //get revenue for each subscription and add them - Map billingEngineUsageData = getCurrentUsageForSubscription(subscriptionUUID, apiProvider); + Map billingEngineUsageData = getCurrentUsageForSubscription(subscriptionUUID, + apiProvider); revenueData.put("Revenue for subscription ID : " + subscriptionId, billingEngineUsageData.get("amount_due")); } @@ -1136,39 +1153,23 @@ public Map getTotalRevenue(API api, APIProvider apiProvider) thr private String getStripePlatformAccountKey(String tenantDomain) throws StripeMonetizationException { try { - int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager(). - getTenantId(tenantDomain); - Registry configRegistry = ServiceReferenceHolder.getInstance().getRegistryService(). - getConfigSystemRegistry(tenantId); - if (configRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) { - Resource resource = configRegistry.get(APIConstants.API_TENANT_CONF_LOCATION); - String tenantConfContent = new String((byte[]) resource.getContent(), Charset.defaultCharset()); - if (StringUtils.isBlank(tenantConfContent)) { - String errorMessage = "Tenant configuration for tenant " + tenantDomain + - " cannot be empty when configuring monetization."; - throw new StripeMonetizationException(errorMessage); - } - //get the stripe key of platform account from tenant conf json file - JSONObject tenantConfig = (JSONObject) new JSONParser().parse(tenantConfContent); - JSONObject monetizationInfo = (JSONObject) tenantConfig.get(StripeMonetizationConstants.MONETIZATION_INFO); - String stripePlatformAccountKey = monetizationInfo.get - (StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); - if (StringUtils.isBlank(stripePlatformAccountKey)) { - String errorMessage = "Stripe platform account key is empty for tenant : " + tenantDomain; - throw new StripeMonetizationException(errorMessage); + //get the stripe key of platform account from tenant conf json file + JSONObject tenantConfig = APIUtil.getTenantConfig(tenantDomain); + if (tenantConfig.containsKey(StripeMonetizationConstants.MONETIZATION_INFO)) { + JSONObject monetizationInfo = (JSONObject) tenantConfig + .get(StripeMonetizationConstants.MONETIZATION_INFO); + if (monetizationInfo.containsKey(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY)) { + String stripePlatformAccountKey = monetizationInfo + .get(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); + if (StringUtils.isBlank(stripePlatformAccountKey)) { + String errorMessage = "Stripe platform account key is empty for tenant : " + tenantDomain; + throw new StripeMonetizationException(errorMessage); + } + return stripePlatformAccountKey; } - return stripePlatformAccountKey; } - } catch (ParseException e) { - String errorMessage = "Error while parsing tenant configuration in tenant : " + tenantDomain; - log.error(errorMessage); - throw new StripeMonetizationException(errorMessage, e); - } catch (UserStoreException e) { - String errorMessage = "Failed to get the corresponding tenant configurations for tenant : " + tenantDomain; - log.error(errorMessage); - throw new StripeMonetizationException(errorMessage, e); - } catch (RegistryException e) { - String errorMessage = "Failed to get the configuration registry for tenant : " + tenantDomain; + } catch (APIManagementException e) { + String errorMessage = "Failed to get the configuration for tenant from DB: " + tenantDomain; log.error(errorMessage); throw new StripeMonetizationException(errorMessage, e); } @@ -1273,7 +1274,15 @@ private long getTimestamp(String date) { public List getAllAPIs(String tenantDomain, String username) throws APIManagementException { Properties persistenceProperties = new Properties(); - APIPersistence apiPersistenceInstance = PersistenceManager.getPersistenceInstance(persistenceProperties); + Map configMap = new HashMap<>(); + Map configs = APIManagerConfiguration.getPersistenceProperties(); + if (configs != null && !configs.isEmpty()) { + configMap.putAll(configs); + } + configMap.put(APIConstants.ALLOW_MULTIPLE_STATUS, + Boolean.toString(APIUtil.isAllowDisplayAPIsWithMultipleStatus())); + APIPersistence apiPersistenceInstance = PersistenceManager + .getPersistenceInstance(configMap, persistenceProperties); List apiSortedList = new ArrayList(); Organization org = new Organization(tenantDomain); String[] roles = APIUtil.getFilteredUserRoles(username); @@ -1281,7 +1290,7 @@ public List getAllAPIs(String tenantDomain, String username) throws APIMana UserContext userCtx = new UserContext(username, org, properties, roles); try { PublisherAPISearchResult searchAPIs = apiPersistenceInstance.searchAPIsForPublisher(org, "", 0, - Integer.MAX_VALUE, userCtx); + Integer.MAX_VALUE, userCtx, null, null); if (searchAPIs != null) { List list = searchAPIs.getPublisherAPIInfoList(); diff --git a/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionCreationWorkflowExecutor.java b/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionCreationWorkflowExecutor.java index 03a277d..0de4ea2 100644 --- a/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionCreationWorkflowExecutor.java +++ b/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionCreationWorkflowExecutor.java @@ -43,6 +43,7 @@ import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.Subscriber; import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; @@ -135,7 +136,14 @@ public WorkflowResponse monetizeSubscription(WorkflowDTO workflowDTO, API api) t Properties properties = new Properties(); properties.put(APIConstants.ALLOW_MULTIPLE_STATUS, APIUtil.isAllowDisplayAPIsWithMultipleStatus()); - apiPersistenceInstance = PersistenceManager.getPersistenceInstance(properties); + Map configMap = new HashMap<>(); + Map configs = APIManagerConfiguration.getPersistenceProperties(); + if (configs != null && !configs.isEmpty()) { + configMap.putAll(configs); + } + configMap.put(APIConstants.ALLOW_MULTIPLE_STATUS, + Boolean.toString(APIUtil.isAllowDisplayAPIsWithMultipleStatus())); + apiPersistenceInstance = PersistenceManager.getPersistenceInstance(configMap, properties); //read the platform account key of Stripe Stripe.apiKey = getPlatformAccountKey(subWorkFlowDTO.getTenantId()); @@ -184,9 +192,9 @@ public WorkflowResponse monetizeSubscription(WorkflowDTO workflowDTO, API api) t requestOptions, subWorkFlowDTO); } //creating Subscriptions - int apiId = ApiMgtDAO.getInstance().getAPIID(api.getId(), APIMgtDBUtil.getConnection()); + int apiId = ApiMgtDAO.getInstance().getAPIID(api.getUuid(), APIMgtDBUtil.getConnection()); String planId = stripeMonetizationDAO.getBillingEnginePlanIdForTier(apiId, subWorkFlowDTO.getTierName()); - createMonetizedSubscriptions(planId, monetizationSharedCustomer, requestOptions, subWorkFlowDTO); + createMonetizedSubscriptions(planId, monetizationSharedCustomer, requestOptions, subWorkFlowDTO, api.getUuid()); } catch (APIManagementException e) { String errorMessage = "Could not monetize subscription for API : " + subWorkFlowDTO.getApiName() + " by Application : " + subWorkFlowDTO.getApplicationName(); @@ -260,7 +268,7 @@ public WorkflowResponse monetizeSubscription(WorkflowDTO workflowDTO, APIProduct //creating Subscriptions int apiId = ApiMgtDAO.getInstance().getAPIProductId(apiProduct.getId()); String planId = stripeMonetizationDAO.getBillingEnginePlanIdForTier(apiId, subWorkFlowDTO.getTierName()); - createMonetizedSubscriptions(planId, monetizationSharedCustomer, requestOptions, subWorkFlowDTO); + createMonetizedSubscriptions(planId, monetizationSharedCustomer, requestOptions, subWorkFlowDTO, apiProduct.getUuid()); } catch (APIManagementException e) { String errorMessage = "Could not monetize subscription for : " + subWorkFlowDTO.getApiName() + " by application : " + subWorkFlowDTO.getApplicationName(); @@ -285,32 +293,25 @@ public WorkflowResponse monetizeSubscription(WorkflowDTO workflowDTO, APIProduct private String getPlatformAccountKey(int tenantId) throws WorkflowException { String stripePlatformAccountKey = null; + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); try { - Registry configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry( - tenantId); - if (configRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) { - Resource resource = configRegistry.get(APIConstants.API_TENANT_CONF_LOCATION); - String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); - - if (StringUtils.isBlank(content)) { - String errorMessage = "Tenant configuration cannot be empty when configuring monetization."; - throw new WorkflowException(errorMessage); - } - //get the stripe key of patform account from tenant conf file - JSONObject tenantConfig = (JSONObject) new JSONParser().parse(content); - JSONObject monetizationInfo = (JSONObject) tenantConfig.get( - StripeMonetizationConstants.MONETIZATION_INFO); - stripePlatformAccountKey = monetizationInfo.get( - StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); - - if (StringUtils.isBlank(stripePlatformAccountKey)) { - throw new WorkflowException("stripePlatformAccountKey is empty!!!"); + //get the stripe key of platform account from tenant conf json file + JSONObject tenantConfig = APIUtil.getTenantConfig(tenantDomain); + if (tenantConfig.containsKey(StripeMonetizationConstants.MONETIZATION_INFO)) { + JSONObject monetizationInfo = (JSONObject) tenantConfig + .get(StripeMonetizationConstants.MONETIZATION_INFO); + if (monetizationInfo.containsKey(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY)) { + stripePlatformAccountKey = monetizationInfo + .get(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); + if (StringUtils.isBlank(stripePlatformAccountKey)) { + String errorMessage = "Stripe platform account key is empty for tenant : " + tenantDomain; + throw new WorkflowException(errorMessage); + } + return stripePlatformAccountKey; } } - } catch (RegistryException ex) { - throw new WorkflowException("Could not get all registry objects : ", ex); - } catch (org.json.simple.parser.ParseException ex) { - throw new WorkflowException("Could not get Stripe Platform key : ", ex); + } catch (APIManagementException e) { + throw new WorkflowException("Failed to get the configuration for tenant from DB: " + tenantDomain, e); } return stripePlatformAccountKey; } @@ -396,7 +397,7 @@ public MonetizationSharedCustomer createSharedCustomer(String email, Monetizatio * @throws WorkflowException */ public void createMonetizedSubscriptions(String planId, MonetizationSharedCustomer sharedCustomer, - RequestOptions requestOptions, SubscriptionWorkflowDTO subWorkFlowDTO) + RequestOptions requestOptions, SubscriptionWorkflowDTO subWorkFlowDTO, String apiUuid) throws WorkflowException { StripeMonetizationDAO stripeMonetizationDAO = StripeMonetizationDAO.getInstance(); @@ -413,7 +414,7 @@ public void createMonetizedSubscriptions(String planId, MonetizationSharedCustom subParams.put(StripeMonetizationConstants.CUSTOMER, sharedCustomer.getSharedCustomerId()); subParams.put(StripeMonetizationConstants.ITEMS, items); try { - //create a subscritpion in stripe under the API Providers Connected Account + //create a subscription in stripe under the API Providers Connected Account subscription = Subscription.create(subParams, requestOptions); } catch (StripeException ex) { String errorMsg = "Error when adding a subscription in Stripe for Application : " + @@ -423,7 +424,7 @@ public void createMonetizedSubscriptions(String planId, MonetizationSharedCustom } try { stripeMonetizationDAO.addBESubscription(identifier, subWorkFlowDTO.getApplicationId(), - subWorkFlowDTO.getTenantId(), sharedCustomer.getId(), subscription.getId()); + subWorkFlowDTO.getTenantId(), sharedCustomer.getId(), subscription.getId(), apiUuid); } catch (StripeMonetizationException e) { //delete the subscription in Stripe, if the entry to database fails in API Manager subscription.cancel((Map) null, requestOptions); diff --git a/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionDeletionWorkflowExecutor.java b/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionDeletionWorkflowExecutor.java index aa712b7..8eda23f 100644 --- a/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionDeletionWorkflowExecutor.java +++ b/src/main/java/org.wso2.apim.monetization/impl/workflow/StripeSubscriptionDeletionWorkflowExecutor.java @@ -37,6 +37,7 @@ import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; @@ -113,7 +114,14 @@ public WorkflowResponse deleteMonetizedSubscription(WorkflowDTO workflowDTO, API subWorkflowDTO = (SubscriptionWorkflowDTO) workflowDTO; Properties properties = new Properties(); properties.put(APIConstants.ALLOW_MULTIPLE_STATUS, APIUtil.isAllowDisplayAPIsWithMultipleStatus()); - apiPersistenceInstance = PersistenceManager.getPersistenceInstance(properties); + Map configMap = new HashMap<>(); + Map configs = APIManagerConfiguration.getPersistenceProperties(); + if (configs != null && !configs.isEmpty()) { + configMap.putAll(configs); + } + configMap.put(APIConstants.ALLOW_MULTIPLE_STATUS, + Boolean.toString(APIUtil.isAllowDisplayAPIsWithMultipleStatus())); + apiPersistenceInstance = PersistenceManager.getPersistenceInstance(configMap, properties); //read the platform key of Stripe Stripe.apiKey = getPlatformAccountKey(subWorkflowDTO.getTenantId()); String connectedAccountKey = StringUtils.EMPTY; @@ -146,9 +154,9 @@ public WorkflowResponse deleteMonetizedSubscription(WorkflowDTO workflowDTO, API RequestOptions requestOptions = RequestOptions.builder().setStripeAccount(connectedAccountKey).build(); try { //get the stripe subscription id - monetizedSubscription = stripeMonetizationDAO.getMonetizedSubscription(subWorkflowDTO.getApiName(), - subWorkflowDTO.getApiVersion(), subWorkflowDTO.getApiProvider(), subWorkflowDTO.getApplicationId(), - subWorkflowDTO.getTenantDomain()); + monetizedSubscription = stripeMonetizationDAO + .getMonetizedSubscription(api.getUuid(), subWorkflowDTO.getApiName(), + subWorkflowDTO.getApplicationId(), subWorkflowDTO.getTenantDomain()); } catch (StripeMonetizationException ex) { String errorMessage = "Could not retrieve monetized subscription info for : " + subWorkflowDTO.getApplicationName() + " by Application : " + subWorkflowDTO.getApplicationName(); @@ -217,9 +225,9 @@ public WorkflowResponse deleteMonetizedSubscription(WorkflowDTO workflowDTO, API RequestOptions requestOptions = RequestOptions.builder().setStripeAccount(connectedAccountKey).build(); try { //get the stripe subscription id - monetizedSubscription = stripeMonetizationDAO.getMonetizedSubscription(subWorkflowDTO.getApiName(), - subWorkflowDTO.getApiVersion(), subWorkflowDTO.getApiProvider(), subWorkflowDTO.getApplicationId(), - subWorkflowDTO.getTenantDomain()); + monetizedSubscription = stripeMonetizationDAO + .getMonetizedSubscription(apiProduct.getUuid(), subWorkflowDTO.getApiName(), + subWorkflowDTO.getApplicationId(), subWorkflowDTO.getTenantDomain()); } catch (StripeMonetizationException ex) { String errorMessage = "Could not retrieve monetized subscription info for : " + subWorkflowDTO.getApplicationName() + " by application : " + subWorkflowDTO.getApplicationName(); @@ -266,32 +274,25 @@ public WorkflowResponse deleteMonetizedSubscription(WorkflowDTO workflowDTO, API private String getPlatformAccountKey(int tenantId) throws WorkflowException { String stripePlatformAccountKey = null; + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); try { - Registry configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry( - tenantId); - if (configRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) { - Resource resource = configRegistry.get(APIConstants.API_TENANT_CONF_LOCATION); - String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); - - if (StringUtils.isBlank(content)) { - String errorMessage = "Tenant configuration cannot be empty when configuring monetization."; - throw new WorkflowException(errorMessage); - } - //get the stripe key of patform account from tenant conf file - JSONObject tenantConfig = (JSONObject) new JSONParser().parse(content); - JSONObject monetizationInfo = (JSONObject) tenantConfig.get( - StripeMonetizationConstants.MONETIZATION_INFO); - stripePlatformAccountKey = monetizationInfo.get( - StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); - - if (StringUtils.isBlank(stripePlatformAccountKey)) { - throw new WorkflowException("stripePlatformAccountKey is empty!!!"); + //get the stripe key of platform account from tenant conf json file + JSONObject tenantConfig = APIUtil.getTenantConfig(tenantDomain); + if (tenantConfig.containsKey(StripeMonetizationConstants.MONETIZATION_INFO)) { + JSONObject monetizationInfo = (JSONObject) tenantConfig + .get(StripeMonetizationConstants.MONETIZATION_INFO); + if (monetizationInfo.containsKey(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY)) { + stripePlatformAccountKey = monetizationInfo + .get(StripeMonetizationConstants.BILLING_ENGINE_PLATFORM_ACCOUNT_KEY).toString(); + if (StringUtils.isBlank(stripePlatformAccountKey)) { + String errorMessage = "Stripe platform account key is empty for tenant : " + tenantDomain; + throw new WorkflowException(errorMessage); + } + return stripePlatformAccountKey; } } - } catch (RegistryException ex) { - throw new WorkflowException("Could not get all registry objects : ", ex); - } catch (org.json.simple.parser.ParseException ex) { - throw new WorkflowException("Could not get Stripe Platform key : ", ex); + } catch (APIManagementException e) { + throw new WorkflowException("Failed to get the configuration for tenant from DB: " + tenantDomain, e); } return stripePlatformAccountKey; }