Search in sources :

Example 1 with APIInfoAdditionalPropertiesMapDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPIToInfoDTO.

/**
 * Creates a minimal DTO representation of an API object.
 *
 * @param api API object
 * @return a minimal representation DTO
 */
public static APIInfoDTO fromAPIToInfoDTO(API api) {
    APIInfoDTO apiInfoDTO = new APIInfoDTO();
    apiInfoDTO.setDescription(api.getDescription());
    String context = api.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    apiInfoDTO.setContext(context);
    apiInfoDTO.setId(api.getUUID());
    APIIdentifier apiId = api.getId();
    apiInfoDTO.setName(apiId.getApiName());
    apiInfoDTO.setVersion(apiId.getVersion());
    apiInfoDTO.setType(api.getType());
    String providerName = api.getId().getProviderName();
    apiInfoDTO.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    apiInfoDTO.setLifeCycleStatus(api.getStatus());
    apiInfoDTO.setHasThumbnail(!StringUtils.isBlank(api.getThumbnailUrl()));
    if (api.getAudience() != null) {
        apiInfoDTO.setAudience(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoDTO.AudienceEnum.valueOf(api.getAudience()));
    }
    if (api.getCreatedTime() != null) {
        Date createdTime = new Date(Long.parseLong(api.getCreatedTime()));
        apiInfoDTO.setCreatedTime(String.valueOf(createdTime.getTime()));
    }
    if (api.getLastUpdated() != null) {
        Date lastUpdatedTime = api.getLastUpdated();
        apiInfoDTO.setUpdatedTime(String.valueOf(lastUpdatedTime.getTime()));
    }
    apiInfoDTO.setAdvertiseOnly(api.isAdvertiseOnly());
    if (api.getAdditionalProperties() != null) {
        JSONObject additionalProperties = api.getAdditionalProperties();
        List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
            APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
            } else {
                additionalPropertiesDTO.setName(key);
                apiInfoAdditionalPropertiesMapDTO.setName(key);
                additionalPropertiesDTO.setDisplay(false);
            }
            apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
            additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
            additionalPropertiesList.add(additionalPropertiesDTO);
        }
        apiInfoDTO.setAdditionalProperties(additionalPropertiesList);
        apiInfoDTO.setAdditionalPropertiesMap(additionalPropertiesMap);
        apiInfoDTO.setGatewayVendor(api.getGatewayVendor());
    }
    return apiInfoDTO;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.util.Date) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONObject(org.json.simple.JSONObject) APIRevisionAPIInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionAPIInfoDTO) APIInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO)

Example 2 with APIInfoAdditionalPropertiesMapDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPIProducttoDTO.

public static APIProductDTO fromAPIProducttoDTO(APIProduct product) throws APIManagementException {
    APIProductDTO productDto = new APIProductDTO();
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    productDto.setName(product.getId().getName());
    productDto.setProvider(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
    productDto.setId(product.getUuid());
    productDto.setContext(product.getContext());
    productDto.setDescription(product.getDescription());
    productDto.setApiType(APIProductDTO.ApiTypeEnum.fromValue(APIConstants.AuditLogConstants.API_PRODUCT));
    productDto.setAuthorizationHeader(product.getAuthorizationHeader());
    productDto.setGatewayVendor(product.getGatewayVendor());
    Set<String> apiTags = product.getTags();
    List<String> tagsToReturn = new ArrayList<>(apiTags);
    productDto.setTags(tagsToReturn);
    productDto.setEnableSchemaValidation(product.isEnabledSchemaValidation());
    productDto.setIsRevision(product.isRevision());
    productDto.setRevisionedApiProductId(product.getRevisionedApiProductId());
    productDto.setRevisionId(product.getRevisionId());
    if (APIConstants.ENABLED.equals(product.getResponseCache())) {
        productDto.setResponseCachingEnabled(Boolean.TRUE);
    } else {
        productDto.setResponseCachingEnabled(Boolean.FALSE);
    }
    productDto.setCacheTimeout(product.getCacheTimeout());
    APIProductBusinessInformationDTO businessInformation = new APIProductBusinessInformationDTO();
    businessInformation.setBusinessOwner(product.getBusinessOwner());
    businessInformation.setBusinessOwnerEmail(product.getBusinessOwnerEmail());
    businessInformation.setTechnicalOwner(product.getTechnicalOwner());
    businessInformation.setTechnicalOwnerEmail(product.getTechnicalOwnerEmail());
    productDto.setBusinessInformation(businessInformation);
    APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
    CORSConfiguration corsConfiguration = product.getCorsConfiguration();
    if (corsConfiguration == null) {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
    apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
    productDto.setCorsConfiguration(apiCorsConfigurationDTO);
    productDto.setState(StateEnum.valueOf(product.getState()));
    productDto.setWorkflowStatus(product.getWorkflowStatus());
    // Aggregate API resources to each relevant API.
    Map<String, ProductAPIDTO> aggregatedAPIs = new HashMap<String, ProductAPIDTO>();
    List<APIProductResource> resources = product.getProductResources();
    for (APIProductResource apiProductResource : resources) {
        String uuid = apiProductResource.getApiId();
        if (aggregatedAPIs.containsKey(uuid)) {
            ProductAPIDTO productAPI = aggregatedAPIs.get(uuid);
            URITemplate template = apiProductResource.getUriTemplate();
            List<APIOperationsDTO> operations = productAPI.getOperations();
            APIOperationsDTO operation = getOperationFromURITemplate(template);
            operations.add(operation);
        } else {
            ProductAPIDTO productAPI = new ProductAPIDTO();
            productAPI.setApiId(uuid);
            productAPI.setName(apiProductResource.getApiName());
            productAPI.setVersion(apiProductResource.getApiIdentifier().getVersion());
            List<APIOperationsDTO> operations = new ArrayList<APIOperationsDTO>();
            URITemplate template = apiProductResource.getUriTemplate();
            APIOperationsDTO operation = getOperationFromURITemplate(template);
            operations.add(operation);
            productAPI.setOperations(operations);
            aggregatedAPIs.put(uuid, productAPI);
        }
    }
    productDto.setApis(new ArrayList<>(aggregatedAPIs.values()));
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(product.getId().getProviderName()));
    String apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(product.getId(), tenantDomain);
    List<ScopeDTO> scopeDTOS = getScopesFromSwagger(apiSwaggerDefinition);
    productDto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS));
    String subscriptionAvailability = product.getSubscriptionAvailability();
    if (subscriptionAvailability != null) {
        productDto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPIProducttoDTO(subscriptionAvailability));
    }
    if (product.getSubscriptionAvailableTenants() != null) {
        productDto.setSubscriptionAvailableTenants(Arrays.asList(product.getSubscriptionAvailableTenants().split(",")));
    }
    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = product.getAvailableTiers();
    List<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    productDto.setPolicies(tiersToReturn);
    productDto.setApiThrottlingPolicy(product.getProductLevelPolicy());
    if (product.getVisibility() != null) {
        productDto.setVisibility(mapVisibilityFromAPIProducttoDTO(product.getVisibility()));
    }
    if (product.getVisibleRoles() != null) {
        productDto.setVisibleRoles(Arrays.asList(product.getVisibleRoles().split(",")));
    }
    if (product.getVisibleTenants() != null) {
        productDto.setVisibleTenants(Arrays.asList(product.getVisibleTenants().split(",")));
    }
    productDto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(product.getAccessControl()) ? APIProductDTO.AccessControlEnum.RESTRICTED : APIProductDTO.AccessControlEnum.NONE);
    if (product.getAccessControlRoles() != null) {
        productDto.setAccessControlRoles(Arrays.asList(product.getAccessControlRoles().split(",")));
    }
    if (StringUtils.isEmpty(product.getTransports())) {
        List<String> transports = new ArrayList<>();
        transports.add(APIConstants.HTTPS_PROTOCOL);
        productDto.setTransport(transports);
    } else {
        productDto.setTransport(Arrays.asList(product.getTransports().split(",")));
    }
    if (product.getAdditionalProperties() != null) {
        JSONObject additionalProperties = product.getAdditionalProperties();
        List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
            APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
            } else {
                additionalPropertiesDTO.setName(key);
                apiInfoAdditionalPropertiesMapDTO.setName(key);
                additionalPropertiesDTO.setDisplay(false);
            }
            apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
            additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
            additionalPropertiesList.add(additionalPropertiesDTO);
        }
        productDto.setAdditionalPropertiesMap(additionalPropertiesMap);
        productDto.setAdditionalProperties(additionalPropertiesList);
    }
    if (product.getApiSecurity() != null) {
        productDto.setSecurityScheme(Arrays.asList(product.getApiSecurity().split(",")));
    }
    List<APICategory> apiCategories = product.getApiCategories();
    List<String> categoryNameList = new ArrayList<>();
    if (apiCategories != null && !apiCategories.isEmpty()) {
        for (APICategory category : apiCategories) {
            categoryNameList.add(category.getName());
        }
    }
    productDto.setCategories(categoryNameList);
    if (null != product.getLastUpdated()) {
        Date lastUpdateDate = product.getLastUpdated();
        Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
        productDto.setLastUpdatedTime(String.valueOf(timeStamp));
    }
    if (null != product.getCreatedTime()) {
        Date createdTime = product.getCreatedTime();
        Timestamp timeStamp = new Timestamp(createdTime.getTime());
        productDto.setCreatedTime(String.valueOf(timeStamp));
    }
    return productDto;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) HashMap(java.util.HashMap) ScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ScopeDTO) APIScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIScopeDTO) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Timestamp(java.sql.Timestamp) APIProductBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductBusinessInformationDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) Date(java.util.Date) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) JSONObject(org.json.simple.JSONObject) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 3 with APIInfoAdditionalPropertiesMapDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPItoDTO.

public static APIDTO fromAPItoDTO(API model, boolean preserveCredentials, APIProvider apiProviderParam) throws APIManagementException {
    APIProvider apiProvider;
    if (apiProviderParam != null) {
        apiProvider = apiProviderParam;
    } else {
        apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    }
    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());
    String context = model.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    dto.setContext(context);
    dto.setCreatedTime(model.getCreatedTime());
    if (model.getLastUpdated() != null) {
        dto.setLastUpdatedTime(Long.toString(model.getLastUpdated().getTime()));
    }
    dto.setDescription(model.getDescription());
    dto.setIsDefaultVersion(model.isDefaultVersion());
    dto.setIsRevision(model.isRevision());
    dto.setRevisionedApiId(model.getRevisionedApiId());
    dto.setRevisionId(model.getRevisionId());
    dto.setEnableSchemaValidation(model.isEnabledSchemaValidation());
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(model.isAdvertiseOnly());
    advertiseInfoDTO.setApiExternalProductionEndpoint(model.getApiExternalProductionEndpoint());
    advertiseInfoDTO.setApiExternalSandboxEndpoint(model.getApiExternalSandboxEndpoint());
    advertiseInfoDTO.setOriginalDevPortalUrl(model.getRedirectURL());
    advertiseInfoDTO.setApiOwner(model.getApiOwner());
    if (model.getAdvertiseOnlyAPIVendor() != null) {
        advertiseInfoDTO.setVendor(AdvertiseInfoDTO.VendorEnum.valueOf(model.getAdvertiseOnlyAPIVendor()));
    }
    dto.setAdvertiseInfo(advertiseInfoDTO);
    if (APIConstants.ENABLED.equals(model.getResponseCache())) {
        dto.setResponseCachingEnabled(Boolean.TRUE);
    } else {
        dto.setResponseCachingEnabled(Boolean.FALSE);
    }
    String serviceKey = model.getServiceInfo("key");
    if (StringUtils.isNotEmpty(serviceKey)) {
        APIServiceInfoDTO apiServiceInfoDTO = new APIServiceInfoDTO();
        apiServiceInfoDTO.setKey(serviceKey);
        apiServiceInfoDTO.setOutdated(Boolean.parseBoolean(model.getServiceInfo("outdated")));
        apiServiceInfoDTO.setName(model.getServiceInfo("name"));
        apiServiceInfoDTO.setVersion(model.getServiceInfo("version"));
        dto.setServiceInfo(apiServiceInfoDTO);
    }
    dto.setCacheTimeout(model.getCacheTimeout());
    String endpointConfig = model.getEndpointConfig();
    if (!StringUtils.isBlank(endpointConfig)) {
        try {
            JSONParser parser = new JSONParser();
            JSONObject endpointConfigJson = (JSONObject) parser.parse(endpointConfig);
            // AWS Lambda: set secret key based on preserveCredentials
            if (APIConstants.ENDPOINT_TYPE_AWSLAMBDA.equals(endpointConfigJson.get(APIConstants.API_ENDPOINT_CONFIG_PROTOCOL_TYPE))) {
                handleAWSCredentials(endpointConfigJson, preserveCredentials);
            }
            CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
            if (endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY) != null) {
                JSONObject endpointSecurity = (JSONObject) endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY);
                if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION) != null) {
                    JSONObject productionEndpointSecurity = (JSONObject) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                    String productionEndpointType = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                    if (productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                        String customParametersString = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                        JSONObject customParameters = (JSONObject) parser.parse(customParametersString);
                        productionEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParameters);
                    }
                    if (APIConstants.OAuthConstants.OAUTH.equals(productionEndpointType)) {
                        String clientSecret = (String) productionEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET);
                        if (StringUtils.isNotEmpty(clientSecret)) {
                            productionEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, new String(cryptoUtil.base64DecodeAndDecrypt(clientSecret)));
                        }
                    }
                    endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION, productionEndpointSecurity);
                    endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                }
                if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX) != null) {
                    JSONObject sandboxEndpointSecurity = (JSONObject) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                    String sandboxEndpointType = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                    if (sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                        String customParametersString = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                        JSONObject customParameters = (JSONObject) parser.parse(customParametersString);
                        sandboxEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParameters);
                    }
                    if (APIConstants.OAuthConstants.OAUTH.equals(sandboxEndpointType)) {
                        String clientSecret = (String) sandboxEndpointSecurity.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET);
                        if (StringUtils.isNotEmpty(clientSecret)) {
                            sandboxEndpointSecurity.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, new String(cryptoUtil.base64DecodeAndDecrypt(clientSecret)));
                        }
                    }
                    endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX, sandboxEndpointSecurity);
                    endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                }
                JSONObject jsonObject = handleEndpointSecurity(model, (JSONObject) endpointConfigJson.get(APIConstants.ENDPOINT_SECURITY), preserveCredentials);
                endpointConfigJson.put(APIConstants.ENDPOINT_SECURITY, jsonObject);
            }
            dto.setEndpointConfig(endpointConfigJson);
        } catch (ParseException e) {
            // logs the error and continues as this is not a blocker
            log.error("Cannot convert endpoint configurations when setting endpoint for API. " + "API ID = " + model.getId(), e);
        } catch (CryptoException e) {
            log.error("Error while decrypting client credentials for API: " + model.getId(), e);
        }
    }
    dto.setHasThumbnail(!StringUtils.isBlank(model.getThumbnailUrl()));
    List<MediationPolicyDTO> mediationPolicies = new ArrayList<>();
    String inMedPolicyName = model.getInSequence();
    if (inMedPolicyName != null && !inMedPolicyName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN;
        Mediation mediation = model.getInSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO inMedPolicy = new MediationPolicyDTO();
        inMedPolicy.setName(inMedPolicyName);
        inMedPolicy.setType(type.toUpperCase());
        inMedPolicy.setShared(sharedStatus);
        inMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(inMedPolicy);
    }
    String outMedPolicyName = model.getOutSequence();
    if (outMedPolicyName != null && !outMedPolicyName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT;
        Mediation mediation = model.getOutSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO outMedPolicy = new MediationPolicyDTO();
        outMedPolicy.setName(outMedPolicyName);
        outMedPolicy.setType(type.toUpperCase());
        outMedPolicy.setShared(sharedStatus);
        outMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(outMedPolicy);
    }
    String faultSequenceName = model.getFaultSequence();
    if (faultSequenceName != null && !faultSequenceName.isEmpty()) {
        String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT;
        Mediation mediation = model.getFaultSequenceMediation();
        String mediationPolicyUUID = (mediation != null) ? mediation.getUuid() : null;
        boolean sharedStatus = (mediation != null) ? mediation.isGlobal() : false;
        MediationPolicyDTO faultMedPolicy = new MediationPolicyDTO();
        faultMedPolicy.setName(faultSequenceName);
        faultMedPolicy.setType(type.toUpperCase());
        faultMedPolicy.setShared(sharedStatus);
        faultMedPolicy.setId(mediationPolicyUUID);
        mediationPolicies.add(faultMedPolicy);
    }
    dto.setMediationPolicies(mediationPolicies);
    dto.setLifeCycleStatus(model.getStatus());
    String subscriptionAvailability = model.getSubscriptionAvailability();
    if (subscriptionAvailability != null) {
        dto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPItoDTO(subscriptionAvailability));
    }
    if (model.getSubscriptionAvailableTenants() != null) {
        dto.setSubscriptionAvailableTenants(Arrays.asList(model.getSubscriptionAvailableTenants().split(",")));
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
    boolean isAsyncAPI = APIDTO.TypeEnum.WS.toString().equals(model.getType()) || APIDTO.TypeEnum.WEBSUB.toString().equals(model.getType()) || APIDTO.TypeEnum.SSE.toString().equals(model.getType()) || APIDTO.TypeEnum.ASYNC.toString().equals(model.getType());
    // Get Swagger definition which has URL templates, scopes and resource details
    model.getId().setUuid(model.getUuid());
    if (!isAsyncAPI) {
        // Get from swagger definition
        List<APIOperationsDTO> apiOperationsDTO;
        String apiSwaggerDefinition;
        if (model.getSwaggerDefinition() != null) {
            apiSwaggerDefinition = model.getSwaggerDefinition();
        } else {
            apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(model.getId(), tenantDomain);
        }
        // We will fetch operations from the swagger definition and not from the AM_API_URL_MAPPING table: table
        // entries may have API level throttling tiers listed in case API level throttling is selected for the API.
        // This will lead the x-throttling-tiers of API definition to get overwritten. (wso2/product-apim#11240)
        apiOperationsDTO = getOperationsFromSwaggerDef(model, apiSwaggerDefinition);
        // since the operation details goes missing after fetching operations list from the swagger definition, we
        // have to set them back from the original API model.
        setOperationPoliciesToOperationsDTO(model, apiOperationsDTO);
        dto.setOperations(apiOperationsDTO);
        List<ScopeDTO> scopeDTOS = getScopesFromSwagger(apiSwaggerDefinition);
        dto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS, apiProvider));
    } else {
        // Get from asyncapi definition
        List<APIOperationsDTO> apiOperationsDTO = getOperationsFromAPI(model);
        dto.setOperations(apiOperationsDTO);
        String asyncAPIDefinition;
        if (model.getAsyncApiDefinition() != null) {
            asyncAPIDefinition = model.getAsyncApiDefinition();
        } else {
            asyncAPIDefinition = apiProvider.getAsyncAPIDefinition(model.getId().getUUID(), tenantDomain);
        }
        if (asyncAPIDefinition != null) {
            List<ScopeDTO> scopeDTOS = getScopesFromAsyncAPI(asyncAPIDefinition);
            dto.setScopes(getAPIScopesFromScopeDTOs(scopeDTOS, apiProvider));
        }
    }
    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<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    dto.setPolicies(tiersToReturn);
    dto.setApiThrottlingPolicy(model.getApiLevelPolicy());
    // APIs created with type set to "NULL" will be considered as "HTTP"
    if (model.getType() == null || model.getType().toLowerCase().equals("null")) {
        dto.setType(APIDTO.TypeEnum.HTTP);
    } else {
        dto.setType(APIDTO.TypeEnum.fromValue(model.getType()));
    }
    if (!APIConstants.APITransportType.WS.toString().equals(model.getType())) {
        if (StringUtils.isEmpty(model.getTransports())) {
            List<String> transports = new ArrayList<>();
            transports.add(APIConstants.HTTPS_PROTOCOL);
            dto.setTransport(transports);
        }
        dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    }
    if (StringUtils.isEmpty(model.getTransports())) {
        dto.setVisibility(APIDTO.VisibilityEnum.PUBLIC);
    }
    dto.setVisibility(mapVisibilityFromAPItoDTO(model.getVisibility()));
    if (model.getVisibleRoles() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleRoles().split(",")));
    }
    if (model.getVisibleTenants() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleTenants().split(",")));
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        List<APIInfoAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
        Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            APIInfoAdditionalPropertiesDTO additionalPropertiesDTO = new APIInfoAdditionalPropertiesDTO();
            APIInfoAdditionalPropertiesMapDTO apiInfoAdditionalPropertiesMapDTO = new APIInfoAdditionalPropertiesMapDTO();
            String key = (String) propertyKey;
            int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
            additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
            apiInfoAdditionalPropertiesMapDTO.setValue((String) additionalProperties.get(key));
            if (index > 0) {
                additionalPropertiesDTO.setName(key.substring(0, index));
                apiInfoAdditionalPropertiesMapDTO.setName(key.substring(0, index));
                additionalPropertiesDTO.setDisplay(true);
            } else {
                additionalPropertiesDTO.setName(key);
                apiInfoAdditionalPropertiesMapDTO.setName(key);
                additionalPropertiesDTO.setDisplay(false);
            }
            apiInfoAdditionalPropertiesMapDTO.setDisplay(false);
            additionalPropertiesMap.put(key, apiInfoAdditionalPropertiesMapDTO);
            additionalPropertiesList.add(additionalPropertiesDTO);
        }
        dto.setAdditionalProperties(additionalPropertiesList);
        dto.setAdditionalPropertiesMap(additionalPropertiesMap);
    }
    if (model.getImplementation() != null) {
        dto.setEndpointImplementationType(APIDTO.EndpointImplementationTypeEnum.valueOf(model.getImplementation()));
    }
    dto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(model.getAccessControl()) ? APIDTO.AccessControlEnum.RESTRICTED : APIDTO.AccessControlEnum.NONE);
    if (model.getAccessControlRoles() != null) {
        dto.setAccessControlRoles(Arrays.asList(model.getAccessControlRoles().split(",")));
    }
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
    CORSConfiguration corsConfiguration = model.getCorsConfiguration();
    if (corsConfiguration == null) {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
    apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
    dto.setCorsConfiguration(apiCorsConfigurationDTO);
    WebsubSubscriptionConfigurationDTO websubSubscriptionConfigurationDTO = new WebsubSubscriptionConfigurationDTO();
    WebsubSubscriptionConfiguration websubSubscriptionConfiguration = model.getWebsubSubscriptionConfiguration();
    if (websubSubscriptionConfiguration == null) {
        websubSubscriptionConfiguration = APIUtil.getDefaultWebsubSubscriptionConfiguration();
    }
    websubSubscriptionConfigurationDTO.setEnable(websubSubscriptionConfiguration.isEnable());
    websubSubscriptionConfigurationDTO.setSecret(websubSubscriptionConfiguration.getSecret());
    websubSubscriptionConfigurationDTO.setSigningAlgorithm(websubSubscriptionConfiguration.getSigningAlgorithm());
    websubSubscriptionConfigurationDTO.setSignatureHeader(websubSubscriptionConfiguration.getSignatureHeader());
    dto.setWebsubSubscriptionConfiguration(websubSubscriptionConfigurationDTO);
    if (model.getWsdlUrl() != null) {
        WSDLInfoDTO wsdlInfoDTO = getWsdlInfoDTO(model);
        dto.setWsdlInfo(wsdlInfoDTO);
    }
    dto.setWsdlUrl(model.getWsdlUrl());
    setEndpointSecurityFromModelToApiDTO(model, dto, preserveCredentials);
    setMaxTpsFromModelToApiDTO(model, dto);
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    if (null != model.getLastUpdated()) {
        Date lastUpdateDate = model.getLastUpdated();
        Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
        dto.setLastUpdatedTime(String.valueOf(timeStamp));
    }
    if (null != model.getCreatedTime()) {
        Date created = new Date(Long.parseLong(model.getCreatedTime()));
        Timestamp timeStamp = new Timestamp(created.getTime());
        dto.setCreatedTime(String.valueOf(timeStamp.getTime()));
    }
    dto.setWorkflowStatus(model.getWorkflowStatus());
    List<APICategory> apiCategories = model.getApiCategories();
    List<String> categoryNameList = new ArrayList<>();
    if (apiCategories != null && !apiCategories.isEmpty()) {
        for (APICategory category : apiCategories) {
            categoryNameList.add(category.getName());
        }
    }
    dto.setCategories(categoryNameList);
    dto.setKeyManagers(model.getKeyManagers());
    if (model.getAudience() != null) {
        dto.setAudience(AudienceEnum.valueOf(model.getAudience()));
    }
    dto.setGatewayVendor(StringUtils.toRootLowerCase(model.getGatewayVendor()));
    if (model.getAsyncTransportProtocols() != null) {
        dto.setAsyncTransportProtocols(Arrays.asList(model.getAsyncTransportProtocols().split(",")));
    }
    return dto;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO) WebsubSubscriptionConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WebsubSubscriptionConfigurationDTO) HashMap(java.util.HashMap) ScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ScopeDTO) APIScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIScopeDTO) ArrayList(java.util.ArrayList) APIUtil.getDefaultWebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.impl.utils.APIUtil.getDefaultWebsubSubscriptionConfiguration) WebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) Timestamp(java.sql.Timestamp) MediationPolicyDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MediationPolicyDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) Tier(org.wso2.carbon.apimgt.api.model.Tier) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) Date(java.util.Date) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) WSDLInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WSDLInfoDTO) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) JSONObject(org.json.simple.JSONObject) APIServiceInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIServiceInfoDTO) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 4 with APIInfoAdditionalPropertiesMapDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method fromDTOtoAPI.

public static API fromDTOtoAPI(APIDTO dto, String provider) throws APIManagementException {
    String providerEmailDomainReplaced = APIUtil.replaceEmailDomain(provider);
    // The provider name that is coming from the body is not honored for now.
    // Later we can use it by checking admin privileges of the user.
    APIIdentifier apiId = new APIIdentifier(providerEmailDomainReplaced, dto.getName(), dto.getVersion());
    API model = new API(apiId);
    String context = dto.getContext();
    final String originalContext = context;
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null && !context.contains("/t/" + providerDomain)) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    // This is to support the pluggable version strategy
    // if the context does not contain any {version} segment, we use the default version strategy.
    context = checkAndSetVersionParam(context);
    model.setContextTemplate(context);
    context = updateContextWithVersion(dto.getVersion(), originalContext, context);
    model.setContext(context);
    model.setDescription(dto.getDescription());
    if (dto.getEndpointConfig() != null) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            model.setEndpointConfig(mapper.writeValueAsString(dto.getEndpointConfig()));
        } catch (IOException e) {
            handleException("Error while converting endpointConfig to json", e);
        }
    }
    model.setImplementation(dto.getEndpointImplementationType().toString());
    model.setType(dto.getType().toString());
    if (dto.getLifeCycleStatus() != null) {
        model.setStatus((dto.getLifeCycleStatus() != null) ? dto.getLifeCycleStatus().toUpperCase() : null);
    }
    if (dto.isIsDefaultVersion() != null) {
        model.setAsDefaultVersion(dto.isIsDefaultVersion());
    }
    if (dto.isEnableSchemaValidation() != null) {
        model.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    model.setEnableStore(true);
    if (dto.getAdvertiseInfo() != null) {
        AdvertiseInfoDTO advertiseInfoDTO = dto.getAdvertiseInfo();
        model.setAdvertiseOnly(advertiseInfoDTO.isAdvertised());
        model.setApiExternalProductionEndpoint(advertiseInfoDTO.getApiExternalProductionEndpoint());
        model.setApiExternalSandboxEndpoint(advertiseInfoDTO.getApiExternalSandboxEndpoint());
        model.setRedirectURL(advertiseInfoDTO.getOriginalDevPortalUrl());
        model.setApiOwner(advertiseInfoDTO.getApiOwner());
        model.setAdvertiseOnlyAPIVendor(dto.getAdvertiseInfo().getVendor().value());
    }
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        model.setResponseCache(APIConstants.ENABLED);
    } else {
        model.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        model.setCacheTimeout(dto.getCacheTimeout());
    } else {
        model.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getMediationPolicies() != null) {
        List<MediationPolicyDTO> policies = dto.getMediationPolicies();
        // validate whether provided sequences are available
        for (MediationPolicyDTO policy : policies) {
            if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equalsIgnoreCase(policy.getType())) {
                model.setInSequence(policy.getName());
            } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equalsIgnoreCase(policy.getType())) {
                model.setOutSequence(policy.getName());
            } else {
                model.setFaultSequence(policy.getName());
            }
        }
    }
    if (dto.getSubscriptionAvailability() != null) {
        model.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPI(dto.getSubscriptionAvailability()));
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        model.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    Set<Scope> scopes = getScopes(dto);
    model.setScopes(scopes);
    // URI Templates
    // No default topics for AsyncAPIs. Therefore set URITemplates only for non-AsyncAPIs.
    Set<URITemplate> uriTemplates = getURITemplates(model, dto.getOperations());
    model.setUriTemplates(uriTemplates);
    // wsUriMapping
    if (dto.getType().toString().equals(APIConstants.API_TYPE_WS)) {
        Map<String, String> wsUriMapping = new HashMap<>();
        for (APIOperationsDTO operationsDTO : dto.getOperations()) {
            wsUriMapping.put(operationsDTO.getVerb() + "_" + operationsDTO.getTarget(), operationsDTO.getUriMapping());
        }
        model.setWsUriMapping(wsUriMapping);
    }
    if (dto.getTags() != null) {
        Set<String> apiTags = new HashSet<>(dto.getTags());
        model.addTags(apiTags);
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    model.addAvailableTiers(apiTiers);
    model.setApiLevelPolicy(dto.getApiThrottlingPolicy());
    String transports = StringUtils.join(dto.getTransport(), ',');
    model.setTransports(transports);
    if (dto.getVisibility() != null) {
        model.setVisibility(mapVisibilityFromDTOtoAPI(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        model.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        if (APIUtil.isCrossTenantSubscriptionsEnabled()) {
            String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
            model.setVisibleTenants(visibleTenants);
        }
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        model.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        model.setAccessControlRoles("null");
    } else {
        model.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        model.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                model.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                model.addProperty(property.getName(), property.getValue());
            }
        }
    }
    Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = dto.getAdditionalPropertiesMap();
    if (additionalPropertiesMap != null && !additionalPropertiesMap.isEmpty()) {
        for (Map.Entry<String, APIInfoAdditionalPropertiesMapDTO> entry : additionalPropertiesMap.entrySet()) {
            if (entry.getValue().isDisplay()) {
                model.addProperty(entry.getKey() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, entry.getValue().getValue());
            } else {
                model.addProperty(entry.getKey(), entry.getValue().getValue());
            }
        }
    }
    ObjectMapper objectMapper = new ObjectMapper();
    APIBusinessInformationDTO apiBusinessInformationDTO = objectMapper.convertValue(dto.getBusinessInformation(), APIBusinessInformationDTO.class);
    if (apiBusinessInformationDTO != null) {
        model.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
        model.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
        model.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
        model.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
    }
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    model.setCorsConfiguration(corsConfiguration);
    setMaxTpsFromApiDTOToModel(dto, model);
    model.setAuthorizationHeader(dto.getAuthorizationHeader());
    model.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    if (dto.getType().toString().equals(APIConstants.API_TYPE_WEBSUB)) {
        WebsubSubscriptionConfigurationDTO websubSubscriptionConfigurationDTO = dto.getWebsubSubscriptionConfiguration();
        WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
        if (websubSubscriptionConfigurationDTO != null) {
            websubSubscriptionConfiguration = new WebsubSubscriptionConfiguration(websubSubscriptionConfigurationDTO.isEnable(), websubSubscriptionConfigurationDTO.getSecret(), websubSubscriptionConfigurationDTO.getSigningAlgorithm(), websubSubscriptionConfigurationDTO.getSignatureHeader());
        } else {
            websubSubscriptionConfiguration = getDefaultWebsubSubscriptionConfiguration();
        }
        model.setWebsubSubscriptionConfiguration(websubSubscriptionConfiguration);
    }
    // attach api categories to API model
    setAPICategoriesToModel(dto, model, provider);
    if (dto.getKeyManagers() instanceof List) {
        model.setKeyManagers((List<String>) dto.getKeyManagers());
    } else if (dto.getKeyManagers() == null) {
        model.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    APIServiceInfoDTO serviceInfoDTO = dto.getServiceInfo();
    if (serviceInfoDTO != null) {
        ObjectMapper mapper = new ObjectMapper();
        JSONParser parser = new JSONParser();
        JSONObject serviceInfoJson;
        String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
        try {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            serviceInfoJson = (JSONObject) parser.parse(mapper.writeValueAsString(serviceInfoDTO));
            ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
            ServiceEntry service = serviceCatalog.getServiceByKey(dto.getServiceInfo().getKey(), tenantId);
            // Set the md5 of the service which is already available in the system to the API model
            if (service == null) {
                if (log.isDebugEnabled()) {
                    log.debug("A service with key" + dto.getServiceInfo().getKey() + " referenced in the API " + "information is not available in the service catalog");
                }
            } else {
                serviceInfoJson.put("md5", service.getMd5());
            }
            model.setServiceInfo(serviceInfoJson);
        } catch (JsonProcessingException | ParseException e) {
            String msg = "Error while getting json representation of APIServiceInfo";
            handleException(msg, e);
        } catch (UserStoreException e) {
            String msg = "Error while getting tenantId from the given tenant domain " + tenantDomain;
            handleException(msg, e);
        }
    }
    if (dto.getAudience() != null) {
        model.setAudience(dto.getAudience().toString());
    }
    if (dto.getGatewayVendor() != null) {
        model.setGatewayVendor(dto.getGatewayVendor());
    }
    if (dto.getAsyncTransportProtocols() != null) {
        String asyncTransports = StringUtils.join(dto.getAsyncTransportProtocols(), ',');
        model.setAsyncTransportProtocols(asyncTransports);
    }
    return model;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO) WebsubSubscriptionConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WebsubSubscriptionConfigurationDTO) HashMap(java.util.HashMap) APIUtil.getDefaultWebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.impl.utils.APIUtil.getDefaultWebsubSubscriptionConfiguration) WebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) MediationPolicyDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MediationPolicyDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ArrayList(java.util.ArrayList) List(java.util.List) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) IOException(java.io.IOException) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIServiceInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIServiceInfoDTO) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) JSONParser(org.json.simple.parser.JSONParser) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 JSONObject (org.json.simple.JSONObject)4 APIInfoAdditionalPropertiesDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO)4 APIInfoAdditionalPropertiesMapDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO)4 Date (java.util.Date)3 CORSConfiguration (org.wso2.carbon.apimgt.api.model.CORSConfiguration)3 Tier (org.wso2.carbon.apimgt.api.model.Tier)3 APICorsConfigurationDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO)3 APIOperationsDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO)3 Timestamp (java.sql.Timestamp)2 JSONParser (org.json.simple.parser.JSONParser)2 ParseException (org.json.simple.parser.ParseException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APICategory (org.wso2.carbon.apimgt.api.model.APICategory)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)2 WebsubSubscriptionConfiguration (org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration)2 APIUtil.getDefaultWebsubSubscriptionConfiguration (org.wso2.carbon.apimgt.impl.utils.APIUtil.getDefaultWebsubSubscriptionConfiguration)2 APIBusinessInformationDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO)2