Search in sources :

Example 1 with APIResourceMediationPolicy

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

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

the class ApisApiServiceImpl method getGeneratedMockScriptsOfAPI.

/**
 * Gets generated scripts
 *
 * @param apiId  API Id
 * @param ifNoneMatch If-None-Match header value
 * @param messageContext message context
 * @return list of policies of generated sample payload
 * @throws APIManagementException
 */
@Override
public Response getGeneratedMockScriptsOfAPI(String apiId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
    APIIdentifier apiIdentifier = originalAPI.getId();
    String apiDefinition = apiProvider.getOpenAPIDefinition(apiIdentifier, organization);
    Map<String, Object> examples = OASParserUtil.generateExamples(apiDefinition);
    List<APIResourceMediationPolicy> policies = (List<APIResourceMediationPolicy>) examples.get(APIConstants.MOCK_GEN_POLICY_LIST);
    return Response.ok().entity(APIMappingUtil.fromMockPayloadsToListDTO(policies)).build();
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONObject(org.json.simple.JSONObject) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 3 with APIResourceMediationPolicy

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

the class OAS2Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) throws APIManagementException {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        Map<String, Model> definitions = swagger.getDefinitions();
        // operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        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>();
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<HttpMethod, Operation> operationEntry = (Map.Entry<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");
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    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);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            // sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        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) ArrayList(java.util.ArrayList) Operation(io.swagger.models.Operation) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 4 with APIResourceMediationPolicy

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

the class APIMappingUtil method fromMockPayloadToDTO.

/**
 * This method creates object of MockPayloadDTO.
 *
 * @param model APIResourceMediationPolicy object
 * @return mockResponsePayloadInfoDTO object
 */
public static MockResponsePayloadInfoDTO fromMockPayloadToDTO(APIResourceMediationPolicy model) {
    MockResponsePayloadInfoDTO mockResponsePayloadInfoDTO = new MockResponsePayloadInfoDTO();
    mockResponsePayloadInfoDTO.setPath(model.getPath());
    mockResponsePayloadInfoDTO.setVerb(model.getVerb());
    mockResponsePayloadInfoDTO.setContent(model.getContent());
    return mockResponsePayloadInfoDTO;
}
Also used : MockResponsePayloadInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MockResponsePayloadInfoDTO)

Example 5 with APIResourceMediationPolicy

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

the class APIMappingUtil method fromMockPayloadsToListDTO.

/**
 * This method creates the list of MockPayloadDTO objects for resetting inline prototyping scripts.
 *
 * @param mockPayloads APIResourceMediationPolicy List
 * @return mockResponsePayloadListDTO (list of MockPayloadDTO)
 * @throws APIManagementException
 */
public static MockResponsePayloadListDTO fromMockPayloadsToListDTO(List<APIResourceMediationPolicy> mockPayloads) throws APIManagementException {
    MockResponsePayloadListDTO mockResponsePayloadListDTO = new MockResponsePayloadListDTO();
    List<MockResponsePayloadInfoDTO> mockResponsePayloadInfoDTOS = mockResponsePayloadListDTO.getList();
    for (APIResourceMediationPolicy apiResourceMediationPolicy : mockPayloads) {
        mockResponsePayloadInfoDTOS.add(fromMockPayloadToDTO(apiResourceMediationPolicy));
    }
    return mockResponsePayloadListDTO;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) MockResponsePayloadListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MockResponsePayloadListDTO) MockResponsePayloadInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MockResponsePayloadInfoDTO)

Aggregations

APIResourceMediationPolicy (org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy)4 ArrayList (java.util.ArrayList)3 HttpMethod (io.swagger.models.HttpMethod)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 JSONObject (org.json.simple.JSONObject)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 MockResponsePayloadInfoDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MockResponsePayloadInfoDTO)2 Model (io.swagger.models.Model)1 Operation (io.swagger.models.Operation)1 Path (io.swagger.models.Path)1 RefModel (io.swagger.models.RefModel)1 RefPath (io.swagger.models.RefPath)1 Swagger (io.swagger.models.Swagger)1 SwaggerParser (io.swagger.parser.SwaggerParser)1 SwaggerDeserializationResult (io.swagger.parser.util.SwaggerDeserializationResult)1 OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 Operation (io.swagger.v3.oas.models.Operation)1 PathItem (io.swagger.v3.oas.models.PathItem)1