Java Code Examples for io.swagger.v3.oas.models.Operation#addExtension()

The following examples show how to use io.swagger.v3.oas.models.Operation#addExtension() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScalaGatlingCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Creates all the necessary openapi vendor extensions and feeder files for gatling
 *
 * @param operation     OpoenAPI Operation
 * @param parameters    OpenAPI Parameters
 * @param parameterType OpenAPI Parameter Type
 */
private void prepareGatlingData(Operation operation, Set<Parameter> parameters, String parameterType) {
    if (parameters.size() > 0) {
        List<String> parameterNames = new ArrayList<>();
        List<Object> vendorList = new ArrayList<>();
        for (Parameter parameter : parameters) {
            Map<String, Object> extensionMap = new HashMap<>();
            extensionMap.put("gatlingParamName", parameter.getName());
            extensionMap.put("gatlingParamValue", "${" + parameter.getName() + "}");
            vendorList.add(extensionMap);
            parameterNames.add(parameter.getName());
        }
        operation.addExtension("x-gatling-" + parameterType.toLowerCase(Locale.ROOT) + "-params", vendorList);
        operation.addExtension("x-gatling-" + parameterType.toLowerCase(Locale.ROOT) + "-feeder", operation.getOperationId() + parameterType.toUpperCase(Locale.ROOT) + "Feeder");
        try {
            FileUtils.writeStringToFile(
                new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + parameterType.toLowerCase(Locale.ROOT) + "Params.csv"),
                StringUtils.join(parameterNames, ","),
                StandardCharsets.UTF_8
            );
        } catch (IOException ioe) {
            LOGGER.error("Could not create feeder file for operationId" + operation.getOperationId(), ioe);
        }
    }
}
 
Example 2
Source File: JMeterClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    if (openAPI != null && openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem path = openAPI.getPaths().get(pathname);
            if (path.readOperations() != null) {
                for (Operation operation : path.readOperations()) {
                    String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{");
                    operation.addExtension("x-path", pathWithDollars);
                }
            }
        }
    }
}
 
Example 3
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Add openAPI path item to the the openAPI object.
 *
 * @param path            name of the pathItem
 * @param scopes          array of operation scopes
 * @param throttlingTier throttling tier
 */
void addOpenAPIPath(String path, String[] scopes, String throttlingTier) {
    PathItem pathItem = new PathItem();
    Operation operation = new Operation();
    operation.setOperationId(UUID.randomUUID().toString());
    addOauth2SecurityRequirement(operation, scopes);
    if (StringUtils.isNotEmpty(throttlingTier)) {
        operation.addExtension(OpenAPIConstants.THROTTLING_TIER, throttlingTier);
    }
    //needs to add the basic Auth Requirement to the operation level because if scopes are mentioned,
    // there would be oauth2 security requirement in method level.
    if (isBasicAuthEnabled) {
        addBasicAuthSecurityRequirement(operation);
    }
    if (isAPIKeyEnabled) {
        addAPIKeySecurityRequirement(operation);
    }
    //For each path, the only available http method is "post" according to the grpc mapping.
    pathItem.setPost(operation);
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    //as Responses object is mandatory
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.setDescription(ProtoToOpenAPIConstants.RESPONSE_DESCRIPTION);
    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse(ProtoToOpenAPIConstants.SUCCESS_RESPONSE_CODE, apiResponse);
    operation.setResponses(apiResponses);
    //append forward slash to preserve openAPI syntax
    openAPI.getPaths().addPathItem(ProtoToOpenAPIConstants.PATH_SEPARATOR + path, pathItem);
}
 
Example 4
Source File: ReflectionUtilsTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetControllerNameFromExtension() throws Exception {
    Operation operation = new Operation();
    operation.addExtension(Constants.X_SWAGGER_ROUTER_CONTROLLER, "com.test.class");

    String controllerName = utils.getControllerName(operation);
    assertEquals(controllerName, "com.test.class");
}
 
Example 5
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList,
        String apiLevelTier) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(oasDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).readOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList
                        .contains(op.getExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }
}
 
Example 6
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);
    if (openAPI == null) {
        return;
    }
    if (openAPI.getPaths() != null) {
        for (String pathname : openAPI.getPaths().keySet()) {
            PathItem path = openAPI.getPaths().get(pathname);
            if (path.readOperations() == null) {
                continue;
            }
            for (Operation operation : path.readOperations()) {
                LOGGER.info("Processing operation " + operation.getOperationId());
                if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) {
                    String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json";
                    List<String> consumes = new ArrayList<>(getConsumesInfo(openAPI, operation));
                    String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
                    operation.addExtension("x-contentType", contentType);
                }
                String accepts = getAccept(openAPI, operation);
                operation.addExtension("x-accepts", accepts);

            }
        }
    }

    // TODO: Setting additionalProperties is not the responsibility of this method. These side-effects should be moved elsewhere to prevent unexpected behaviors.
    if (artifactVersion == null) {
        // If no artifactVersion is provided in additional properties, version from API specification is used.
        // If none of them is provided then fallbacks to default version
        if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION) && additionalProperties.get(CodegenConstants.ARTIFACT_VERSION) != null) {
            this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
        } else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
            this.setArtifactVersion(openAPI.getInfo().getVersion());
        } else {
            this.setArtifactVersion(ARTIFACT_VERSION_DEFAULT_VALUE);
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

    if (additionalProperties.containsKey(CodegenConstants.SNAPSHOT_VERSION)) {
        if (convertPropertyToBooleanAndWriteBack(CodegenConstants.SNAPSHOT_VERSION)) {
            this.setArtifactVersion(this.buildSnapshotVersion(this.getArtifactVersion()));
        }
    }
    additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);

}
 
Example 7
Source File: ScalaGatlingCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Modifies the openapi doc to make mustache easier to use
 *
 * @param openAPI input openapi document
 */
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    for (String pathname : openAPI.getPaths().keySet()) {
        PathItem path = openAPI.getPaths().get(pathname);
        if (path.readOperations() == null) {
            continue;
        }
        for (Operation operation : path.readOperations()) {

            if (operation.getExtensions() == null) {
                operation.setExtensions(new HashMap());
            }

            if (!operation.getExtensions().keySet().contains("x-gatling-path")) {
                if (pathname.contains("{")) {
                    String gatlingPath = pathname.replaceAll("\\{", "\\$\\{");
                    operation.addExtension("x-gatling-path", gatlingPath);
                } else {
                    operation.addExtension("x-gatling-path", pathname);
                }
            }

            Set<Parameter> headerParameters = new HashSet<>();
            Set<Parameter> formParameters = new HashSet<>();
            Set<Parameter> queryParameters = new HashSet<>();
            Set<Parameter> pathParameters = new HashSet<>();

            if (operation.getParameters() != null) {

                for (Parameter parameter : operation.getParameters()) {
                    if (parameter.getIn().equalsIgnoreCase("header")) {
                        headerParameters.add(parameter);
                    }
                /* need to revise below as form parameter is no longer in the parameter list
                if (parameter.getIn().equalsIgnoreCase("formData")) {
                    formParameters.add(parameter);
                }
                */
                    if (parameter.getIn().equalsIgnoreCase("query")) {
                        queryParameters.add(parameter);
                    }
                    if (parameter.getIn().equalsIgnoreCase("path")) {
                        pathParameters.add(parameter);
                    }
                /* TODO need to revise below as body is no longer in the parameter
                if (parameter.getIn().equalsIgnoreCase("body")) {
                    BodyParameter bodyParameter = (BodyParameter) parameter;
                    Model model = bodyParameter.getSchema();
                    if (model instanceof RefModel) {
                        String[] refArray = model.getReference().split("\\/");
                        operation.setVendorExtension("x-gatling-body-object", refArray[refArray.length - 1] + ".toStringBody");
                        Set<String> bodyFeederParams = new HashSet<>();
                        Set<String> sessionBodyVars = new HashSet<>();
                        for (Map.Entry<String, Model> modelEntry : swagger.getDefinitions().entrySet()) {
                            if (refArray[refArray.length - 1].equalsIgnoreCase(modelEntry.getKey())) {
                                for (Map.Entry<String, Property> propertyEntry : modelEntry.getValue().getProperties().entrySet()) {
                                    bodyFeederParams.add(propertyEntry.getKey());
                                    sessionBodyVars.add("\"${" + propertyEntry.getKey() + "}\"");
                                }
                            }
                        }
                        operation.setVendorExtension("x-gatling-body-feeder", operation.getOperationId() + "BodyFeeder");
                        operation.setVendorExtension("x-gatling-body-feeder-params", StringUtils.join(sessionBodyVars, ","));
                        try {
                            FileUtils.writeStringToFile(
                                new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + "bodyParams.csv"),
                                StringUtils.join(bodyFeederParams, ","),
                                StandardCharsets.UTF_8
                            );
                        } catch (IOException ioe) {
                            LOGGER.error("Could not create feeder file for operationId" + operation.getOperationId(), ioe);
                        }

                    } else if (model instanceof ArrayModel) {
                        operation.setVendorExtension("x-gatling-body-object", "StringBody(\"[]\")");
                    } else {
                        operation.setVendorExtension("x-gatling-body-object", "StringBody(\"{}\")");
                    }

                }
                */
                }
            }

            prepareGatlingData(operation, headerParameters, "header");
            prepareGatlingData(operation, formParameters, "form");
            prepareGatlingData(operation, queryParameters, "query");
            prepareGatlingData(operation, pathParameters, "path");
        }
    }

}
 
Example 8
Source File: NodeJSExpressServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
    public void preprocessOpenAPI(OpenAPI openAPI) {
        URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides());
        String host = URLPathUtils.getProtocolAndHost(url);
        String port = URLPathUtils.getPort(url, defaultServerPort);
        String basePath = url.getPath();

        if (additionalProperties.containsKey(SERVER_PORT)) {
            port = additionalProperties.get(SERVER_PORT).toString();
        }
        this.additionalProperties.put(SERVER_PORT, port);

        if (openAPI.getInfo() != null) {
            Info info = openAPI.getInfo();
            if (info.getTitle() != null) {
                // when info.title is defined, use it for projectName
                // used in package.json
                projectName = info.getTitle()
                        .replaceAll("[^a-zA-Z0-9]", "-")
                        .replaceAll("^[-]*", "")
                        .replaceAll("[-]*$", "")
                        .replaceAll("[-]{2,}", "-")
                        .toLowerCase(Locale.ROOT);
                this.additionalProperties.put("projectName", projectName);
            }
        }

        // need vendor extensions
        Paths paths = openAPI.getPaths();
        if (paths != null) {
            for (String pathname : paths.keySet()) {
                PathItem path = paths.get(pathname);
                Map<HttpMethod, Operation> operationMap = path.readOperationsMap();
                if (operationMap != null) {
                    for (HttpMethod method : operationMap.keySet()) {
                        Operation operation = operationMap.get(method);
                        String tag = "default";
                        if (operation.getTags() != null && operation.getTags().size() > 0) {
                            tag = toApiName(operation.getTags().get(0));
                        }
                        if (operation.getOperationId() == null) {
                            operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString()));
                        }
                        // add x-openapi-router-controller
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-controller") == null) {
//                            operation.addExtension("x-openapi-router-controller", sanitizeTag(tag) + "Controller");
//                        }
//                        // add x-openapi-router-service
//                        if (operation.getExtensions() == null ||
//                                operation.getExtensions().get("x-openapi-router-service") == null) {
//                            operation.addExtension("x-openapi-router-service", sanitizeTag(tag) + "Service");
//                        }
                        if (operation.getExtensions() == null ||
                                operation.getExtensions().get("x-eov-operation-handler") == null) {
                            operation.addExtension("x-eov-operation-handler", "controllers/" + sanitizeTag(tag) + "Controller");
                        }
                    }
                }
            }
        }

    }
 
Example 9
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * 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) {
    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();
        //initializing apiResourceMediationPolicyObject
        APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
        //setting path for apiResourceMediationPolicyObject
        apiResourceMediationPolicyObject.setPath(path);
        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 (Operation op : operations) {
            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;
            for (Map.Entry<PathItem.HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) {
                //add verb to apiResourceMediationPolicyObject
                apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey()));
            }
            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;
}
 
Example 10
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Updates managed info of a provided operation such as auth type and throttling
 *
 * @param resource  API resource data
 * @param operation swagger operation
 */
private void updateOperationManagedInfo(SwaggerData.Resource resource, Operation operation) {
    String authType = resource.getAuthType();
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application & Application User";
    }
    if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application User";
    }
    if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(authType)) {
        authType = "Application";
    }
    operation.addExtension(APIConstants.SWAGGER_X_AUTH_TYPE, authType);
    operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, resource.getPolicy());
    // AWS Lambda: set arn & timeout to swagger
    if (resource.getAmznResourceName() != null) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME, resource.getAmznResourceName());
    }
    if (resource.getAmznResourceTimeout() != 0) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT, resource.getAmznResourceTimeout());
    }
    updateLegacyScopesFromOperation(resource, operation);
    List<SecurityRequirement> security = operation.getSecurity();
    if (security == null) {
        security = new ArrayList<>();
        operation.setSecurity(security);
    }
    for (Map<String, List<String>> requirement : security) {
        if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) != null) {

            if (resource.getScopes().isEmpty()) {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
            } else {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey)
                        .collect(Collectors.toList()));
            }
            return;
        }
    }
    // if oauth2SchemeKey not present, add a new
    SecurityRequirement defaultRequirement = new SecurityRequirement();
    if (resource.getScopes().isEmpty()) {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
    } else {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey)
                .collect(Collectors.toList()));
    }
    security.add(defaultRequirement);
}