use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class OAS3Parser method modifyGraphQLSwagger.
/**
* Construct openAPI definition for graphQL. Add get and post operations
*
* @param openAPI OpenAPI
* @return modified openAPI for GraphQL
*/
private void modifyGraphQLSwagger(OpenAPI openAPI) {
SwaggerData.Resource resource = new SwaggerData.Resource();
resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
resource.setPath("/");
resource.setVerb(APIConstants.HTTP_POST);
Operation postOperation = createOperation(resource);
// post operation
RequestBody requestBody = new RequestBody();
requestBody.setDescription("Query or mutation to be passed to graphQL API");
requestBody.setRequired(true);
JSONObject typeOfPayload = new JSONObject();
JSONObject payload = new JSONObject();
typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);
Schema postSchema = new Schema();
postSchema.setType(APIConstants.OBJECT);
postSchema.setProperties(payload);
MediaType mediaType = new MediaType();
mediaType.setSchema(postSchema);
Content content = new Content();
content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
requestBody.setContent(content);
postOperation.setRequestBody(requestBody);
// add post and get operations to path /*
PathItem pathItem = new PathItem();
pathItem.setPost(postOperation);
Paths paths = new Paths();
paths.put("/", pathItem);
openAPI.setPaths(paths);
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class OAS3Parser method removeExamplesFromOpenAPI.
/**
* Remove x-examples from all the paths from the OpenAPI definition.
*
* @param apiDefinition OpenAPI definition as String
*/
public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException {
try {
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 openAPI = parseAttemptForV3.getOpenAPI();
for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
String path = entry.getKey();
List<Operation> operations = openAPI.getPaths().get(path).readOperations();
for (Operation operation : operations) {
if (operation.getExtensions() != null && operation.getExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
}
}
}
return Yaml.pretty().writeValueAsString(openAPI);
} catch (JsonProcessingException e) {
throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES);
}
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation 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.doc.model.Operation in project carbon-apimgt by wso2.
the class OAS2Parser method getURITemplates.
/**
* This method returns URI templates according to the given swagger file
*
* @param resourceConfigsJSON swaggerJSON
* @return URI Templates
* @throws APIManagementException
*/
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
Swagger swagger = getSwagger(resourceConfigsJSON);
Set<URITemplate> urlTemplates = new LinkedHashSet<>();
Set<Scope> scopes = getScopes(resourceConfigsJSON);
String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);
for (String pathString : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathString);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
Operation operation = entry.getValue();
URITemplate template = new URITemplate();
template.setHTTPVerb(entry.getKey().name().toUpperCase());
template.setHttpVerbs(entry.getKey().name().toUpperCase());
template.setUriTemplate(pathString);
List<String> opScopes = getScopeOfOperations(oauth2SchemeKey, operation);
if (!opScopes.isEmpty()) {
if (opScopes.size() == 1) {
String firstScope = opScopes.get(0);
if (StringUtils.isNotBlank(firstScope)) {
Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
if (scope == null) {
throw new APIManagementException("Scope '" + firstScope + "' not found.");
}
template.setScope(scope);
template.setScopes(scope);
}
} else {
template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
}
}
Map<String, Object> extensions = operation.getVendorExtensions();
if (extensions != null) {
if (extensions.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) {
String authType = (String) extensions.get(APIConstants.SWAGGER_X_AUTH_TYPE);
template.setAuthType(authType);
template.setAuthTypes(authType);
} else {
template.setAuthType("Any");
template.setAuthTypes("Any");
}
if (extensions.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) {
String throttlingTier = (String) extensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER);
template.setThrottlingTier(throttlingTier);
template.setThrottlingTiers(throttlingTier);
}
if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
String mediationScript = (String) extensions.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
template.setMediationScript(mediationScript);
template.setMediationScripts(template.getHTTPVerb(), mediationScript);
}
if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
template.setAmznResourceName((String) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
}
if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
template.setAmznResourceTimeout(((Long) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
}
}
urlTemplates.add(template);
}
}
return urlTemplates;
}
use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.
the class OAS2Parser method createOperation.
/**
* Creates a new operation object using the URI template object
*
* @param resource API resource data
* @return a new operation object using the URI template object
*/
private Operation createOperation(SwaggerData.Resource resource) {
Operation operation = new Operation();
List<String> pathParams = getPathParamNames(resource.getPath());
for (String pathParam : pathParams) {
PathParameter pathParameter = new PathParameter();
pathParameter.setName(pathParam);
pathParameter.setType("string");
operation.addParameter(pathParameter);
}
updateOperationManagedInfo(resource, operation);
Response response = new Response();
response.setDescription("OK");
operation.addResponse(APIConstants.SWAGGER_RESPONSE_200, response);
return operation;
}
Aggregations