Search in sources :

Example 26 with APIDefinition

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

the class OAS3Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Open API Specification (3.0) definitions
 *
 * @param apiDefinition API Definition
 * @return swagger Json
 */
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
        int minResponseCode = 0;
        int responseCode = 0;
        String path = entry.getKey();
        Map<String, Schema> definitions = swagger.getComponents().getSchemas();
        // operation map to get verb
        Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
        List<Operation> operations = swagger.getPaths().get(path).readOperations();
        for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
            Operation op = operations.get(i);
            // initializing apiResourceMediationPolicyObject
            APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
            // setting path for apiResourceMediationPolicyObject
            apiResourceMediationPolicyObject.setPath(path);
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            // for each HTTP method get the verb
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
                apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
            } else {
                throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
            }
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                Content content = op.getResponses().get(responseEntry).getContent();
                if (content != null) {
                    MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
                    MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        Schema jsonSchema = applicationJson.getSchema();
                        if (jsonSchema != null) {
                            String jsonExample = getJsonExample(jsonSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                            respCodeInitialized = true;
                            hasJsonPayload = true;
                        }
                    }
                    if (applicationXml != null) {
                        Schema xmlSchema = applicationXml.getSchema();
                        if (xmlSchema != null) {
                            String xmlExample = getXmlExample(xmlSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                            hasXmlPayload = true;
                        }
                    }
                } else {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            // inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            // gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            // sets script to each resource in the swagger
            op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
        }
        checkAndSetEmptyScope(swagger);
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediaType(io.swagger.v3.oas.models.media.MediaType) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Content(io.swagger.v3.oas.models.media.Content) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 27 with APIDefinition

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

the class OAS2Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(apiDefinition);
    boolean swaggerErrorFound = false;
    for (String message : parseAttemptForV2.getMessages()) {
        OASParserUtil.addErrorToValidationResponse(validationResponse, message);
        if (message.contains(APIConstants.SWAGGER_IS_MISSING_MSG)) {
            ErrorItem errorItem = new ErrorItem();
            errorItem.setErrorCode(ExceptionCodes.INVALID_OAS2_FOUND.getErrorCode());
            errorItem.setMessage(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            errorItem.setDescription(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            validationResponse.getErrorItems().add(errorItem);
            swaggerErrorFound = true;
        }
    }
    if (parseAttemptForV2.getSwagger() == null || swaggerErrorFound) {
        validationResponse.setValid(false);
    } else {
        Swagger swagger = parseAttemptForV2.getSwagger();
        Info info = swagger.getInfo();
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, swagger.getSwagger(), info.getTitle(), info.getVersion(), swagger.getBasePath(), info.getDescription(), (swagger.getHost() == null || swagger.getHost().isEmpty()) ? null : new ArrayList<String>(Arrays.asList(swagger.getHost())));
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                try {
                    JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition, new SwaggerDeserializationResult());
                    validationResponse.setJsonContent(jsonNode.toString());
                } catch (IOException e) {
                    throw new APIManagementException("Error while reading API definition yaml", e);
                }
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) Info(io.swagger.models.Info) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 28 with APIDefinition

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

the class AsyncApiParser method validateAPIDefinition.

@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    // import and load AsyncAPI HyperSchema for JSON schema validation
    JSONObject hyperSchema = new JSONObject(ASYNCAPI_JSON_HYPERSCHEMA);
    String protocol = StringUtils.EMPTY;
    boolean validationSuccess = false;
    List<String> validationErrorMessages = null;
    boolean isWebSocket = false;
    JSONObject schemaToBeValidated = new JSONObject(apiDefinition);
    // validate AsyncAPI using JSON schema validation
    try {
        JSONParser parser = new JSONParser();
        org.json.simple.JSONObject json = (org.json.simple.JSONObject) parser.parse(metaSchema);
        SchemaLoader schemaLoader = SchemaLoader.builder().registerSchemaByURI(new URI("http://json-schema.org/draft-07/schema#"), json).schemaJson(hyperSchema).build();
        Schema schemaValidator = schemaLoader.load().build();
        schemaValidator.validate(schemaToBeValidated);
        /*AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
            validationErrorMessages = new ArrayList<>();
            if (asyncApiDocument.getServers().size() == 1) {
                if (!APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
                    validationErrorMessages.add("#:The protocol of the server should be 'ws' for websockets");
                }
            }
            if (asyncApiDocument.getServers().size() > 1) {
                validationErrorMessages.add("#:The AsyncAPI definition should contain only a single server for websockets");
            }
            if (asyncApiDocument.getChannels().size() > 1) {
                validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
            }
            if (validationErrorMessages.size() == 0) {
                validationSuccess = true;
                validationErrorMessages = null;
            }*/
        // AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
        /*//Checking whether it is a websocket
            validationErrorMessages = new ArrayList<>();
            if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(asyncApiDocument.getServers().get(0).protocol)) {
                if (APIConstants.WS_PROTOCOL.equalsIgnoreCase(protocol)) {
                    isWebSocket = true;
                }
            }*/
        // validating channel count for websockets
        /*if (isWebSocket) {
                if (asyncApiDocument.getChannels().size() > 1) {
                    validationErrorMessages.add("#:The AsyncAPI definition should contain only a single channel for websockets");
                }
            }*/
        /*if (validationErrorMessages.size() == 0) {
                validationSuccess = true;
                validationErrorMessages = null;
            }*/
        validationSuccess = true;
    } catch (ValidationException e) {
        // validation error messages
        validationErrorMessages = e.getAllMessages();
    } catch (URISyntaxException e) {
        String msg = "Error occurred when registering the schema";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Error occurred when parsing the schema";
        throw new APIManagementException(msg, e);
    }
    // TODO: Validation is failing. Need to fix this. Therefore overriding the value as True.
    validationSuccess = true;
    if (validationSuccess) {
        AaiDocument asyncApiDocument = (AaiDocument) Library.readDocumentFromJSONString(apiDefinition);
        ArrayList<String> endpoints = new ArrayList<>();
        if (asyncApiDocument.getServers().size() == 1) {
            protocol = asyncApiDocument.getServers().get(0).protocol;
        }
        /*for (AaiServer x : asyncApiDocument.getServers()){
                endpoints.add(x.url);
            }
            AsyncApiParserUtil.updateValidationResponseAsSuccess(
                    validationResponse,
                    apiDefinition,
                    asyncApiDocument.asyncapi,
                    asyncApiDocument.info.title,
                    asyncApiDocument.info.version,
                    null,                           //asyncApiDocument.getChannels().get(0)._name,
                    asyncApiDocument.info.description,
                    endpoints
            );*/
        /*if (isWebSocket) {
                for (AaiServer x : asyncApiDocument.getServers()){
                    endpoints.add(x.url);
                }
                AsyncApiParserUtil.updateValidationResponseAsSuccess(
                        validationResponse,
                        apiDefinition,
                        asyncApiDocument.asyncapi,
                        asyncApiDocument.info.title,
                        asyncApiDocument.info.version,
                        asyncApiDocument.getChannels().get(0)._name,            //make this null
                        asyncApiDocument.info.description,
                        endpoints
                );
            } else {
                AsyncApiParserUtil.updateValidationResponseAsSuccess(
                        validationResponse,
                        apiDefinition,
                        asyncApiDocument.asyncapi,
                        asyncApiDocument.info.title,
                        asyncApiDocument.info.version,
                        null,
                        asyncApiDocument.info.description,
                        null
                );
            }*/
        AsyncApiParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, asyncApiDocument.asyncapi, asyncApiDocument.info.title, asyncApiDocument.info.version, null, asyncApiDocument.info.description, null);
        validationResponse.setParser(this);
        if (returnJsonContent) {
            validationResponse.setJsonContent(apiDefinition);
        }
        if (StringUtils.isNotEmpty(protocol)) {
            validationResponse.setProtocol(protocol);
        }
    } else {
        if (validationErrorMessages != null) {
            validationResponse.setValid(false);
            for (String errorMessage : validationErrorMessages) {
                AsyncApiParserUtil.addErrorToValidationResponse(validationResponse, errorMessage);
            }
        }
    }
    return validationResponse;
}
Also used : SchemaLoader(org.everit.json.schema.loader.SchemaLoader) ValidationException(org.everit.json.schema.ValidationException) Schema(org.everit.json.schema.Schema) ArrayList(java.util.ArrayList) AaiDocument(io.apicurio.datamodels.asyncapi.models.AaiDocument) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 29 with APIDefinition

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

the class APIProviderImpl method addAPIProductSwagger.

@Override
public void addAPIProductSwagger(String productId, Map<API, List<APIProductResource>> apiToProductResourceMapping, APIProduct apiProduct, String orgId) throws APIManagementException {
    APIDefinition parser = new OAS3Parser();
    SwaggerData swaggerData = new SwaggerData(apiProduct);
    String apiProductSwagger = parser.generateAPIDefinition(swaggerData);
    apiProductSwagger = OASParserUtil.updateAPIProductSwaggerOperations(apiToProductResourceMapping, apiProductSwagger);
    saveSwaggerDefinition(productId, apiProductSwagger, orgId);
    apiProduct.setDefinition(apiProductSwagger);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser)

Example 30 with APIDefinition

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

the class APIProviderImpl method updateAPIProductSwagger.

@Override
public void updateAPIProductSwagger(String productId, Map<API, List<APIProductResource>> apiToProductResourceMapping, APIProduct apiProduct, String orgId) throws APIManagementException {
    APIDefinition parser = new OAS3Parser();
    SwaggerData updatedData = new SwaggerData(apiProduct);
    String existingProductSwagger = getAPIDefinitionOfAPIProduct(apiProduct);
    String updatedProductSwagger = parser.generateAPIDefinition(updatedData, existingProductSwagger);
    updatedProductSwagger = OASParserUtil.updateAPIProductSwaggerOperations(apiToProductResourceMapping, updatedProductSwagger);
    saveSwaggerDefinition(productId, updatedProductSwagger, orgId);
    apiProduct.setDefinition(updatedProductSwagger);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 HashMap (java.util.HashMap)30 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)30 API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 ArrayList (java.util.ArrayList)23 API (org.wso2.carbon.apimgt.api.model.API)20 Map (java.util.Map)19 IOException (java.io.IOException)18 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)16 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)15 Scope (org.wso2.carbon.apimgt.api.model.Scope)15 HashSet (java.util.HashSet)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)12 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12