Search in sources :

Example 16 with Monetization

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

the class SettingsMappingUtil method getMonetizationAttributes.

/**
 * This method returns the monetization properties from configuration.
 *
 * @return List<String> monetization properties
 * @throws APIManagementException
 */
private List<MonetizationAttributeDTO> getMonetizationAttributes() {
    List<MonetizationAttributeDTO> monetizationAttributeDTOSList = new ArrayList<MonetizationAttributeDTO>();
    JSONArray monetizationAttributes = APIUtil.getMonetizationAttributes();
    for (int i = 0; i < monetizationAttributes.size(); i++) {
        JSONObject monetizationAttribute = (JSONObject) monetizationAttributes.get(i);
        MonetizationAttributeDTO monetizationAttributeDTO = new MonetizationAttributeDTO();
        monetizationAttributeDTO.setName((String) monetizationAttribute.get(APIConstants.Monetization.ATTRIBUTE));
        monetizationAttributeDTO.setDisplayName((String) monetizationAttribute.get(APIConstants.Monetization.ATTRIBUTE_DISPLAY_NAME));
        monetizationAttributeDTO.setDescription((String) monetizationAttribute.get(APIConstants.Monetization.ATTRIBUTE_DESCRIPTION));
        monetizationAttributeDTO.setRequired((Boolean) monetizationAttribute.get(APIConstants.Monetization.IS_ATTRIBITE_REQUIRED));
        monetizationAttributeDTO.setHidden((Boolean) monetizationAttribute.get(APIConstants.Monetization.IS_ATTRIBUTE_HIDDEN));
        monetizationAttributeDTOSList.add(monetizationAttributeDTO);
    }
    return monetizationAttributeDTOSList;
}
Also used : JSONObject(org.json.simple.JSONObject) MonetizationAttributeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MonetizationAttributeDTO) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray)

Example 17 with Monetization

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

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(APIProduct model, String organization) throws APIManagementException {
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUuid());
    dto.setContext(model.getContext());
    dto.setDescription(model.getDescription());
    dto.setLifeCycleStatus(model.getState());
    dto.setType(model.getType());
    dto.setAvgRating(String.valueOf(model.getRating()));
    /* todo: created and last updated times
        if (null != model.getLastUpdated()) {
            Date lastUpdateDate = model.getLastUpdated();
            Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
            dto.setLastUpdatedTime(String.valueOf(timeStamp));
        }

        String createdTimeStamp = model.getCreatedTime();
        if (null != createdTimeStamp) {
            Date date = new Date(Long.valueOf(createdTimeStamp));
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            String dateFormatted = formatter.format(date);
            dto.setCreatedTime(dateFormatted);
        } */
    String apiDefinition = null;
    if (model.isAsync()) {
        // for asyncAPI retrieve asyncapi.yml specification
        apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
    } else {
        // retrieve open API definition
        if (model.getDefinition() != null) {
            apiDefinition = model.getDefinition();
        } else {
            apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
        }
    }
    dto.setApiDefinition(apiDefinition);
    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<APITiersDTO> tiersToReturn = new ArrayList<>();
    // set the monetization status of this API (enabled or disabled)
    APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
    monetizationInfoDTO.enabled(model.getMonetizationStatus());
    dto.setMonetization(monetizationInfoDTO);
    for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
        APITiersDTO apiTiersDTO = new APITiersDTO();
        apiTiersDTO.setTierName(currentTier.getName());
        apiTiersDTO.setTierPlan(currentTier.getTierPlan());
        // monetization attributes are applicable only for commercial tiers
        if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
            APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
            if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
                Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
                // check the billing plan (fixed or price per request)
                if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
                    monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
                } else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
                    monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
                }
                monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
                monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
            }
            apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
        }
        tiersToReturn.add(apiTiersDTO);
    }
    dto.setTiers(tiersToReturn);
    List<APIOperationsDTO> operationList = new ArrayList<>();
    Map<String, ScopeInfoDTO> uniqueScopes = new HashMap<>();
    for (APIProductResource productResource : model.getProductResources()) {
        URITemplate uriTemplate = productResource.getUriTemplate();
        APIOperationsDTO operation = new APIOperationsDTO();
        operation.setTarget(uriTemplate.getUriTemplate());
        operation.setVerb(uriTemplate.getHTTPVerb());
        operationList.add(operation);
        List<Scope> scopes = uriTemplate.retrieveAllScopes();
        for (Scope scope : scopes) {
            if (!uniqueScopes.containsKey(scope.getKey())) {
                ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
                if (StringUtils.isNotBlank(scope.getRoles())) {
                    scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
                }
                uniqueScopes.put(scope.getKey(), scopeInfoDTO);
            }
        }
    }
    dto.setOperations(operationList);
    dto.setScopes(new ArrayList<>(uniqueScopes.values()));
    dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    if (!StringUtils.isBlank(model.getThumbnailUrl())) {
        dto.setHasThumbnail(true);
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
                additionalPropertiesList.add(additionalPropertiesDTO);
            }
        }
        dto.setAdditionalProperties(additionalPropertiesList);
    }
    if (model.getEnvironments() != null) {
        List<String> environmentListToReturn = new ArrayList<>(model.getEnvironments());
        dto.setEnvironmentList(environmentListToReturn);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    // Since same APIInfoDTO is used for APIProduct in StoreUI set default AdvertisedInfo to the DTO
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(false);
    dto.setAdvertiseInfo(advertiseInfoDTO);
    String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    String subscriptionAvailability = model.getSubscriptionAvailability();
    String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
    dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
    return dto;
}
Also used : AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdvertiseInfoDTO) HashMap(java.util.HashMap) APITiersDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APITiersDTO) ArrayList(java.util.ArrayList) APIAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIAdditionalPropertiesDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationInfoDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) ScopeInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ScopeInfoDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIMonetizationAttributesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)

Example 18 with Monetization

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

the class RegistryPersistenceUtil method createAPIArtifactContent.

/**
 * Create Governance artifact from given attributes
 *
 * @param artifact initial governance artifact
 * @param api      API object with the attributes value
 * @return GenericArtifact
 * @throws 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_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_ADVERTISE_ONLY_API_VENDOR, api.getAdvertiseOnlyAPIVendor());
        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.isEnableSchemaValidation()));
        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.getEnvironments()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, RegistryPersistenceUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, RegistryPersistenceUtil.getWebsubSubscriptionJsonFromDto(api.getWebsubSubscriptionConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, RegistryPersistenceUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
        // attaching micro-gateway labels to the API
        // 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.isMonetizationEnabled()));
        // 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, "");
        }
        // set gateway vendor for the API
        artifact.setAttribute(APIConstants.API_GATEWAY_VENDOR, api.getGatewayVendor());
        // set async transport protocols for the API
        artifact.setAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS, api.getAsyncTransportProtocols());
        artifact.setAttribute(APIConstants.API_OVERVIEW_AUDIENCE, api.getAudience());
    } 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)

Example 19 with Monetization

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

the class RegistryPersistenceUtil method createAPIProductArtifactContent.

/**
 * Create Governance artifact from given attributes
 *
 * @param artifact   initial governance artifact
 * @param apiProduct APIProduct object with the attributes value
 * @return GenericArtifact
 * @throws APIManagementException if failed to create API Product
 */
public static GenericArtifact createAPIProductArtifactContent(GenericArtifact artifact, APIProduct apiProduct) throws APIManagementException {
    try {
        // todo : review and add missing fields
        artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, apiProduct.getId().getName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, apiProduct.getId().getVersion());
        artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, apiProduct.getId().getProviderName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, apiProduct.getContext());
        artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, apiProduct.getDescription());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, APIConstants.AuditLogConstants.API_PRODUCT);
        artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiProduct.getState());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, apiProduct.getVisibility());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, apiProduct.getVisibleRoles());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, apiProduct.getVisibleTenants());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, apiProduct.getBusinessOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, apiProduct.getBusinessOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, apiProduct.getTechnicalOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, apiProduct.getTechnicalOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, apiProduct.getSubscriptionAvailability());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, apiProduct.getSubscriptionAvailableTenants());
        artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, apiProduct.getThumbnailUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(apiProduct.getCacheTimeout()));
        StringBuilder policyBuilder = new StringBuilder();
        for (Tier tier : apiProduct.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);
        } else {
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
        }
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(apiProduct.getEnvironments()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, apiProduct.getTransports());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, getCorsConfigurationJsonFromDto(apiProduct.getCorsConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, apiProduct.getAuthorizationHeader());
        artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, apiProduct.getApiSecurity());
        // 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(apiProduct.getContextTemplate())) {
                throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
            }
        } else {
            String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
            if (invalidContext.equals(apiProduct.getContextTemplate())) {
                throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
            }
        }
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(apiProduct.isEnabledSchemaValidation()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(apiProduct.isEnableStore()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, apiProduct.getResponseCache());
        // This is to support the pluggable version strategy.
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, apiProduct.getContextTemplate());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
        artifact.setAttribute(APIConstants.API_GATEWAY_VENDOR, apiProduct.getGatewayVendor());
        // set monetization status (i.e - enabled or disabled)
        artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(apiProduct.getMonetizationStatus()));
        // set additional monetization data
        if (apiProduct.getMonetizationProperties() != null) {
            artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, apiProduct.getMonetizationProperties().toJSONString());
        }
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = apiProduct.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 version timestamp
        artifact.addAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, apiProduct.getVersionTimestamp());
    } catch (GovernanceException e) {
        String msg = "Failed to create API for : " + apiProduct.getId().getName();
        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) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 20 with Monetization

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

the class ApisApiServiceImpl method getAPIMonetization.

/**
 * Get API monetization status and monetized tier to billing plan mapping
 *
 * @param apiId API ID
 * @param messageContext message context
 * @return API monetization status and monetized tier to billing plan mapping
 */
@Override
public Response getAPIMonetization(String apiId, MessageContext messageContext) {
    try {
        if (StringUtils.isBlank(apiId)) {
            String errorMessage = "API ID cannot be empty or null when retrieving monetized plans.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String uuid;
        APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId);
        if (apiRevision != null && apiRevision.getApiUUID() != null) {
            uuid = apiRevision.getApiUUID();
        } else {
            uuid = apiId;
        }
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
        Map<String, String> monetizedPoliciesToPlanMapping = monetizationImplementation.getMonetizedPoliciesToPlanMapping(api);
        APIMonetizationInfoDTO monetizationInfoDTO = APIMappingUtil.getMonetizedTiersDTO(uuid, organization, monetizedPoliciesToPlanMapping);
        return Response.ok().entity(monetizationInfoDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Failed to retrieve monetized plans for API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (MonetizationException e) {
        String errorMessage = "Failed to fetch monetized plans of API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return Response.serverError().build();
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)

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