Search in sources :

Example 21 with APIDefinitionValidationResponse

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

the class PublisherCommonUtils method updateSwagger.

/**
 * update swagger definition of the given api.
 *
 * @param apiId    API Id
 * @param response response of a swagger definition validation call
 * @param organization  Organization Identifier
 * @return updated swagger definition
 * @throws APIManagementException when error occurred updating swagger
 * @throws FaultGatewaysException when error occurred publishing API to the gateway
 */
public static String updateSwagger(String apiId, APIDefinitionValidationResponse response, boolean isServiceAPI, String organization) throws APIManagementException, FaultGatewaysException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // this will fail if user does not have access to the API or the API does not exist
    API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
    APIDefinition oasParser = response.getParser();
    String apiDefinition = response.getJsonContent();
    if (isServiceAPI) {
        apiDefinition = oasParser.copyVendorExtensions(existingAPI.getSwaggerDefinition(), apiDefinition);
    } else {
        apiDefinition = OASParserUtil.preProcess(apiDefinition);
    }
    if (APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType())) {
        List<SOAPToRestSequence> sequenceList = SequenceGenerator.generateSequencesFromSwagger(apiDefinition);
        existingAPI.setSoapToRestSequences(sequenceList);
    }
    Set<URITemplate> uriTemplates = null;
    uriTemplates = oasParser.getURITemplates(apiDefinition);
    if (uriTemplates == null || uriTemplates.isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    Set<org.wso2.carbon.apimgt.api.model.Scope> scopes = oasParser.getScopes(apiDefinition);
    // validating scope roles
    for (org.wso2.carbon.apimgt.api.model.Scope scope : scopes) {
        String roles = scope.getRoles();
        if (roles != null) {
            for (String aRole : roles.split(",")) {
                boolean isValidRole = APIUtil.isRoleNameExist(RestApiCommonUtil.getLoggedInUsername(), aRole);
                if (!isValidRole) {
                    throw new APIManagementException("Role '" + aRole + "' Does not exist.");
                }
            }
        }
    }
    List<APIResource> removedProductResources = apiProvider.getRemovedProductResources(uriTemplates, existingAPI);
    if (!removedProductResources.isEmpty()) {
        throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, existingAPI.getId().getApiName(), existingAPI.getId().getVersion()));
    }
    // set existing operation policies to URI templates
    apiProvider.setOperationPoliciesToURITemplates(apiId, uriTemplates);
    existingAPI.setUriTemplates(uriTemplates);
    existingAPI.setScopes(scopes);
    PublisherCommonUtils.validateScopes(existingAPI);
    // Update API is called to update URITemplates and scopes of the API
    SwaggerData swaggerData = new SwaggerData(existingAPI);
    String updatedApiDefinition = oasParser.populateCustomManagementInfo(apiDefinition, swaggerData);
    apiProvider.saveSwaggerDefinition(existingAPI, updatedApiDefinition, organization);
    existingAPI.setSwaggerDefinition(updatedApiDefinition);
    API unModifiedAPI = apiProvider.getAPIbyUUID(apiId, organization);
    existingAPI.setStatus(unModifiedAPI.getStatus());
    apiProvider.updateAPI(existingAPI, unModifiedAPI);
    // retrieves the updated swagger definition
    // TODO see why we need to get it
    String apiSwagger = apiProvider.getOpenAPIDefinition(apiId, organization);
    // instead of passing same
    return oasParser.getOASDefinitionForPublisher(existingAPI, apiSwagger);
}
Also used : APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API)

Example 22 with APIDefinitionValidationResponse

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

the class ImportUtils method retrieveValidatedAsyncApiDefinitionFromArchive.

/**
 * Validate Aysnc API definition from the archive directory and return it.
 *
 * @param pathToArchive Path to API archive
 * @return APIDefinitionValidationResponse of the Async API definition content
 * @throws APIManagementException If an error occurs while reading the file
 */
public static APIDefinitionValidationResponse retrieveValidatedAsyncApiDefinitionFromArchive(String pathToArchive) throws APIManagementException {
    try {
        String asyncApiDefinition = loadAsyncApiDefinitionFromFile(pathToArchive);
        APIDefinitionValidationResponse validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(asyncApiDefinition, true);
        if (!validationResponse.isValid()) {
            throw new APIManagementException("Error occurred while importing the API. Invalid AsyncAPI definition found. " + validationResponse.getErrorItems());
        }
        return validationResponse;
    } catch (IOException e) {
        throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 23 with APIDefinitionValidationResponse

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

the class SynapseArtifactGenerator method generateGatewayArtifact.

@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList) throws APIManagementException {
    RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
    List<String> synapseArtifacts = new ArrayList<>();
    for (APIRuntimeArtifactDto runTimeArtifact : apiRuntimeArtifactDtoList) {
        if (runTimeArtifact.isFile()) {
            String tenantDomain = runTimeArtifact.getTenantDomain();
            String label = runTimeArtifact.getLabel();
            Environment environment = APIUtil.getEnvironments(tenantDomain).get(label);
            GatewayAPIDTO gatewayAPIDTO = null;
            if (environment != null) {
                try (InputStream artifact = (InputStream) runTimeArtifact.getArtifact()) {
                    File baseDirectory = CommonUtil.createTempDirectory(null);
                    try {
                        String extractedFolderPath = ImportUtils.getArchivePathOfExtractedDirectory(baseDirectory.getAbsolutePath(), artifact);
                        if (APIConstants.API_PRODUCT.equals(runTimeArtifact.getType())) {
                            APIProductDTO apiProductDTO = ImportUtils.retrieveAPIProductDto(extractedFolderPath);
                            apiProductDTO.setId(runTimeArtifact.getApiId());
                            APIProduct apiProduct = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, apiProductDTO.getProvider());
                            APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                            apiProduct.setDefinition(apiDefinitionValidationResponse.getContent());
                            gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(apiProduct, environment, tenantDomain, extractedFolderPath);
                        } else {
                            APIDTO apidto = ImportUtils.retrievedAPIDto(extractedFolderPath);
                            API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
                            api.setUUID(apidto.getId());
                            if (APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
                                APIDefinition parser = new OAS3Parser();
                                SwaggerData swaggerData = new SwaggerData(api);
                                String apiDefinition = parser.generateAPIDefinition(swaggerData);
                                api.setSwaggerDefinition(apiDefinition);
                                GraphqlComplexityInfo graphqlComplexityInfo = APIUtil.getComplexityDetails(api);
                                String graphqlSchema = ImportUtils.retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
                                api.setGraphQLSchema(graphqlSchema);
                                GraphQLSchemaDefinition graphQLSchemaDefinition = new GraphQLSchemaDefinition();
                                graphqlSchema = graphQLSchemaDefinition.buildSchemaWithAdditionalInfo(api, graphqlComplexityInfo);
                                api.setGraphQLSchema(graphqlSchema);
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath);
                            } else if (api.getType() != null && (APIConstants.APITransportType.HTTP.toString().equals(api.getType()) || APIConstants.API_TYPE_SOAP.equals(api.getType()) || APIConstants.API_TYPE_SOAPTOREST.equals(api.getType()) || APIConstants.APITransportType.WEBHOOK.toString().equals(api.getType()))) {
                                APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                                api.setSwaggerDefinition(apiDefinitionValidationResponse.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath, apiDefinitionValidationResponse);
                            } else if (api.getType() != null && (APIConstants.APITransportType.WS.toString().equals(api.getType()) || APIConstants.APITransportType.SSE.toString().equals(api.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(api.getType()))) {
                                APIDefinitionValidationResponse asyncApiDefinition = ImportUtils.retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
                                api.setAsyncApiDefinition(asyncApiDefinition.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDtoForStreamingAPI(api, environment, tenantDomain, apidto, extractedFolderPath);
                            }
                        }
                        if (gatewayAPIDTO != null) {
                            String content = new Gson().toJson(gatewayAPIDTO);
                            synapseArtifacts.add(content);
                        }
                    } finally {
                        FileUtils.deleteQuietly(baseDirectory);
                    }
                } catch (Exception e) {
                    // only do error since we need to continue for other apis
                    log.error("Error while creating Synapse configurations", e);
                }
            }
        }
    }
    runtimeArtifactDto.setFile(false);
    runtimeArtifactDto.setArtifact(synapseArtifacts);
    return runtimeArtifactDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) InputStream(java.io.InputStream) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) Gson(com.google.gson.Gson) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File)

Example 24 with APIDefinitionValidationResponse

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

the class ServicesApiServiceImpl method validateAsyncAPISpecification.

/**
 * Validate the ASYNC API definition provided
 * @param url Service Definition URL
 * @param definitionContent Service Definition Content
 * @return APIDefinitionValidationResponse
 * @throws APIManagementException
 */
private APIDefinitionValidationResponse validateAsyncAPISpecification(String url, String definitionContent) throws APIManagementException, IOException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    if (StringUtils.isNotEmpty(definitionContent)) {
        // validate file
        // convert .yml or .yaml to JSON for validation
        String schemaToBeValidated = CommonUtil.yamlToJson(definitionContent);
        validationResponse = AsyncApiParserUtil.validateAsyncAPISpecification(schemaToBeValidated, true);
    } else if (url != null) {
        validationResponse = AsyncApiParserUtil.validateAsyncAPISpecificationByURL(url, true);
    }
    return validationResponse;
}
Also used : APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 25 with APIDefinitionValidationResponse

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

the class ServicesApiServiceImpl method validateAndRetrieveServiceDefinition.

private APIDefinitionValidationResponse validateAndRetrieveServiceDefinition(byte[] definitionFileByteArray, String url, ServiceEntry.DefinitionType type) throws APIManagementException, IOException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    String definitionContent = new String(definitionFileByteArray);
    if (ServiceEntry.DefinitionType.OAS3.equals(type) || ServiceEntry.DefinitionType.OAS2.equals(type)) {
        validationResponse = validateOpenAPIDefinition(url, definitionContent);
    } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(type)) {
        validationResponse = validateAsyncAPISpecification(url, definitionContent);
    }
    return validationResponse;
}
Also used : APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Aggregations

APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)24 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)14 API (org.wso2.carbon.apimgt.api.model.API)10 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 LinkedHashMap (java.util.LinkedHashMap)7 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)7 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)5 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)5 ArrayList (java.util.ArrayList)4 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)4 JSONObject (org.json.JSONObject)3 ErrorItem (org.wso2.carbon.apimgt.api.ErrorItem)3 Scope (org.wso2.carbon.apimgt.api.model.Scope)3 AsyncAPISpecificationValidationResponseDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AsyncAPISpecificationValidationResponseDTO)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Gson (com.google.gson.Gson)2 JsonObject (com.google.gson.JsonObject)2