Search in sources :

Example 21 with APIRevision

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

the class APIProviderImpl method restoreAPIRevision.

/**
 * Restore a provided API Revision as the current API of the API
 *
 * @param apiId API UUID
 * @param apiRevisionId API Revision UUID
 * @throws APIManagementException if failed to restore APIRevision
 */
@Override
public void restoreAPIRevision(String apiId, String apiRevisionId, String organization) throws APIManagementException {
    APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiId);
    if (apiIdentifier == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
    }
    APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId);
    if (apiRevision == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_REVISION_NOT_FOUND, apiRevisionId));
    }
    apiIdentifier.setUuid(apiId);
    try {
        apiPersistenceInstance.restoreAPIRevision(new Organization(organization), apiIdentifier.getUUID(), apiRevision.getRevisionUUID(), apiRevision.getId());
    } catch (APIPersistenceException e) {
        String errorMessage = "Failed to restore registry artifacts";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_RESTORING_API_REVISION, apiRevision.getApiUUID()));
    }
    apiMgtDAO.restoreAPIRevision(apiRevision);
}
Also used : DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 22 with APIRevision

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

the class APIUtil method getAPIScopes.

/**
 * Get scopes attached to the API.
 *
 * @param id   API uuid
 * @param organization Organization
 * @return Scope key to Scope object mapping
 * @throws APIManagementException if an error occurs while getting scope attached to API
 */
public static Map<String, Scope> getAPIScopes(String id, String organization) throws APIManagementException {
    String currentApiUuid;
    APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(id);
    if (apiRevision != null && apiRevision.getApiUUID() != null) {
        currentApiUuid = apiRevision.getApiUUID();
    } else {
        currentApiUuid = id;
    }
    Set<String> scopeKeys = ApiMgtDAO.getInstance().getAPIScopeKeys(currentApiUuid);
    return getScopes(scopeKeys, organization);
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision)

Example 23 with APIRevision

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

the class APIMappingUtil method fromListAPIRevisiontoDTO.

public static APIRevisionListDTO fromListAPIRevisiontoDTO(List<APIRevision> apiRevisionList) throws APIManagementException {
    APIRevisionListDTO apiRevisionListDTO = new APIRevisionListDTO();
    List<APIRevisionDTO> apiRevisionDTOS = new ArrayList<>();
    for (APIRevision apiRevision : apiRevisionList) {
        apiRevisionDTOS.add(fromAPIRevisiontoDTO(apiRevision));
    }
    apiRevisionListDTO.setCount(apiRevisionList.size());
    apiRevisionListDTO.setList(apiRevisionDTOS);
    return apiRevisionListDTO;
}
Also used : APIRevisionListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionListDTO) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) ArrayList(java.util.ArrayList) APIRevisionDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionDTO)

Example 24 with APIRevision

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

the class ApisApiServiceImpl method getAPIRevisions.

/**
 * Retrieve available revisions of an API
 *
 * @param apiId UUID of the API
 * @param query Search query string
 * @param messageContext    message context object
 * @return response containing list of API revisions
 */
@Override
public Response getAPIRevisions(String apiId, String query, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIRevisionListDTO apiRevisionListDTO;
        List<APIRevision> apiRevisions = apiProvider.getAPIRevisions(apiId);
        if (StringUtils.equalsIgnoreCase(query, "deployed:true")) {
            List<APIRevision> apiDeployedRevisions = new ArrayList<>();
            for (APIRevision apiRevision : apiRevisions) {
                if (!apiRevision.getApiRevisionDeploymentList().isEmpty()) {
                    apiDeployedRevisions.add(apiRevision);
                }
            }
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiDeployedRevisions);
        } else if (StringUtils.equalsIgnoreCase(query, "deployed:false")) {
            List<APIRevision> apiNotDeployedRevisions = new ArrayList<>();
            for (APIRevision apiRevision : apiRevisions) {
                if (apiRevision.getApiRevisionDeploymentList().isEmpty()) {
                    apiNotDeployedRevisions.add(apiRevision);
                }
            }
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiNotDeployedRevisions);
        } else {
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiRevisions);
        }
        return Response.ok().entity(apiRevisionListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding retrieving API Revision for api id : " + apiId + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIRevisionListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionListDTO) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 25 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision 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)

Aggregations

APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 DeployedAPIRevision (org.wso2.carbon.apimgt.api.model.DeployedAPIRevision)23 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)18 ArrayList (java.util.ArrayList)16 Connection (java.sql.Connection)15 PreparedStatement (java.sql.PreparedStatement)15 ResultSet (java.sql.ResultSet)14 SQLException (java.sql.SQLException)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 API (org.wso2.carbon.apimgt.api.model.API)12 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)12 HashSet (java.util.HashSet)11 LinkedHashSet (java.util.LinkedHashSet)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)11 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)10