Search in sources :

Example 6 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPI.

/**
 * Updates an existing API
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update API
 * @throws org.wso2.carbon.apimgt.api.FaultGatewaysException on Gateway Failure
 */
@Override
public void updateAPI(API api) throws APIManagementException, FaultGatewaysException {
    boolean isValid = isAPIUpdateValid(api);
    if (!isValid) {
        throw new APIManagementException(" User doesn't have permission for update");
    }
    API oldApi = getAPIbyUUID(api.getUuid(), api.getOrganization());
    String organization = api.getOrganization();
    if (!oldApi.getStatus().equals(api.getStatus())) {
        // Use changeAPIStatus for that kind of updates.
        throw new APIManagementException("Invalid API update operation involving API status changes");
    }
    validateKeyManagers(api);
    Gson gson = new Gson();
    Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
    if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
        Map<String, String> newMonetizationProperties = gson.fromJson(api.getMonetizationProperties().toString(), HashMap.class);
        if (newMonetizationProperties != null) {
            for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
                String newValue = newMonetizationProperties.get(entry.getKey());
                if (StringUtils.isAllBlank(newValue)) {
                    newMonetizationProperties.put(entry.getKey(), entry.getValue());
                }
            }
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
                api.setMonetizationProperties(jsonObj);
            } catch (ParseException e) {
                throw new APIManagementException("Error when parsing monetization properties ", e);
            }
        }
    }
    String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());
    // Update WSDL in the registry
    if (api.getWsdlUrl() != null && api.getWsdlResource() == null) {
        updateWsdlFromUrl(api);
    }
    if (api.getWsdlResource() != null) {
        updateWsdlFromResourceFile(api);
    }
    boolean updatePermissions = false;
    if (APIUtil.isAccessControlEnabled()) {
        if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
            updatePermissions = true;
        }
    } else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
        updatePermissions = true;
    }
    updateEndpointSecurity(oldApi, api);
    String apiUUid = updateApiArtifact(api, true, updatePermissions);
    api.setUuid(apiUUid);
    if (!oldApi.getContext().equals(api.getContext())) {
        api.setApiHeaderChanged(true);
    }
    int tenantId;
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    try {
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new APIManagementException("Error in retrieving Tenant Information while updating api :" + api.getId().getApiName(), e);
    }
    validateResourceThrottlingTiers(api, tenantDomain);
    // get product resource mappings on API before updating the API. Update uri templates on api will remove all
    // product mappings as well.
    List<APIProductResource> productResources = apiMgtDAO.getProductMappingsForAPI(api);
    updateAPI(api, tenantId, userNameWithoutChange);
    updateProductResourceMappings(api, organization, productResources);
    if (log.isDebugEnabled()) {
        log.debug("Successfully updated the API: " + api.getId() + " in the database");
    }
    JSONObject apiLogObject = new JSONObject();
    apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
    apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
    apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
    apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
    // update doc visibility
    List<Documentation> docsList = getAllDocumentation(api.getId());
    if (docsList != null) {
        Iterator it = docsList.iterator();
        while (it.hasNext()) {
            Object docsObject = it.next();
            Documentation docs = (Documentation) docsObject;
            updateDocVisibility(api, docs);
        }
    }
    // notify key manager with API update
    registerOrUpdateResourceInKeyManager(api, tenantDomain);
    int apiId = apiMgtDAO.getAPIID(api.getUuid());
    if (publishedDefaultVersion != null) {
        if (api.isPublishedDefaultVersion() && !api.getId().getVersion().equals(publishedDefaultVersion)) {
            APIIdentifier previousDefaultVersionIdentifier = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), publishedDefaultVersion);
            sendUpdateEventToPreviousDefaultVersion(previousDefaultVersionIdentifier, organization);
        }
    }
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.ADD_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
}
Also used : RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Gson(com.google.gson.Gson) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Iterator(java.util.Iterator) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 7 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIUtil method createAPIArtifactContent.

/**
 * Create Governance artifact from given attributes
 *
 * @param artifact initial governance artifact
 * @param api      API object with the attributes value
 * @return GenericArtifact
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to create API
 */
public static GenericArtifact createAPIArtifactContent(GenericArtifact artifact, API api) throws APIManagementException {
    try {
        String apiStatus = api.getStatus();
        artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, api.getId().getApiName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, api.getId().getVersion());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, api.getContext());
        artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, api.getId().getProviderName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
        artifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_WADL, api.getWadlUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, api.getThumbnailUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiStatus);
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, api.getTechnicalOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, api.getTechnicalOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, api.getBusinessOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, api.getBusinessOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, api.getVisibility());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, api.getVisibleRoles());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, api.getVisibleTenants());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED, Boolean.toString(api.isEndpointSecured()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST, Boolean.toString(api.isEndpointAuthDigest()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME, api.getEndpointUTUsername());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD, api.getEndpointUTPassword());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, api.getTransports());
        artifact.setAttribute(APIConstants.API_OVERVIEW_INSEQUENCE, api.getInSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE, api.getOutSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE, api.getFaultSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, api.getResponseCache());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(api.getCacheTimeout()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL, api.getRedirectURL());
        artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT, api.getApiExternalProductionEndpoint());
        artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT, api.getApiExternalSandboxEndpoint());
        artifact.setAttribute(APIConstants.API_OVERVIEW_OWNER, api.getApiOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY, Boolean.toString(api.isAdvertiseOnly()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG, api.getEndpointConfig());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, api.getSubscriptionAvailability());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, api.getSubscriptionAvailableTenants());
        artifact.setAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION, api.getImplementation());
        artifact.setAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS, api.getProductionMaxTps());
        artifact.setAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS, api.getSandboxMaxTps());
        artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, api.getAuthorizationHeader());
        artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, api.getApiSecurity());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(api.isEnabledSchemaValidation()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(api.isEnableStore()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_TESTKEY, api.getTestKey());
        // Validate if the API has an unsupported context before setting it in the artifact
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
            String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
            if (invalidContext.equals(api.getContextTemplate())) {
                throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
            }
        } else {
            String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
            if (invalidContext.equals(api.getContextTemplate())) {
                throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
            }
        }
        // This is to support the pluggable version strategy.
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, api.getContextTemplate());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
        artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, api.getType());
        StringBuilder policyBuilder = new StringBuilder();
        for (Tier tier : api.getAvailableTiers()) {
            policyBuilder.append(tier.getName());
            policyBuilder.append("||");
        }
        String policies = policyBuilder.toString();
        if (!"".equals(policies)) {
            policies = policies.substring(0, policies.length() - 2);
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
        }
        StringBuilder tiersBuilder = new StringBuilder();
        for (Tier tier : api.getAvailableTiers()) {
            tiersBuilder.append(tier.getName());
            tiersBuilder.append("||");
        }
        String tiers = tiersBuilder.toString();
        if (!"".equals(tiers)) {
            tiers = tiers.substring(0, tiers.length() - 2);
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
        } else {
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
        }
        if (APIConstants.PUBLISHED.equals(apiStatus)) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "true");
        }
        String[] keys = artifact.getAttributeKeys();
        for (String key : keys) {
            if (key.contains("URITemplate")) {
                artifact.removeAttribute(key);
            }
        }
        Set<URITemplate> uriTemplateSet = api.getUriTemplates();
        int i = 0;
        for (URITemplate uriTemplate : uriTemplateSet) {
            artifact.addAttribute(APIConstants.API_URI_PATTERN + i, uriTemplate.getUriTemplate());
            artifact.addAttribute(APIConstants.API_URI_HTTP_METHOD + i, uriTemplate.getHTTPVerb());
            artifact.addAttribute(APIConstants.API_URI_AUTH_TYPE + i, uriTemplate.getAuthType());
            i++;
        }
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(api));
        artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, APIUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, APIUtil.getWebsubSubscriptionConfigurationJsonFromDto(api.getWebsubSubscriptionConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, APIUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        // set monetization status (i.e - enabled or disabled)
        artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(api.getMonetizationStatus()));
        // set additional monetization data
        if (api.getMonetizationProperties() != null) {
            artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, api.getMonetizationProperties().toJSONString());
        }
        if (api.getKeyManagers() != null) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS, new Gson().toJson(api.getKeyManagers()));
        }
        // check in github code to see this method was removed
        String apiSecurity = artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY);
        if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, "");
        }
    } catch (GovernanceException e) {
        String msg = "Failed to create API for : " + api.getId().getApiName();
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return artifact;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 8 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIConsumerImpl method updateSubscription.

@Override
public SubscriptionResponse updateSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application, String inputSubscriptionId, String currentThrottlingPolicy, String requestedThrottlingPolicy) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUId;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        apiId = product.getProductId();
        apiUUId = product.getUuid();
        identifier = product.getId();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = identifier.getId();
        apiUUId = api.getUuid();
        apiContext = api.getContext();
    }
    checkSubscriptionAllowed(apiTypeWrapper);
    WorkflowResponse workflowResponse = null;
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state)) {
        subscriptionId = apiMgtDAO.updateSubscription(apiTypeWrapper, inputSubscriptionId, APIConstants.SubscriptionStatus.TIER_UPDATE_PENDING, requestedThrottlingPolicy);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        try {
            WorkflowExecutor updateSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(updateSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
            workflowDTO.setCallbackUrl(updateSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(requestedThrottlingPolicy);
            workflowDTO.setApplicationName(application.getName());
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = updateSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = updateSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI updatedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = updatedSubscription.getSubStatus();
            subscriptionUUID = updatedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, application.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            subsLogObject.put(APIConstants.AuditLogConstants.REQUESTED_TIER, requestedThrottlingPolicy);
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE);
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_UPDATE.name(), tenantId, tenantDomain, subscriptionId, updatedSubscription.getUUID(), apiId, apiUUId, application.getId(), application.getUUID(), requestedThrottlingPolicy, subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + application.getName();
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 9 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIConsumerImpl method addSubscription.

@Override
public SubscriptionResponse addSubscription(ApiTypeWrapper apiTypeWrapper, String userId, Application application) throws APIManagementException {
    API api = null;
    APIProduct product = null;
    Identifier identifier = null;
    int apiId;
    String apiUUID;
    final boolean isApiProduct = apiTypeWrapper.isAPIProduct();
    String state;
    String apiContext;
    if (isApiProduct) {
        product = apiTypeWrapper.getApiProduct();
        state = product.getState();
        identifier = product.getId();
        apiId = product.getProductId();
        apiUUID = product.getUuid();
        apiContext = product.getContext();
    } else {
        api = apiTypeWrapper.getApi();
        state = api.getStatus();
        identifier = api.getId();
        apiId = api.getId().getId();
        apiUUID = api.getUuid();
        apiContext = api.getContext();
    }
    WorkflowResponse workflowResponse = null;
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
    checkSubscriptionAllowed(apiTypeWrapper);
    int subscriptionId;
    if (APIConstants.PUBLISHED.equals(state) || APIConstants.PROTOTYPED.equals(state)) {
        subscriptionId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, tenantAwareUsername);
        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        String applicationName = application.getName();
        try {
            WorkflowExecutor addSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getName());
            workflowDTO.setApiContext(apiContext);
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setRequestedTierName(identifier.getTier());
            workflowDTO.setApplicationName(applicationName);
            workflowDTO.setApplicationId(application.getId());
            workflowDTO.setSubscriber(userId);
            Tier tier = null;
            Set<Tier> policies = Collections.emptySet();
            if (!isApiProduct) {
                policies = api.getAvailableTiers();
            } else {
                policies = product.getAvailableTiers();
            }
            for (Tier policy : policies) {
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
            boolean isMonetizationEnabled = false;
            if (api != null) {
                isMonetizationEnabled = api.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, api);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            } else {
                isMonetizationEnabled = product.getMonetizationStatus();
                // check whether monetization is enabled for API and tier plan is commercial
                if (isMonetizationEnabled && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                    workflowResponse = addSubscriptionWFExecutor.monetizeSubscription(workflowDTO, product);
                } else {
                    workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
                }
            }
        } catch (WorkflowException e) {
            // If the workflow execution fails, roll back transaction by removing the subscription entry.
            apiMgtDAO.removeSubscriptionById(subscriptionId);
            log.error("Could not execute Workflow", e);
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
        // to handle on-the-fly subscription rejection (and removal of subscription entry from the database)
        // the response should have {"Status":"REJECTED"} in the json payload for this to work.
        boolean subscriptionRejected = false;
        String subscriptionStatus = null;
        String subscriptionUUID = "";
        SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);
        if (workflowResponse != null && workflowResponse.getJSONPayload() != null && !workflowResponse.getJSONPayload().isEmpty()) {
            try {
                JSONObject wfResponseJson = (JSONObject) new JSONParser().parse(workflowResponse.getJSONPayload());
                if (APIConstants.SubscriptionStatus.REJECTED.equals(wfResponseJson.get("Status"))) {
                    subscriptionRejected = true;
                    subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                }
            } catch (ParseException e) {
                log.error('\'' + workflowResponse.getJSONPayload() + "' is not a valid JSON.", e);
            }
        }
        if (!subscriptionRejected) {
            subscriptionStatus = addedSubscription.getSubStatus();
            subscriptionUUID = addedSubscription.getUUID();
            JSONObject subsLogObject = new JSONObject();
            subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
            subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, application.getId());
            subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
            subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
            if (workflowResponse == null) {
                workflowResponse = new GeneralWorkflowResponse();
            }
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(subscriptionId), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        // only send the notification if approved
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, addedSubscription.getUUID(), apiId, apiUUID, application.getId(), application.getUUID(), identifier.getTier(), subscriptionStatus);
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getName() + ", API Version " + identifier.getVersion() + ", Subscription Status: " + subscriptionStatus + " subscribe by " + userId + " for app " + applicationName;
            log.debug(logMessage);
        }
        return new SubscriptionResponse(subscriptionStatus, subscriptionUUID, workflowResponse);
    } else {
        throw new APIMgtResourceNotFoundException("Subscriptions not allowed on APIs/API Products in the state: " + state);
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) GeneralWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) JSONParser(org.json.simple.parser.JSONParser) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) ParseException(org.json.simple.parser.ParseException)

Example 10 with Monetization

use of org.wso2.carbon.apimgt.api.model.Monetization in project carbon-apimgt by wso2.

the class APIAdminImpl method getMonetizationImplClass.

/**
 * These methods load the monetization implementation class
 *
 * @return monetization implementation class
 * @throws APIManagementException if failed to load monetization implementation class
 */
public Monetization getMonetizationImplClass() throws APIManagementException {
    APIManagerConfiguration configuration = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    Monetization monetizationImpl = null;
    if (configuration == null) {
        log.error("API Manager configuration is not initialized.");
    } else {
        String monetizationImplClass = configuration.getFirstProperty(APIConstants.Monetization.MONETIZATION_IMPL);
        if (monetizationImplClass == null) {
            monetizationImpl = new DefaultMonetizationImpl();
        } else {
            try {
                monetizationImpl = (Monetization) APIUtil.getClassInstance(monetizationImplClass);
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                APIUtil.handleException("Failed to load monetization implementation class.", e);
            }
        }
    }
    return monetizationImpl;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) DefaultMonetizationImpl(org.wso2.carbon.apimgt.impl.monetization.DefaultMonetizationImpl)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 JSONObject (org.json.simple.JSONObject)14 Tier (org.wso2.carbon.apimgt.api.model.Tier)14 API (org.wso2.carbon.apimgt.api.model.API)13 ArrayList (java.util.ArrayList)9 ParseException (org.json.simple.parser.ParseException)9 Monetization (org.wso2.carbon.apimgt.api.model.Monetization)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9 JSONParser (org.json.simple.parser.JSONParser)8 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)8 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)8 Gson (com.google.gson.Gson)7 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)7 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)7 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)7 HashMap (java.util.HashMap)6 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)6 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 HashSet (java.util.HashSet)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)5