Search in sources :

Example 1 with MonetizationInfoDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIMonetization.

/**
 * Monetize (enable or disable) for a given API
 *
 * @param apiId API ID
 * @param body request body
 * @param messageContext message context
 * @return monetizationDTO
 */
@Override
public Response addAPIMonetization(String apiId, APIMonetizationInfoDTO body, MessageContext messageContext) {
    try {
        if (StringUtils.isBlank(apiId)) {
            String errorMessage = "API ID cannot be empty or null when configuring monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifier == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        if (!APIConstants.PUBLISHED.equalsIgnoreCase(api.getStatus())) {
            String errorMessage = "API " + apiIdentifier.getApiName() + " should be in published state to configure monetization.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        // set the monetization status
        boolean monetizationEnabled = body.isEnabled();
        api.setMonetizationStatus(monetizationEnabled);
        // clear the existing properties related to monetization
        api.getMonetizationProperties().clear();
        Map<String, String> monetizationProperties = body.getProperties();
        if (MapUtils.isNotEmpty(monetizationProperties)) {
            String errorMessage = RestApiPublisherUtils.validateMonetizationProperties(monetizationProperties);
            if (!errorMessage.isEmpty()) {
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
            for (Map.Entry<String, String> currentEntry : monetizationProperties.entrySet()) {
                api.addMonetizationProperty(currentEntry.getKey(), currentEntry.getValue());
            }
        }
        Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
        HashMap monetizationDataMap = new Gson().fromJson(api.getMonetizationProperties().toString(), HashMap.class);
        boolean isMonetizationStateChangeSuccessful = false;
        if (MapUtils.isEmpty(monetizationDataMap)) {
            String errorMessage = "Monetization is not configured. Monetization data is empty for " + apiIdentifier.getApiName();
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        try {
            if (monetizationEnabled) {
                isMonetizationStateChangeSuccessful = monetizationImplementation.enableMonetization(organization, api, monetizationDataMap);
            } else {
                isMonetizationStateChangeSuccessful = monetizationImplementation.disableMonetization(organization, api, monetizationDataMap);
            }
        } catch (MonetizationException e) {
            String errorMessage = "Error while changing monetization status for API ID : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
        if (isMonetizationStateChangeSuccessful) {
            apiProvider.configureMonetizationInAPIArtifact(api);
            APIMonetizationInfoDTO monetizationInfoDTO = APIMappingUtil.getMonetizationInfoDTO(apiId, organization);
            return Response.ok().entity(monetizationInfoDTO).build();
        } else {
            String errorMessage = "Unable to change monetization status for API : " + apiId;
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while configuring monetization for API ID : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return Response.serverError().build();
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIMonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)

Example 2 with MonetizationInfoDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO 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 3 with MonetizationInfoDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO 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)

Example 4 with MonetizationInfoDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO in project carbon-apimgt by wso2.

the class SubscriptionThrottlePolicyMappingUtil method fromSubscriptionThrottlePolicyToDTO.

/**
 * Converts a single Subscription Policy model into REST API DTO
 *
 * @param subscriptionPolicy Subscription Policy model object
 * @return Converted Subscription policy REST API DTO object
 * @throws UnsupportedThrottleLimitTypeException
 * @throws ParseException
 */
public static SubscriptionThrottlePolicyDTO fromSubscriptionThrottlePolicyToDTO(SubscriptionPolicy subscriptionPolicy) throws UnsupportedThrottleLimitTypeException, ParseException {
    SubscriptionThrottlePolicyDTO policyDTO = new SubscriptionThrottlePolicyDTO();
    policyDTO = CommonThrottleMappingUtil.updateFieldsFromToPolicyToDTO(subscriptionPolicy, policyDTO);
    policyDTO.setBillingPlan(subscriptionPolicy.getBillingPlan());
    policyDTO.setRateLimitCount(subscriptionPolicy.getRateLimitCount());
    policyDTO.setRateLimitTimeUnit(subscriptionPolicy.getRateLimitTimeUnit());
    policyDTO.setStopOnQuotaReach(subscriptionPolicy.isStopOnQuotaReach());
    policyDTO.setGraphQLMaxComplexity(subscriptionPolicy.getGraphQLMaxComplexity());
    policyDTO.setGraphQLMaxDepth(subscriptionPolicy.getGraphQLMaxDepth());
    policyDTO.setSubscriberCount(subscriptionPolicy.getSubscriberCount());
    byte[] customAttributes = subscriptionPolicy.getCustomAttributes();
    if (customAttributes != null) {
        List<CustomAttributeDTO> customAttributeDTOs = new ArrayList<>();
        JSONParser parser = new JSONParser();
        JSONArray attributeArray = (JSONArray) parser.parse(new String(subscriptionPolicy.getCustomAttributes()));
        for (Object attributeObj : attributeArray) {
            JSONObject attribute = (JSONObject) attributeObj;
            CustomAttributeDTO customAttributeDTO = CommonThrottleMappingUtil.getCustomAttribute(attribute.get(RestApiConstants.THROTTLING_CUSTOM_ATTRIBUTE_NAME).toString(), attribute.get(RestApiConstants.THROTTLING_CUSTOM_ATTRIBUTE_VALUE).toString());
            customAttributeDTOs.add(customAttributeDTO);
        }
        policyDTO.setCustomAttributes(customAttributeDTOs);
    }
    if (subscriptionPolicy.getDefaultQuotaPolicy() != null) {
        policyDTO.setDefaultLimit(CommonThrottleMappingUtil.fromQuotaPolicyToDTO(subscriptionPolicy.getDefaultQuotaPolicy()));
    }
    policyDTO.setType(SUBSCRIPTION_THROTTLE_POLICY_TYPE);
    if (APIConstants.COMMERCIAL_TIER_PLAN.equals(subscriptionPolicy.getBillingPlan())) {
        MonetizationInfoDTO monetizationInfoDTO = new MonetizationInfoDTO();
        if (APIConstants.Monetization.FIXED_RATE.equalsIgnoreCase(subscriptionPolicy.getMonetizationPlan())) {
            monetizationInfoDTO.setMonetizationPlan(MonetizationInfoDTO.MonetizationPlanEnum.FIXEDRATE);
        } else {
            monetizationInfoDTO.setMonetizationPlan(MonetizationInfoDTO.MonetizationPlanEnum.DYNAMICRATE);
        }
        monetizationInfoDTO.setProperties(subscriptionPolicy.getMonetizationPlanProperties());
        policyDTO.setMonetization(monetizationInfoDTO);
    }
    return policyDTO;
}
Also used : MonetizationInfoDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO) JSONObject(org.json.simple.JSONObject) SubscriptionThrottlePolicyDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.SubscriptionThrottlePolicyDTO) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) CustomAttributeDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.CustomAttributeDTO)

Example 5 with MonetizationInfoDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MonetizationInfoDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(API model, String organization) throws APIManagementException {
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    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.setIsDefaultVersion(model.isPublishedDefaultVersion());
    dto.setLifeCycleStatus(model.getStatus());
    dto.setType(model.getType());
    dto.setAvgRating(String.valueOf(model.getRating()));
    Set<Scope> scopes = model.getScopes();
    Map<String, ScopeInfoDTO> uniqueScope = new HashMap<>();
    for (Scope scope : scopes) {
        if (!uniqueScope.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(",")));
            }
            uniqueScope.put(scope.getKey(), scopeInfoDTO);
        }
    }
    dto.setScopes(new ArrayList<>(uniqueScope.values()));
    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.getSwaggerDefinition() != null) {
            apiDefinition = model.getSwaggerDefinition();
        } else {
            apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
        }
    }
    dto.setApiDefinition(apiDefinition);
    if (APIConstants.APITransportType.GRAPHQL.toString().equals(model.getType())) {
        List<APIOperationsDTO> operationList = new ArrayList<>();
        for (URITemplate template : model.getUriTemplates()) {
            APIOperationsDTO operation = new APIOperationsDTO();
            operation.setTarget(template.getUriTemplate());
            operation.setVerb(template.getHTTPVerb());
            operationList.add(operation);
        }
        dto.setOperations(operationList);
    }
    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);
    // set the monetization status of this API (enabled or disabled)
    APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
    monetizationInfoDTO.enabled(model.getMonetizationStatus());
    dto.setMonetization(monetizationInfoDTO);
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<APITiersDTO> tiersToReturn = new ArrayList<>();
    int tenantId = 0;
    if (!StringUtils.isBlank(organization)) {
        tenantId = APIUtil.getInternalOrganizationId(organization);
    }
    Set<String> deniedTiers = apiConsumer.getDeniedTiers(tenantId);
    for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
        if (!deniedTiers.contains(currentTier.getName())) {
            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 for 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);
    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);
    }
    dto.setWsdlUri(model.getWsdlUrl());
    if (model.getEnvironmentList() != null) {
        List<String> environmentListToReturn = new ArrayList<>();
        environmentListToReturn.addAll(model.getEnvironmentList());
        dto.setEnvironmentList(environmentListToReturn);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    dto.setAdvertiseInfo(extractAdvertiseInfo(model));
    String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    String subscriptionAvailability = model.getSubscriptionAvailability();
    String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
    dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
    List<APICategory> apiCategories = model.getApiCategories();
    List<String> categoryNamesList = new ArrayList<>();
    if (apiCategories != null && !apiCategories.isEmpty()) {
        for (APICategory category : apiCategories) {
            categoryNamesList.add(category.getName());
        }
    }
    dto.setCategories(categoryNamesList);
    dto.setKeyManagers(model.getKeyManagers());
    if (model.getGatewayVendor() != null) {
        dto.setGatewayVendor(model.getGatewayVendor());
    } else {
        dto.setGatewayVendor("wso2");
    }
    if (model.getAsyncTransportProtocols() != null) {
        dto.setAsyncTransportProtocols(Arrays.asList(model.getAsyncTransportProtocols().split(",")));
    }
    return dto;
}
Also used : 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) Timestamp(java.sql.Timestamp) 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) Date(java.util.Date) APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIOperationsDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) APIMonetizationAttributesDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)

Aggregations

HashMap (java.util.HashMap)4 ArrayList (java.util.ArrayList)3 JSONObject (org.json.simple.JSONObject)3 JsonObject (com.google.gson.JsonObject)2 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)2 API (org.wso2.carbon.apimgt.api.model.API)2 Monetization (org.wso2.carbon.apimgt.api.model.Monetization)2 Scope (org.wso2.carbon.apimgt.api.model.Scope)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 Tier (org.wso2.carbon.apimgt.api.model.Tier)2 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)2 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)2 APIMonetizationInfoDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO)2 APIAdditionalPropertiesDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIAdditionalPropertiesDTO)2 APIBusinessInformationDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO)2 APIDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO)2 APIMonetizationAttributesDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationAttributesDTO)2