Search in sources :

Example 16 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ExportUtils method addThumbnailToArchive.

/**
 * Retrieve thumbnail image for the exporting API or API Product and store it in the archive directory.
 *
 * @param archivePath File path to export the thumbnail image
 * @param identifier  ID of the requesting API or API Product
 * @param apiProvider API Provider
 * @throws APIImportExportException If an error occurs while retrieving image from the registry or
 *                                  storing in the archive directory
 */
public static void addThumbnailToArchive(String archivePath, Identifier identifier, APIProvider apiProvider) throws APIImportExportException, APIManagementException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    String localImagePath = archivePath + File.separator + ImportExportConstants.IMAGE_RESOURCE;
    try {
        ResourceFile thumbnailResource = apiProvider.getIcon(identifier.getUUID(), tenantDomain);
        if (thumbnailResource != null) {
            String mediaType = thumbnailResource.getContentType();
            String extension = ImportExportConstants.fileExtensionMapping.get(mediaType);
            if (extension != null) {
                CommonUtil.createDirectory(localImagePath);
                try (InputStream imageDataStream = thumbnailResource.getContent();
                    OutputStream outputStream = new FileOutputStream(localImagePath + File.separator + APIConstants.API_ICON_IMAGE + APIConstants.DOT + extension)) {
                    IOUtils.copy(imageDataStream, outputStream);
                    if (log.isDebugEnabled()) {
                        log.debug("Thumbnail image retrieved successfully for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion());
                    }
                }
            } else {
                // api gets imported without thumbnail
                log.error("Unsupported media type for icon " + mediaType + ". Skipping thumbnail export.");
            }
        } else if (log.isDebugEnabled()) {
            log.debug("Thumbnail URL does not exists in registry for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion() + ". Skipping thumbnail export.");
        }
    } catch (IOException e) {
        // Exception is ignored by logging due to the reason that Thumbnail is not essential for
        // an API to be recreated.
        log.error("I/O error while writing API/API Product Thumbnail to file", e);
    }
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException)

Example 17 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ImportUtils method getLifeCycleAction.

/**
 * This method returns the lifecycle action which can be used to transit from currentStatus to targetStatus.
 *
 * @param tenantDomain  Tenant domain
 * @param currentStatus Current status to do status transition
 * @param targetStatus  Target status to do status transition
 * @return Lifecycle action or null if target is not reachable
 * @throws APIImportExportException If getting lifecycle action failed
 */
public static String getLifeCycleAction(String tenantDomain, String currentStatus, String targetStatus, APIProvider provider) throws APIManagementException {
    // No need to change the lifecycle if both the statuses are same
    if (StringUtils.equalsIgnoreCase(currentStatus, targetStatus)) {
        return null;
    }
    LifeCycle lifeCycle = new LifeCycle();
    // Parse DOM of APILifeCycle
    try {
        String data = provider.getLifecycleConfiguration(tenantDomain);
        DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
        Document doc = builder.parse(inputStream);
        Element root = doc.getDocumentElement();
        // Get all nodes with state
        NodeList states = root.getElementsByTagName("state");
        int nStates = states.getLength();
        for (int i = 0; i < nStates; i++) {
            Node node = states.item(i);
            Node id = node.getAttributes().getNamedItem("id");
            if (id != null && !id.getNodeValue().isEmpty()) {
                LifeCycleTransition lifeCycleTransition = new LifeCycleTransition();
                NodeList transitions = node.getChildNodes();
                int nTransitions = transitions.getLength();
                for (int j = 0; j < nTransitions; j++) {
                    Node transition = transitions.item(j);
                    // Add transitions
                    if (ImportExportConstants.NODE_TRANSITION.equals(transition.getNodeName())) {
                        Node target = transition.getAttributes().getNamedItem("target");
                        Node action = transition.getAttributes().getNamedItem("event");
                        if (target != null && action != null) {
                            lifeCycleTransition.addTransition(target.getNodeValue().toLowerCase(), action.getNodeValue());
                        }
                    }
                }
                lifeCycle.addLifeCycleState(id.getNodeValue().toLowerCase(), lifeCycleTransition);
            }
        }
    } catch (ParserConfigurationException | SAXException e) {
        throw new APIManagementException("Error parsing APILifeCycle for tenant: " + tenantDomain, e);
    } catch (UnsupportedEncodingException e) {
        throw new APIManagementException("Error parsing unsupported encoding for APILifeCycle in tenant: " + tenantDomain, e);
    } catch (IOException e) {
        throw new APIManagementException("Error reading APILifeCycle for tenant: " + tenantDomain, e);
    }
    // Retrieve lifecycle action
    LifeCycleTransition transition = lifeCycle.getTransition(currentStatus.toLowerCase());
    if (transition != null) {
        return transition.getAction(targetStatus.toLowerCase());
    }
    return null;
}
Also used : LifeCycle(org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) JsonElement(com.google.gson.JsonElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) LifeCycleTransition(org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycleTransition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 18 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ImportUtils method importDependentAPIs.

/**
 * This method imports dependent APIs of the API Product.
 *
 * @param path                     Location of the extracted folder of the API Product
 * @param currentUser              The current logged in user
 * @param isDefaultProviderAllowed Decision to keep or replace the provider
 * @param apiProvider              API provider
 * @param overwriteAPIs            Whether to overwrite the APIs or not
 * @param apiProductDto            API Product DTO
 * @param tokenScopes              Scopes of the token
 * @param organization  Organization Identifier
 * @return Modified API Product DTO with the correct API UUIDs
 * @throws IOException              If there is an error while reading an API file
 * @throws APIImportExportException If there is an error in importing an API
 * @throws APIManagementException   If failed to get the API Provider of an API, or failed when
 *                                  checking the existence of an API
 */
private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, boolean overwriteAPIs, Boolean rotateRevision, APIProductDTO apiProductDto, String[] tokenScopes, String organization) throws IOException, APIManagementException {
    JsonObject dependentAPIParamsConfigObject = null;
    // Retrieve the dependent APIs param configurations from the params file of the API Product
    JsonObject dependentAPIsParams = APIControllerUtil.getDependentAPIsParams(path);
    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();
            // API in the API directory will be retrieved if available
            if (dependentAPIsParams != null) {
                dependentAPIParamsConfigObject = APIControllerUtil.getDependentAPIParams(dependentAPIsParams, apiDirectory.getName());
                // If the "certificates" directory is specified, copy it inside Deployment directory of the
                // dependent API since there may be certificates required for APIs
                String deploymentCertificatesDirectoryPath = path + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
                if (CommonUtil.checkFileExistence(deploymentCertificatesDirectoryPath)) {
                    try {
                        CommonUtil.copyDirectory(deploymentCertificatesDirectoryPath, apiDirectoryPath + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY);
                    } catch (APIImportExportException e) {
                        throw new APIManagementException("Error while copying the directory " + deploymentCertificatesDirectoryPath, e);
                    }
                }
            }
            JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser, ImportExportConstants.TYPE_API);
            APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class);
            API importedApi = null;
            String apiName = apiDtoToImport.getName();
            String apiVersion = apiDtoToImport.getVersion();
            if (isDefaultProviderAllowed) {
                APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion);
                // Checking whether the API exists
                if (apiProvider.isAPIAvailable(apiIdentifier, organization)) {
                    // otherwise do not update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                    }
                } else {
                    // If the API is not already imported, import it
                    importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                }
            } else {
                // Retrieve the current tenant domain of the logged in user
                String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser));
                // Get the provider of the API if the API is in current user's tenant domain.
                String apiProviderInCurrentTenantDomain = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain);
                if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) {
                    // If there is no API in the current tenant domain (which means the provider name is blank)
                    // then the API should be imported freshly
                    importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                } else {
                    // otherwise do not import/update the API. (Just skip it)
                    if (Boolean.TRUE.equals(overwriteAPIs)) {
                        importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
                    }
                }
            }
            if (importedApi == null) {
                // Retrieve the API from the environment (This happens when you have not specified
                // the overwrite flag, so that we should retrieve the API from inside)
                importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
            }
            updateApiUuidInApiProduct(apiProductDto, importedApi);
        }
    } else {
        String msg = "No dependent APIs supplied. Continuing ...";
        log.info(msg);
    }
    return apiProductDto;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) File(java.io.File)

Example 19 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException 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 20 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ImportUtils method addClientCertificates.

/**
 * Import client certificates for Mutual SSL related configuration.
 *
 * @param pathToArchive Location of the extracted folder of the API
 * @param apiProvider   API Provider
 * @param preserveProvider Decision to keep or replace the provider
 * @param provider     Provider Id
 * @param organization Identifier of the organization
 * @throws APIImportExportException
 */
private static void addClientCertificates(String pathToArchive, APIProvider apiProvider, Boolean preserveProvider, String provider, String organization) throws APIManagementException {
    try {
        List<ClientCertificateDTO> certificateMetadataDTOS = retrieveClientCertificates(pathToArchive);
        for (ClientCertificateDTO certDTO : certificateMetadataDTOS) {
            APIIdentifier apiIdentifier = !preserveProvider ? new APIIdentifier(provider, certDTO.getApiIdentifier().getApiName(), certDTO.getApiIdentifier().getVersion()) : certDTO.getApiIdentifier();
            apiProvider.addClientCertificate(APIUtil.replaceEmailDomainBack(provider), apiIdentifier, certDTO.getCertificate(), certDTO.getAlias(), certDTO.getTierName(), organization);
        }
    } catch (APIManagementException e) {
        throw new APIManagementException("Error while importing client certificate", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)30 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)30 IOException (java.io.IOException)24 File (java.io.File)20 Gson (com.google.gson.Gson)11 JsonObject (com.google.gson.JsonObject)10 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)10 JsonArray (com.google.gson.JsonArray)9 JsonElement (com.google.gson.JsonElement)9 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)8 API (org.wso2.carbon.apimgt.api.model.API)6 GsonBuilder (com.google.gson.GsonBuilder)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 FileOutputStream (java.io.FileOutputStream)5 InputStream (java.io.InputStream)5 ArrayList (java.util.ArrayList)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)4 JsonParser (com.google.gson.JsonParser)3