Search in sources :

Example 1 with APIProductDTO

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

the class APIMappingUtil method setAPICategoriesToModel.

/**
 * Set API categories to API or APIProduct based on the instance type of the DTO object passes.
 *
 * @param dto   APIDTO or APIProductDTO
 * @param model API or APIProduct
 */
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
    List<String> apiCategoryNames = new ArrayList<>();
    if (dto instanceof APIDTO) {
        APIDTO apiDTO = (APIDTO) dto;
        apiCategoryNames = apiDTO.getCategories();
    } else {
        APIProductDTO apiProductDTO = (APIProductDTO) dto;
        apiCategoryNames = apiProductDTO.getCategories();
    }
    List<APICategory> apiCategories = new ArrayList<>();
    for (String categoryName : apiCategoryNames) {
        APICategory category = new APICategory();
        category.setName(categoryName);
        apiCategories.add(category);
    }
    if (model instanceof API) {
        ((API) model).setApiCategories(apiCategories);
    } else {
        ((APIProduct) model).setApiCategories(apiCategories);
    }
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 2 with APIProductDTO

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

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    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) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    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();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 3 with APIProductDTO

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

the class ExportUtils method exportApiProduct.

/**
 * Exports an API Product from API Manager for a given API Product. MMeta information, API Product icon,
 * documentation, client certificates and dependent APIs are exported.
 *
 * @param apiProvider           API Provider
 * @param apiProductIdentifier  API Product Identifier
 * @param apiProductDtoToReturn API Product DTO
 * @param userName              Username
 * @param exportFormat          Format of output documents. Can be YAML or JSON
 * @param preserveStatus        Preserve API Product status on export
 * @param organization          Organization Identifier
 * @return
 * @throws APIManagementException If an error occurs while getting governance registry
 */
public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, APIProductDTO apiProductDtoToReturn, String userName, ExportFormat exportFormat, Boolean preserveStatus, boolean preserveDocs, boolean preserveCredentials, String organization) throws APIManagementException, APIImportExportException {
    int tenantId = 0;
    // Create temp location for storing API Product data
    File exportFolder = CommonUtil.createTempDirectory(apiProductIdentifier);
    String exportAPIBasePath = exportFolder.toString();
    String archivePath = exportAPIBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion());
    tenantId = APIUtil.getTenantId(userName);
    CommonUtil.createDirectory(archivePath);
    if (preserveDocs) {
        addThumbnailToArchive(archivePath, apiProductIdentifier, apiProvider);
        addDocumentationToArchive(archivePath, apiProductIdentifier, exportFormat, apiProvider, APIConstants.API_PRODUCT_IDENTIFIER_TYPE);
    }
    // Set API Product status to created if the status is not preserved
    if (!preserveStatus) {
        apiProductDtoToReturn.setState(APIProductDTO.StateEnum.CREATED);
    }
    addGatewayEnvironmentsToArchive(archivePath, apiProductDtoToReturn.getId(), exportFormat, apiProvider);
    addAPIProductMetaInformationToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider);
    addDependentAPIsToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider, userName, Boolean.TRUE, preserveDocs, preserveCredentials, organization);
    // Export mTLS authentication related certificates
    if (log.isDebugEnabled()) {
        log.debug("Mutual SSL enabled. Exporting client certificates.");
    }
    addClientCertificatesToArchive(archivePath, apiProductIdentifier, tenantId, apiProvider, exportFormat, organization);
    CommonUtil.archiveDirectory(exportAPIBasePath);
    FileUtils.deleteQuietly(new File(exportAPIBasePath));
    return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 4 with APIProductDTO

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

the class ImportUtils method importApiProduct.

/**
 * This method imports an API Product.
 *
 * @param extractedFolderPath Location of the extracted folder of the API Product
 * @param preserveProvider    Decision to keep or replace the provider
 * @param overwriteAPIProduct Whether to update the API Product or not
 * @param overwriteAPIs       Whether to update the dependent APIs or not
 * @param organization  Organization Identifier
 * @param importAPIs          Whether to import the dependent APIs or not
 * @throws APIImportExportException If there is an error in importing an API
 */
public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean rotateRevision, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes, String organization) throws APIManagementException {
    String userName = RestApiCommonUtil.getLoggedInUsername();
    String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
    APIProduct importedApiProduct = null;
    JsonArray deploymentInfoArray = null;
    String currentStatus;
    String targetStatus;
    String lifecycleAction;
    try {
        JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API_PRODUCT);
        APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class);
        // If the provided dependent APIs params config is null, it means this happening when importing an API (not
        // because when importing a dependent API of an API Product). Hence, try to retrieve the definition from
        // the API folder path
        JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
        // If above the params configurations are not null, then resolve those
        if (paramsConfigObject != null) {
            importedApiProductDTO = APIControllerUtil.injectEnvParamsToAPIProduct(importedApiProductDTO, paramsConfigObject, extractedFolderPath);
            JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
            if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
                deploymentInfoArray = deploymentsParam.getAsJsonArray();
            }
        }
        APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider());
        // Check whether the API resources are valid
        checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider, organization);
        targetStatus = importedApiProductDTO.getState().toString();
        if (importAPIs) {
            // Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a
            // fresh import happens)
            importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, rotateRevision, importedApiProductDTO, tokenScopes, organization);
        } else {
            // Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are
            // already in the APIM
            importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain, organization);
        }
        APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
        // If the overwrite is set to true (which means an update), retrieve the existing API
        if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) {
            log.info("Existing API Product found, attempting to update it...");
            currentStatus = targetApiProduct.getState();
            importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName, currentTenantDomain);
        } else {
            if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) {
                log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it.");
            }
            currentStatus = APIStatus.CREATED.toString();
            importedApiProduct = PublisherCommonUtils.addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), organization);
        }
        // Retrieving the life cycle action to do the lifecycle state change explicitly later
        lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
        // Add/update swagger of API Product
        importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct.getUuid(), importedApiProduct, apiProvider, currentTenantDomain);
        // Since Image, documents and client certificates are optional, exceptions are logged and ignored in
        // implementation
        ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct);
        addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider);
        addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider, organization);
        if (log.isDebugEnabled()) {
            log.debug("Mutual SSL enabled. Importing client certificates.");
        }
        addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName(), organization);
        // Change API Product lifecycle if state transition is required
        if (StringUtils.isNotEmpty(lifecycleAction)) {
            apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
            log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
            apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApiProduct), lifecycleAction, new HashMap<>());
        }
        importedApiProduct.setState(targetStatus);
        if (deploymentInfoArray == null) {
            // If the params have not overwritten the deployment environments, yaml file will be read
            deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, false);
        }
        List<APIRevisionDeployment> apiProductRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, currentTenantDomain, apiProvider, organization);
        if (apiProductRevisionDeployments.size() > 0) {
            String importedAPIUuid = importedApiProduct.getUuid();
            String revisionId;
            APIRevision apiProductRevision = new APIRevision();
            apiProductRevision.setApiUUID(importedAPIUuid);
            apiProductRevision.setDescription("Revision created after importing the API Product");
            try {
                revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
                if (log.isDebugEnabled()) {
                    log.debug("A new revision has been created for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion() + " with ID: " + revisionId);
                }
            } catch (APIManagementException e) {
                // rotateRevision enabled, earliest revision will be deleted before creating a revision again
                if (e.getErrorHandler().getErrorCode() == ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED).getErrorCode() && rotateRevision) {
                    String earliestRevisionUuid = apiProvider.getEarliestRevisionUUID(importedAPIUuid);
                    List<APIRevisionDeployment> deploymentsList = apiProvider.getAPIRevisionDeploymentList(earliestRevisionUuid);
                    // if the earliest revision is already deployed in gateway environments, it will be undeployed
                    // before deleting
                    apiProvider.undeployAPIProductRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList);
                    apiProvider.deleteAPIProductRevision(importedAPIUuid, earliestRevisionUuid, organization);
                    revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
                    if (log.isDebugEnabled()) {
                        log.debug("Revision ID: " + earliestRevisionUuid + " has been undeployed from " + deploymentsList.size() + " gateway environments and created a new revision ID: " + revisionId + " for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion());
                    }
                } else {
                    throw new APIManagementException(e);
                }
            }
            // Once the new revision successfully created, artifacts will be deployed in mentioned gateway
            // environments
            apiProvider.deployAPIProductRevision(importedAPIUuid, revisionId, apiProductRevisionDeployments);
        } else {
            log.info("Valid deployment environments were not found for the imported artifact. Hence not deployed" + " in any of the gateway environments.");
        }
        return importedApiProduct;
    } catch (IOException e) {
        // mandatory steps
        throw new APIManagementException("Error while reading API Product meta information from path: " + extractedFolderPath, e);
    } catch (FaultGatewaysException e) {
        throw new APIManagementException("Error while updating API Product: " + importedApiProduct.getId().getName(), e);
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing API Product: ";
        if (importedApiProduct != null) {
            errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion();
        }
        throw new APIManagementException(errorMessage + " " + e.getMessage(), e);
    }
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) JsonArray(com.google.gson.JsonArray) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList)

Example 5 with APIProductDTO

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

the class ImportUtils method checkAPIProductResourcesValid.

/**
 * This method checks whether the resources in the API Product are valid.
 *
 * @param path          Location of the extracted folder of the API Product
 * @param currentUser   The current logged in user
 * @param apiProvider   API provider
 * @param apiProductDto API Product DTO
 * @param preserveProvider
 * @param organization
 * @throws IOException            If there is an error while reading an API file
 * @throws APIManagementException If failed to get the API Provider of an API,
 *                                or failed when checking the existence of an API
 */
private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider, String organization) throws IOException, APIManagementException {
    // Get dependent APIs in the API Product
    List<ProductAPIDTO> apis = apiProductDto.getApis();
    String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
    File apisDirectory = new File(apisDirectoryPath);
    File[] apisDirectoryListing = apisDirectory.listFiles();
    if (apisDirectoryListing != null) {
        for (File apiDirectory : apisDirectoryListing) {
            String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
            JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser, ImportExportConstants.TYPE_API);
            APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class);
            String apiName = apiDto.getName();
            String apiVersion = apiDto.getVersion();
            String swaggerContent = loadSwaggerFile(apiDirectoryPath);
            APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
            Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent);
            for (ProductAPIDTO apiFromProduct : apis) {
                if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils.equals(apiFromProduct.getVersion(), apiVersion)) {
                    List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources(apiFromProduct.getOperations(), apiUriTemplates);
                    // dependent APIs inside the directory) check whether those are already inside APIM
                    if (!invalidApiOperations.isEmpty()) {
                        // Get the provider of the API if the API is in current user's tenant domain.
                        API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
                        invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates());
                    }
                    // inside the APIM
                    if (!invalidApiOperations.isEmpty()) {
                        throw new APIMgtResourceNotFoundException("Cannot find API resources for some API Product resources.");
                    }
                }
            }
        }
    }
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) JsonElement(com.google.gson.JsonElement) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) File(java.io.File)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)12 APIProductDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO)9 ArrayList (java.util.ArrayList)7 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)7 API (org.wso2.carbon.apimgt.api.model.API)7 ProductAPIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO)7 JsonElement (com.google.gson.JsonElement)5 File (java.io.File)5 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)5 Gson (com.google.gson.Gson)4 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)4 Tier (org.wso2.carbon.apimgt.api.model.Tier)4 IOException (java.io.IOException)3 List (java.util.List)3 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)3 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)3 APIOperationsDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO)3 JsonObject (com.google.gson.JsonObject)2 LinkedHashSet (java.util.LinkedHashSet)2