Search in sources :

Example 1 with APIRevisionDeployment

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

the class ApiMgtDAO method getAPIRevisionDeploymentByRevisionUUID.

/**
 * Get APIRevisionDeployment details by providing revision uuid
 *
 * @return List<APIRevisionDeployment> object
 * @throws APIManagementException if an error occurs while retrieving revision deployment mapping details
 */
public List<APIRevisionDeployment> getAPIRevisionDeploymentByRevisionUUID(String revisionUUID) throws APIManagementException {
    List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>();
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_API_REVISION_DEPLOYMENT_MAPPING_BY_REVISION_UUID)) {
        statement.setString(1, revisionUUID);
        try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
                String environmentName = rs.getString("NAME");
                String vhost = rs.getString("VHOST");
                apiRevisionDeployment.setDeployment(environmentName);
                apiRevisionDeployment.setVhost(VHostUtils.resolveIfNullToDefaultVhost(environmentName, vhost));
                apiRevisionDeployment.setRevisionUUID(rs.getString("REVISION_UUID"));
                apiRevisionDeployment.setDisplayOnDevportal(rs.getBoolean("DISPLAY_ON_DEVPORTAL"));
                apiRevisionDeployment.setDeployedTime(rs.getString("DEPLOYED_TIME"));
                apiRevisionDeploymentList.add(apiRevisionDeployment);
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get API Revision deployment mapping details for revision uuid: " + revisionUUID, e);
    }
    return apiRevisionDeploymentList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) PreparedStatement(java.sql.PreparedStatement)

Example 2 with APIRevisionDeployment

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

the class ImportUtils method importApi.

/**
 * This method imports an API.
 *
 * @param extractedFolderPath            Location of the extracted folder of the API
 * @param importedApiDTO                 API DTO of the importing API
 *                                       (This will not be null when importing dependent APIs with API Products)
 * @param preserveProvider               Decision to keep or replace the provider
 * @param overwrite                      Whether to update the API or not
 * @param tokenScopes                    Scopes of the token
 * @param dependentAPIParamsConfigObject Params configuration of an API (this will not be null if a dependent API
 *                                       of an
 *                                       API product wants to override the parameters)
 * @param organization  Identifier of an Organization
 * @throws APIImportExportException If there is an error in importing an API
 * @@return Imported API
 */
public static API importApi(String extractedFolderPath, APIDTO importedApiDTO, Boolean preserveProvider, Boolean rotateRevision, Boolean overwrite, Boolean dependentAPIFromProduct, String[] tokenScopes, JsonObject dependentAPIParamsConfigObject, String organization) throws APIManagementException {
    String userName = RestApiCommonUtil.getLoggedInUsername();
    APIDefinitionValidationResponse validationResponse = null;
    String graphQLSchema = null;
    API importedApi = null;
    String currentStatus;
    String targetStatus;
    String lifecycleAction;
    GraphqlComplexityInfo graphqlComplexityInfo = null;
    int tenantId = 0;
    JsonArray deploymentInfoArray = null;
    JsonObject paramsConfigObject;
    try {
        if (importedApiDTO == null) {
            JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API);
            importedApiDTO = new Gson().fromJson(jsonObject, APIDTO.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
        paramsConfigObject = (dependentAPIParamsConfigObject != null) ? dependentAPIParamsConfigObject : APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
        // If above the params configurations are not null, then resolve those
        if (paramsConfigObject != null) {
            importedApiDTO = APIControllerUtil.injectEnvParamsToAPI(importedApiDTO, paramsConfigObject, extractedFolderPath);
            if (!isAdvertiseOnlyAPI(importedApiDTO)) {
                JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
                if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
                    deploymentInfoArray = deploymentsParam.getAsJsonArray();
                }
            }
        }
        String apiType = importedApiDTO.getType().toString();
        APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiDTO.getProvider());
        // Validate swagger content except for streaming APIs
        if (!PublisherCommonUtils.isStreamingAPI(importedApiDTO) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
            validationResponse = retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
        }
        // Validate the GraphQL schema
        if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
            graphQLSchema = retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
        }
        // Validate the WSDL of SOAP APIs
        if (APIConstants.API_TYPE_SOAP.equalsIgnoreCase(apiType)) {
            validateWSDLFromArchive(extractedFolderPath, importedApiDTO);
        }
        // Validate the AsyncAPI definition of streaming APIs
        if (PublisherCommonUtils.isStreamingAPI(importedApiDTO)) {
            validationResponse = retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
        }
        String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
        // The status of the importing API should be stored separately to do the lifecycle change at the end
        targetStatus = importedApiDTO.getLifeCycleStatus();
        API targetApi = retrieveApiToOverwrite(importedApiDTO.getName(), importedApiDTO.getVersion(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
        if (isAdvertiseOnlyAPI(importedApiDTO)) {
            processAdvertiseOnlyPropertiesInDTO(importedApiDTO, tokenScopes);
        }
        Map<String, List<OperationPolicy>> extractedPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(importedApiDTO.getOperations());
        // If the overwrite is set to true (which means an update), retrieve the existing API
        if (Boolean.TRUE.equals(overwrite) && targetApi != null) {
            log.info("Existing API found, attempting to update it...");
            currentStatus = targetApi.getStatus();
            // Set the status of imported API to current status of target API when updating
            importedApiDTO.setLifeCycleStatus(currentStatus);
            // when updating an API from the UI there is at least one resource (operation) inside the DTO.
            if (importedApiDTO.getOperations().isEmpty()) {
                setOperationsToDTO(importedApiDTO, validationResponse);
            }
            targetApi.setOrganization(organization);
            importedApi = PublisherCommonUtils.updateApi(targetApi, importedApiDTO, RestApiCommonUtil.getLoggedInUserProvider(), tokenScopes);
        } else {
            if (targetApi == null && Boolean.TRUE.equals(overwrite)) {
                log.info("Cannot find : " + importedApiDTO.getName() + "-" + importedApiDTO.getVersion() + ". Creating it.");
            }
            // Initialize to CREATED when import
            currentStatus = APIStatus.CREATED.toString();
            importedApiDTO.setLifeCycleStatus(currentStatus);
            importedApi = PublisherCommonUtils.addAPIWithGeneratedSwaggerDefinition(importedApiDTO, ImportExportConstants.OAS_VERSION_3, importedApiDTO.getProvider(), organization);
            // Set API definition to validationResponse if the API is imported with sample API definition
            if (validationResponse.isInit()) {
                validationResponse.setContent(importedApi.getSwaggerDefinition());
                validationResponse.setJsonContent(importedApi.getSwaggerDefinition());
            }
        }
        if (!extractedPoliciesMap.isEmpty()) {
            importedApi.setUriTemplates(validateOperationPolicies(importedApi, apiProvider, extractedFolderPath, extractedPoliciesMap, currentTenantDomain));
            apiProvider.updateAPI(importedApi);
        }
        // Retrieving the life cycle action to do the lifecycle state change explicitly later
        lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
        // Add/update swagger content except for streaming APIs and GraphQL APIs
        if (!PublisherCommonUtils.isStreamingAPI(importedApiDTO) && !APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
            // Add the validated swagger separately since the UI does the same procedure
            PublisherCommonUtils.updateSwagger(importedApi.getUuid(), validationResponse, false, organization);
        }
        // Add the GraphQL schema
        if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
            importedApi.setOrganization(organization);
            PublisherCommonUtils.addGraphQLSchema(importedApi, graphQLSchema, apiProvider);
            graphqlComplexityInfo = retrieveGraphqlComplexityInfoFromArchive(extractedFolderPath, graphQLSchema);
            if (graphqlComplexityInfo != null && graphqlComplexityInfo.getList().size() != 0) {
                apiProvider.addOrUpdateComplexityDetails(importedApi.getUuid(), graphqlComplexityInfo);
            }
        }
        // Add/update Async API definition for streaming APIs
        if (PublisherCommonUtils.isStreamingAPI(importedApiDTO)) {
            // Add the validated Async API definition separately since the UI does the same procedure
            PublisherCommonUtils.updateAsyncAPIDefinition(importedApi.getUuid(), validationResponse, organization);
        }
        tenantId = APIUtil.getTenantId(RestApiCommonUtil.getLoggedInUsername());
        // Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in
        // implementation
        ApiTypeWrapper apiTypeWrapperWithUpdatedApi = new ApiTypeWrapper(importedApi);
        addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider);
        addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApi, apiProvider, organization);
        addAPIWsdl(extractedFolderPath, importedApi, apiProvider);
        if (StringUtils.equals(importedApi.getType().toLowerCase(), APIConstants.API_TYPE_SOAPTOREST.toLowerCase())) {
            addSOAPToREST(importedApi, validationResponse.getContent(), apiProvider);
        }
        if (!isAdvertiseOnlyAPI(importedApiDTO)) {
            addAPISequences(extractedFolderPath, importedApi, apiProvider);
            addAPISpecificSequences(extractedFolderPath, importedApi, apiProvider);
            addEndpointCertificates(extractedFolderPath, importedApi, apiProvider, tenantId);
            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL enabled. Importing client certificates.");
            }
            addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApi.getId().getProviderName(), organization);
        }
        // Change API lifecycle if state transition is required
        if (StringUtils.isNotEmpty(lifecycleAction)) {
            apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
            log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
            if (StringUtils.equals(lifecycleAction, APIConstants.LC_PUBLISH_LC_STATE)) {
                apiProvider.changeAPILCCheckListItems(importedApi.getId(), ImportExportConstants.REFER_REQUIRE_RE_SUBSCRIPTION_CHECK_ITEM, true);
            }
            apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApi), lifecycleAction, new HashMap<>());
        }
        importedApi.setStatus(targetStatus);
        String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
        if (deploymentInfoArray == null && !isAdvertiseOnlyAPI(importedApiDTO)) {
            // If the params have not overwritten the deployment environments, yaml file will be read
            deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, dependentAPIFromProduct);
        }
        List<APIRevisionDeployment> apiRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, tenantDomain, apiProvider, organization);
        if (apiRevisionDeployments.size() > 0) {
            String importedAPIUuid = importedApi.getUuid();
            String revisionId;
            APIRevision apiRevision = new APIRevision();
            apiRevision.setApiUUID(importedAPIUuid);
            apiRevision.setDescription("Revision created after importing the API");
            try {
                revisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
                if (log.isDebugEnabled()) {
                    log.debug("A new revision has been created for API " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion());
                }
            } catch (APIManagementException e) {
                // 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.undeployAPIRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList, organization);
                    apiProvider.deleteAPIRevision(importedAPIUuid, earliestRevisionUuid, tenantDomain);
                    revisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
                    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 " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion());
                    }
                } else {
                    throw new APIManagementException("Error occurred while creating a new revision for the API: " + importedApi.getId().getApiName(), e);
                }
            }
            // Once the new revision successfully created, artifacts will be deployed in mentioned gateway
            // environments
            apiProvider.deployAPIRevision(importedAPIUuid, revisionId, apiRevisionDeployments, organization);
            if (log.isDebugEnabled()) {
                log.debug("API: " + importedApi.getId().getApiName() + "_" + importedApi.getId().getVersion() + " was deployed in " + apiRevisionDeployments.size() + " gateway environments.");
            }
        } else {
            log.info("Valid deployment environments were not found for the imported artifact. Only working copy " + "was updated and not deployed in any of the gateway environments.");
        }
        return importedApi;
    } catch (CryptoException | IOException e) {
        throw new APIManagementException("Error while reading API meta information from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA);
    } catch (FaultGatewaysException e) {
        throw new APIManagementException("Error while updating API: " + importedApi.getId().getApiName(), e);
    } catch (APIMgtAuthorizationFailedException e) {
        throw new APIManagementException("Please enable preserveProvider property for cross tenant API Import.", e, ExceptionCodes.TENANT_MISMATCH);
    } catch (ParseException e) {
        throw new APIManagementException("Error while parsing the endpoint configuration of the API", ExceptionCodes.JSON_PARSE_ERROR);
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing API: ";
        if (importedApi != null) {
            errorMessage += importedApi.getId().getApiName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApi.getId().getVersion();
        }
        throw new APIManagementException(errorMessage + StringUtils.SPACE + e.getMessage(), e);
    }
}
Also used : ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList) GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JsonArray(com.google.gson.JsonArray) 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) API(org.wso2.carbon.apimgt.api.model.API) JsonParseException(com.google.gson.JsonParseException) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 3 with APIRevisionDeployment

use of org.wso2.carbon.apimgt.api.model.APIRevisionDeployment 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 4 with APIRevisionDeployment

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

the class ImportUtils method getValidatedDeploymentsList.

/**
 * This method is used to validate the Gateway environments from the deployment environments file. Gateway
 * environments will be validated with a set of all the labels and environments of the tenant domain. If
 * environment is not found in this set, it will be skipped with an error message in the console. This method is
 * common to both APIs and API Products
 *
 * @param deploymentInfoArray Deployment environment array found in the import artifact
 * @param tenantDomain        Tenant domain
 * @param apiProvider         Provider of the API/ API Product
 * @return a list of API/API Product revision deployments ready to be deployed.
 * @throws APIManagementException If an error occurs when validating the deployments list
 */
private static List<APIRevisionDeployment> getValidatedDeploymentsList(JsonArray deploymentInfoArray, String tenantDomain, APIProvider apiProvider, String organization) throws APIManagementException {
    List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
    if (deploymentInfoArray != null && deploymentInfoArray.size() > 0) {
        Map<String, Environment> gatewayEnvironments = APIUtil.getEnvironments(organization);
        for (int i = 0; i < deploymentInfoArray.size(); i++) {
            JsonObject deploymentJson = deploymentInfoArray.get(i).getAsJsonObject();
            JsonElement deploymentNameElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_NAME);
            if (deploymentNameElement != null) {
                String deploymentName = deploymentNameElement.getAsString();
                Environment gatewayEnvironment = gatewayEnvironments.get(deploymentName);
                if (gatewayEnvironment != null) {
                    JsonElement deploymentVhostElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_VHOST);
                    String deploymentVhost;
                    if (deploymentVhostElement != null) {
                        deploymentVhost = deploymentVhostElement.getAsString();
                    } else {
                        // set the default vhost of the given environment
                        if (gatewayEnvironment.getVhosts().isEmpty()) {
                            throw new APIManagementException("No VHosts defined for the environment: " + deploymentName);
                        }
                        deploymentVhost = gatewayEnvironment.getVhosts().get(0).getHost();
                    }
                    // resolve vhost to null if it is the default vhost of read only environment
                    deploymentVhost = VHostUtils.resolveIfDefaultVhostToNull(deploymentName, deploymentVhost);
                    JsonElement displayOnDevportalElement = deploymentJson.get(ImportExportConstants.DISPLAY_ON_DEVPORTAL_OPTION);
                    boolean displayOnDevportal = displayOnDevportalElement == null || displayOnDevportalElement.getAsBoolean();
                    APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
                    apiRevisionDeployment.setDeployment(deploymentName);
                    apiRevisionDeployment.setVhost(deploymentVhost);
                    apiRevisionDeployment.setDisplayOnDevportal(displayOnDevportal);
                    apiRevisionDeployments.add(apiRevisionDeployment);
                } else {
                    throw new APIManagementException("Label " + deploymentName + " is not a defined gateway environment. Hence " + "skipped without deployment", ExceptionCodes.from(ExceptionCodes.GATEWAY_ENVIRONMENT_NOT_FOUND, String.format("label '%s'", deploymentName)));
                }
            }
        }
    }
    return apiRevisionDeployments;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) JsonObject(com.google.gson.JsonObject) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)

Example 5 with APIRevisionDeployment

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

the class AdditionalSubscriptionInfoMappingUtil method setSolaceEnvironmentDetailsForSubscription.

/**
 * Sets the solace environment details For Solace API subscription with the protocol details
 *
 * @param api          API object
 * @param tenantDomain Tenant Domain
 * @return List containing AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO
 * @throws APIManagementException if error occurred when retrieving protocols URLs
 */
private static List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> setSolaceEnvironmentDetailsForSubscription(API api, String tenantDomain) throws APIManagementException {
    APIDTO apidto = APIMappingUtil.fromAPItoDTO(api, tenantDomain);
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    List<APIRevisionDeployment> revisionDeployments = apiConsumer.getAPIRevisionDeploymentListOfAPI(apidto.getId());
    List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> solaceEndpointURLsList = new ArrayList<>();
    // Get revision list of APIs and check Solace deployment environment
    for (APIRevisionDeployment revisionDeployment : revisionDeployments) {
        if (revisionDeployment.isDisplayOnDevportal()) {
            if (gatewayEnvironments != null) {
                // Deployed environment
                Environment environment = gatewayEnvironments.get(revisionDeployment.getDeployment());
                if (environment != null) {
                    // Set solace environment details if deployment is in Solace broker
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(environment.getProvider())) {
                        AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO solaceEnvironmentDTO = new AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO();
                        solaceEnvironmentDTO.setEnvironmentName(environment.getName());
                        solaceEnvironmentDTO.setEnvironmentDisplayName(environment.getDisplayName());
                        solaceEnvironmentDTO.setOrganizationName(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION));
                        // Get Solace endpoint URLs for provided protocols
                        solaceEnvironmentDTO.setSolaceURLs(mapSolaceURLsToStoreDTO(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION), environment.getName(), apidto.getAsyncTransportProtocols()));
                        solaceEndpointURLsList.add(solaceEnvironmentDTO);
                    }
                }
            }
        }
    }
    return solaceEndpointURLsList;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Aggregations

APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)45 ArrayList (java.util.ArrayList)20 Environment (org.wso2.carbon.apimgt.api.model.Environment)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)12 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)11 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)10 DeployedAPIRevision (org.wso2.carbon.apimgt.api.model.DeployedAPIRevision)10 APIRevisionDeploymentDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionDeploymentDTO)10 Connection (java.sql.Connection)9 PreparedStatement (java.sql.PreparedStatement)9 SQLException (java.sql.SQLException)9 HashSet (java.util.HashSet)8 LinkedHashSet (java.util.LinkedHashSet)8 HashMap (java.util.HashMap)6 Response (javax.ws.rs.core.Response)6 API (org.wso2.carbon.apimgt.api.model.API)6 APIStateChangeResponse (org.wso2.carbon.apimgt.api.model.APIStateChangeResponse)6 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)6 List (java.util.List)5