Search in sources :

Example 1 with APIGenException

use of org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException in project carbon-mediation by wso2.

the class OpenAPIProcessor method getUpdatedSwaggerFromApi.

/**
 * Update a given swagger definition of the Synapse API.
 *
 * @param existingSwagger swagger definition needs to be updated.
 * @param isJSONIn        input swagger data type JSON / YAML.
 * @param isJSONOut       output swagger data type JSON / YAML.
 * @return updated swagger definition as string.
 */
public String getUpdatedSwaggerFromApi(String existingSwagger, boolean isJSONIn, boolean isJSONOut) throws APIGenException {
    if (api == null) {
        throw new APIGenException("Provided API is null");
    }
    if (StringUtils.isEmpty(existingSwagger)) {
        throw new APIGenException("Provided swagger definition is empty");
    }
    if (isJSONIn) {
        JsonNode jsonNodeTree = null;
        try {
            jsonNodeTree = new ObjectMapper().readTree(existingSwagger);
            existingSwagger = new YAMLMapper().writeValueAsString(jsonNodeTree);
        } catch (JsonProcessingException e) {
            throw new APIGenException("Error occurred while converting the swagger to YAML format", e);
        }
    }
    OpenAPIV3Parser apiv3Parser = new OpenAPIV3Parser();
    SwaggerParseResult swaggerParseResult = apiv3Parser.readContents(existingSwagger);
    OpenAPI openAPI = swaggerParseResult.getOpenAPI();
    Paths paths = openAPI.getPaths();
    Paths newPaths = new Paths();
    final Map<String, Object> dataMap = GenericApiObjectDefinition.getPathMap(api);
    for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
        boolean pathItemExists = false;
        PathItem pathItem;
        if (paths.containsKey(entry.getKey())) {
            pathItem = paths.get(entry.getKey());
            pathItemExists = true;
        } else {
            pathItem = new PathItem();
        }
        Map<String, Object> methodMap = (Map<String, Object>) entry.getValue();
        List<String> newMethodsList = new ArrayList<>();
        for (Map.Entry<String, Object> methodEntry : methodMap.entrySet()) {
            Operation operation = null;
            boolean operationExists = false;
            if (pathItemExists) {
                newMethodsList.add(methodEntry.getKey());
                switch(methodEntry.getKey()) {
                    case OPERATION_HTTP_GET:
                        operation = pathItem.getGet();
                        break;
                    case OPERATION_HTTP_POST:
                        operation = pathItem.getPost();
                        break;
                    case OPERATION_HTTP_DELETE:
                        operation = pathItem.getDelete();
                        break;
                    case OPERATION_HTTP_PUT:
                        operation = pathItem.getPut();
                        break;
                    case OPERATION_HTTP_HEAD:
                        operation = pathItem.getHead();
                        break;
                    case OPERATION_HTTP_PATCH:
                        operation = pathItem.getPatch();
                        break;
                    case OPERATION_HTTP_OPTIONS:
                        operation = pathItem.getOptions();
                }
            }
            if (operation == null) {
                operation = new Operation();
            } else {
                operationExists = true;
            }
            Object[] paramArr = (Object[]) ((Map<String, Object>) methodEntry.getValue()).get(PARAMETERS);
            if (operationExists) {
                List<Parameter> parameters = operation.getParameters();
                List<Parameter> newParameter = new ArrayList<>();
                if (paramArr != null && paramArr.length > 0) {
                    for (Object o : paramArr) {
                        String paramType = (String) ((Map<String, Object>) o).get(PARAMETER_IN);
                        String paramName = (String) ((Map<String, Object>) o).get(PARAMETER_NAME);
                        Optional<Parameter> existing = null;
                        switch(paramType) {
                            case PARAMETER_IN_PATH:
                                existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof PathParameter).findFirst();
                                break;
                            case PARAMETER_IN_QUERY:
                                existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof QueryParameter).findFirst();
                                break;
                        }
                        if (existing == null || !existing.isPresent()) {
                            // if we found parameter do not update
                            updatePathQueryAndBodyParams(operation, paramType, paramName, newParameter);
                        } else {
                            newParameter.add(existing.get());
                        }
                        updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
                    }
                } else {
                    // no parameters defined ( default resource in the API )
                    updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
                }
                // remove deleted parameters from swagger
                if (newParameter.size() > 0) {
                    parameters.removeIf(c -> !newParameter.contains(c));
                }
            } else {
                populateParameters(pathItem, methodMap);
            }
        }
        if (pathItemExists) {
            // Remove additional methods
            List<String> allMethodsList = Arrays.asList(new String[] { "get", "post", "put", "delete", "head", "options", "patch" });
            List<String> differences = allMethodsList.stream().filter(element -> !newMethodsList.contains(element)).collect(Collectors.toList());
            for (String method : differences) {
                switch(method) {
                    case OPERATION_HTTP_GET:
                        pathItem.setGet(null);
                        break;
                    case OPERATION_HTTP_POST:
                        pathItem.setPost(null);
                        break;
                    case OPERATION_HTTP_DELETE:
                        pathItem.setDelete(null);
                        break;
                    case OPERATION_HTTP_PUT:
                        pathItem.setPut(null);
                        break;
                    case OPERATION_HTTP_HEAD:
                        pathItem.setHead(null);
                        break;
                    case OPERATION_HTTP_PATCH:
                        pathItem.setPatch(null);
                        break;
                    case OPERATION_HTTP_OPTIONS:
                        pathItem.setOptions(null);
                        break;
                }
            }
        }
        newPaths.put(entry.getKey(), pathItem);
    }
    // Adding the new path map
    openAPI.setPaths(newPaths);
    updateInfoSection(openAPI);
    try {
        updateServersSection(openAPI);
    } catch (AxisFault axisFault) {
        throw new APIGenException("Error occurred while getting host details", axisFault);
    }
    try {
        if (isJSONOut) {
            return Json.mapper().writeValueAsString(openAPI);
        }
        return Yaml.mapper().writeValueAsString(openAPI);
    } catch (JsonProcessingException e) {
        throw new APIGenException("Error occurred while creating the output JAML/JSON", e);
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) OPERATION_HTTP_PATCH(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_PATCH) Yaml(io.swagger.v3.core.util.Yaml) URL(java.net.URL) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Operation(io.swagger.v3.oas.models.Operation) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) URLBasedVersionStrategy(org.apache.synapse.api.version.URLBasedVersionStrategy) PROTOCOL_HTTP_ONLY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP_ONLY) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Content(io.swagger.v3.oas.models.media.Content) API(org.apache.synapse.api.API) PROTOCOL_HTTP(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP) MediaType(io.swagger.v3.oas.models.media.MediaType) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) Paths(io.swagger.v3.oas.models.Paths) Collectors(java.util.stream.Collectors) OPERATION_HTTP_PUT(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_PUT) PARAMETER_IN_BODY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_BODY) List(java.util.List) Server(io.swagger.v3.oas.models.servers.Server) StringSchema(io.swagger.v3.oas.models.media.StringSchema) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PARAMETER_IN_PATH(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_PATH) Optional(java.util.Optional) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) AxisFault(org.apache.axis2.AxisFault) LogFactory(org.apache.commons.logging.LogFactory) OPERATION_HTTP_HEAD(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_HEAD) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PROTOCOL_HTTP_AND_HTTPS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP_AND_HTTPS) PARAMETERS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETERS) Json(io.swagger.v3.core.util.Json) PARAMETER_NAME(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_NAME) HashMap(java.util.HashMap) OPERATION_HTTP_OPTIONS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_OPTIONS) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) OPERATION_HTTP_GET(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_GET) Schema(io.swagger.v3.oas.models.media.Schema) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) OPERATION_HTTP_DELETE(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_DELETE) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) PARAMETER_IN(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PathItem(io.swagger.v3.oas.models.PathItem) Info(io.swagger.v3.oas.models.info.Info) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PARAMETER_IN_QUERY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_QUERY) PROTOCOL_HTTPS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTPS) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) Log(org.apache.commons.logging.Log) OPERATION_HTTP_POST(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_POST) AxisFault(org.apache.axis2.AxisFault) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) PathItem(io.swagger.v3.oas.models.PathItem) Paths(io.swagger.v3.oas.models.Paths) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with APIGenException

use of org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException in project carbon-mediation by wso2.

the class RestApiAdmin method generateUpdatedAPIFromSwagger.

/**
 * Function to generate updated existing API by referring to swagger definition (from JSON representation)
 *
 * @param swaggerJsonString swagger definition
 * @param existingApiName   name of the existing API
 * @return generated synapse API
 * @throws APIException
 */
public String generateUpdatedAPIFromSwagger(String swaggerJsonString, String existingApiName) throws APIException {
    if (swaggerJsonString == null || swaggerJsonString.isEmpty()) {
        handleException(log, "Provided swagger definition is empty, hence unable to generate API", null);
    }
    if (existingApiName == null || existingApiName.isEmpty()) {
        handleException(log, "Provided existing API name is empty, hence unable to generate API", null);
    }
    JsonParser jsonParser = new JsonParser();
    JsonElement swaggerJson = jsonParser.parse(swaggerJsonString);
    if (swaggerJson.isJsonObject()) {
        APIGenerator apiGenerator = new APIGenerator(swaggerJson.getAsJsonObject());
        try {
            API api = apiGenerator.generateUpdatedSynapseAPI(getSynapseAPIByName(existingApiName));
            return APISerializer.serializeAPI(api).toString();
        } catch (APIGenException e) {
            handleException(log, "Error occurred while generating API", e);
        }
    } else {
        handleException(log, "Error in swagger definition format: should be a json object", null);
    }
    // Definitely will not reach here
    return "";
}
Also used : APIGenException(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException) APIGenerator(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenerator) API(org.apache.synapse.api.API)

Example 3 with APIGenException

use of org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException in project carbon-mediation by wso2.

the class RestApiAdmin method generateUpdatedAPIFromSwaggerByFormat.

/**
 * Function to generate updated existing API by referring to swagger definition.
 *
 * @param swaggerJsonString swagger definition.
 * @param isJSON            input in YAML / JSON format.
 * @param existingApi       existing synapse API.
 * @return generated synapse API.
 * @throws APIException error occurred while retrieving host details.
 */
public String generateUpdatedAPIFromSwaggerByFormat(String swaggerJsonString, boolean isJSON, API existingApi) throws APIException {
    if (swaggerJsonString == null || swaggerJsonString.isEmpty()) {
        handleException(log, "Provided swagger definition is empty, hence unable to generate API", null);
    }
    if (existingApi == null) {
        handleException(log, "Provided existing API name is empty, hence unable to generate API", null);
    }
    if (!isJSON) {
        try {
            swaggerJsonString = GenericApiObjectDefinition.convertYamlToJson(swaggerJsonString);
        } catch (JsonProcessingException e) {
            handleException(log, "Error occurred while converting the provided YAML to JSON", null);
        }
    }
    JsonParser jsonParser = new JsonParser();
    JsonElement swaggerJson = jsonParser.parse(swaggerJsonString);
    if (swaggerJson.isJsonObject()) {
        APIGenerator apiGenerator = new APIGenerator(swaggerJson.getAsJsonObject());
        try {
            API api = apiGenerator.generateUpdatedSynapseAPI(existingApi);
            return APISerializer.serializeAPI(api).toString();
        } catch (APIGenException e) {
            handleException(log, "Error occurred while generating API", e);
        }
    } else {
        handleException(log, "Error in swagger definition format: should be a json object", null);
    }
    // Definitely will not reach here
    return "";
}
Also used : APIGenException(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException) APIGenerator(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenerator) API(org.apache.synapse.api.API) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with APIGenException

use of org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException in project carbon-mediation by wso2.

the class RestApiAdmin method generateAPIFromSwaggerByFormat.

/**
 * Function to generate API from swagger definition (from JSON representation)
 *
 * @param swaggerString swagger definition
 * @param isJSON        input in YAML / JSON format.
 * @return generated synapse API.
 * @throws APIException error occurred while retrieving host details.
 */
public String generateAPIFromSwaggerByFormat(String swaggerString, boolean isJSON) throws APIException {
    if (swaggerString == null || swaggerString.isEmpty()) {
        handleException(log, "Swagger provided is empty, hence unable to generate API", null);
    }
    if (!isJSON) {
        try {
            swaggerString = GenericApiObjectDefinition.convertYamlToJson(swaggerString);
        } catch (JsonProcessingException e) {
            handleException(log, "Error occurred while converting the provided YAML to JSON", null);
        }
    }
    JsonParser jsonParser = new JsonParser();
    JsonElement swaggerJson = jsonParser.parse(swaggerString);
    if (swaggerJson.isJsonObject()) {
        APIGenerator apiGenerator = new APIGenerator(swaggerJson.getAsJsonObject());
        try {
            API api = apiGenerator.generateSynapseAPI();
            return APISerializer.serializeAPI(api).toString();
        } catch (APIGenException e) {
            handleException(log, "Error occurred while generating API", e);
        }
    } else {
        handleException(log, "Error in swagger definition format: should be a json object", null);
    }
    // Definitely will not reach here
    return "";
}
Also used : APIGenException(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException) APIGenerator(org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenerator) API(org.apache.synapse.api.API) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

API (org.apache.synapse.api.API)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 APIGenException (org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenException)3 APIGenerator (org.wso2.carbon.mediation.commons.rest.api.swagger.APIGenerator)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLMapper (com.fasterxml.jackson.dataformat.yaml.YAMLMapper)1 Json (io.swagger.v3.core.util.Json)1 Yaml (io.swagger.v3.core.util.Yaml)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 Paths (io.swagger.v3.oas.models.Paths)1 Info (io.swagger.v3.oas.models.info.Info)1 Content (io.swagger.v3.oas.models.media.Content)1 MediaType (io.swagger.v3.oas.models.media.MediaType)1 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)1 Schema (io.swagger.v3.oas.models.media.Schema)1 StringSchema (io.swagger.v3.oas.models.media.StringSchema)1 Parameter (io.swagger.v3.oas.models.parameters.Parameter)1