Search in sources :

Example 31 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.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;
}
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 32 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.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;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Operation(io.swagger.models.Operation) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 33 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.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;
}
Also used : Response(io.swagger.models.Response) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) RefResponse(io.swagger.models.RefResponse) Operation(io.swagger.models.Operation) PathParameter(io.swagger.models.parameters.PathParameter)

Example 34 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class OAS2Parser method removeExamplesFromSwagger.

/**
 * Remove x-wso2-examples from all the paths from the swagger.
 *
 * @param swaggerString Swagger as String
 */
public String removeExamplesFromSwagger(String swaggerString) throws APIManagementException {
    try {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swagger = swaggerParser.parse(swaggerString);
        swagger.getPaths().values().forEach(path -> {
            path.getOperations().forEach(operation -> {
                if (operation.getVendorExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getVendorExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            });
        });
        return Yaml.pretty().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 35 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class APIDefinitionFromOpenAPISpec method validateScopesFromSwagger.

/**
 * Called using the jaggery api. Checks if the swagger contains valid api scopes.
 *
 * @param swagger Swagger definition
 * @return true if the scope definition is valid
 * @throws APIManagementException
 */
public Boolean validateScopesFromSwagger(String swagger) throws APIManagementException {
    try {
        Set<Scope> scopes = getScopes(swagger);
        JSONParser parser = new JSONParser();
        JSONObject swaggerJson;
        swaggerJson = (JSONObject) parser.parse(swagger);
        if (swaggerJson.get("paths") != null) {
            JSONObject paths = (JSONObject) swaggerJson.get("paths");
            for (Object uriTempKey : paths.keySet()) {
                String uriTemp = (String) uriTempKey;
                // if url template is a custom attribute "^x-" ignore.
                if (uriTemp.startsWith("x-") || uriTemp.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTemp);
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    continue;
                }
                for (Object httpVerbKey : path.keySet()) {
                    String httpVerb = (String) httpVerbKey;
                    JSONObject operation = (JSONObject) path.get(httpVerb);
                    String operationScope = (String) operation.get(APIConstants.SWAGGER_X_SCOPE);
                    Scope scope = APIUtil.findScopeByKey(scopes, operationScope);
                    if (scope == null && operationScope != null) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (APIManagementException e) {
        handleException("Error when validating scopes", e);
        return false;
    } catch (ParseException e) {
        handleException("Error when validating scopes", e);
        return false;
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 HashMap (java.util.HashMap)55 ArrayList (java.util.ArrayList)43 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)42 Test (org.testng.annotations.Test)34 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)29 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)29 Map (java.util.Map)28 IOException (java.io.IOException)23 API (org.wso2.carbon.apimgt.api.model.API)22 List (java.util.List)20 JSONObject (org.json.simple.JSONObject)20 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)20 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)19 LinkedHashMap (java.util.LinkedHashMap)18 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)18 OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)18 APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16