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;
}
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();
}
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;
}
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;
}
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;
}
Aggregations