Java Code Examples for io.swagger.v3.oas.models.PathItem#readOperationsMap()
The following examples show how to use
io.swagger.v3.oas.models.PathItem#readOperationsMap() .
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: PathItemOperationsValidator.java From servicecomb-toolkit with Apache License 2.0 | 6 votes |
@Override public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location, PathItem oasObject) { if (StringUtils.isNotBlank(oasObject.get$ref())) { return emptyList(); } List<OasViolation> violations = new ArrayList<>(); Map<PathItem.HttpMethod, Operation> operationMap = oasObject.readOperationsMap(); for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationMap.entrySet()) { PathItem.HttpMethod method = entry.getKey(); Operation operation = entry.getValue(); OasObjectPropertyLocation operationLocation = location.property(method.toString().toLowerCase(), OasObjectType.OPERATION); violations.addAll( OasObjectValidatorUtils.doValidateProperty(context, operationLocation, operation, operationValidators)); } return violations; }
Example 2
Source File: EndpointUtils.java From openapi-diff with Apache License 2.0 | 6 votes |
public static List<Endpoint> convert2EndpointList(Map<String, PathItem> map) { List<Endpoint> endpoints = new ArrayList<>(); if (null == map) return endpoints; for (Map.Entry<String, PathItem> entry : map.entrySet()) { String url = entry.getKey(); PathItem path = entry.getValue(); Map<PathItem.HttpMethod, Operation> operationMap = path.readOperationsMap(); for (Map.Entry<PathItem.HttpMethod, Operation> entryOper : operationMap.entrySet()) { PathItem.HttpMethod httpMethod = entryOper.getKey(); Operation operation = entryOper.getValue(); Endpoint endpoint = new Endpoint(); endpoint.setPathUrl(url); endpoint.setMethod(httpMethod); endpoint.setSummary(operation.getSummary()); endpoint.setPath(path); endpoint.setOperation(operation); endpoints.add(endpoint); } } return endpoints; }
Example 3
Source File: PathDiff.java From openapi-diff with Apache License 2.0 | 6 votes |
public Optional<ChangedPath> diff(PathItem left, PathItem right, DiffContext context) { Map<PathItem.HttpMethod, Operation> oldOperationMap = left.readOperationsMap(); Map<PathItem.HttpMethod, Operation> newOperationMap = right.readOperationsMap(); MapKeyDiff<PathItem.HttpMethod, Operation> operationsDiff = MapKeyDiff.diff(oldOperationMap, newOperationMap); List<PathItem.HttpMethod> sharedMethods = operationsDiff.getSharedKey(); ChangedPath changedPath = new ChangedPath(context.getUrl(), left, right, context) .setIncreased(operationsDiff.getIncreased()) .setMissing(operationsDiff.getMissing()); for (PathItem.HttpMethod method : sharedMethods) { Operation oldOperation = oldOperationMap.get(method); Operation newOperation = newOperationMap.get(method); openApiDiff .getOperationDiff() .diff(oldOperation, newOperation, context.copyWithMethod(method)) .ifPresent(changedPath.getChanged()::add); } openApiDiff .getExtensionsDiff() .diff(left.getExtensions(), right.getExtensions(), context) .ifPresent(changedPath::setExtensions); return isChanged(changedPath); }
Example 4
Source File: CallbackProcessor.java From swagger-parser with Apache License 2.0 | 6 votes |
public void processCallback(Callback callback) { if (callback.get$ref() != null){ processReferenceCallback(callback); } //Resolver PathItem for(String name : callback.keySet()){ PathItem pathItem = callback.get(name); final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap(); for (PathItem.HttpMethod httpMethod : operationMap.keySet()) { Operation operation = operationMap.get(httpMethod); operationProcessor.processOperation(operation); } List<Parameter> parameters = pathItem.getParameters(); if (parameters != null) { for (Parameter parameter: parameters){ parameterProcessor.processParameter(parameter); } } } }
Example 5
Source File: AbstractOpenApiResource.java From springdoc-openapi with Apache License 2.0 | 5 votes |
/** * Calculate path. * * @param routerOperation the router operation */ protected void calculatePath(RouterOperation routerOperation) { String operationPath = routerOperation.getPath(); io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation(); String[] methodConsumes = routerOperation.getConsumes(); String[] methodProduces = routerOperation.getProduces(); String[] headers = routerOperation.getHeaders(); Map<String, String> queryParams = routerOperation.getQueryParams(); OpenAPI openAPI = openAPIBuilder.getCalculatedOpenAPI(); Paths paths = openAPI.getPaths(); Map<HttpMethod, Operation> operationMap = null; if (paths.containsKey(operationPath)) { PathItem pathItem = paths.get(operationPath); operationMap = pathItem.readOperationsMap(); } for (RequestMethod requestMethod : routerOperation.getMethods()) { Operation existingOperation = getExistingOperation(operationMap, requestMethod); MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers); methodAttributes.setMethodOverloaded(existingOperation != null); Operation operation = getOperation(routerOperation, existingOperation); if (apiOperation != null) openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes); String operationId = operationParser.getOperationId(operation.getOperationId(), openAPI); operation.setOperationId(operationId); fillParametersList(operation, queryParams, methodAttributes); if (!CollectionUtils.isEmpty(operation.getParameters())) operation.getParameters().forEach(parameter -> { if (parameter.getSchema() == null) parameter.setSchema(new StringSchema()); if (parameter.getIn() == null) parameter.setIn(ParameterIn.QUERY.toString()); } ); PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths); paths.addPathItem(operationPath, pathItemObject); } }
Example 6
Source File: JavaVertXServerCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
private void manageOperationNames(PathItem path, String pathname) { String serviceIdTemp; Map<HttpMethod, Operation> operationMap = path.readOperationsMap(); if (operationMap != null) { for (Entry<HttpMethod, Operation> entry : operationMap.entrySet()) { serviceIdTemp = computeServiceId(pathname, entry); entry.getValue().addExtension("x-serviceid", serviceIdTemp); entry.getValue().addExtension("x-serviceid-varname", serviceIdTemp.toUpperCase(Locale.ROOT) + "_SERVICE_ID"); } } }
Example 7
Source File: PathsProcessor.java From swagger-parser with Apache License 2.0 | 5 votes |
public void processPaths() { final Map<String, PathItem> pathMap = openAPI.getPaths(); if (pathMap == null) { return; } for (String pathStr : pathMap.keySet()) { PathItem pathItem = pathMap.get(pathStr); addParametersToEachOperation(pathItem); if (pathItem.get$ref() != null) { PathItem resolvedPath = processReferencePath(pathItem); String pathRef = pathItem.get$ref().split("#")[0]; if (resolvedPath != null) { updateLocalRefs(resolvedPath, pathRef); //we need to put the resolved path into swagger object openAPI.path(pathStr, resolvedPath); pathItem = resolvedPath; } } //at this point we can process this path final List<Parameter> processedPathParameters = parameterProcessor.processParameters(pathItem.getParameters()); pathItem.setParameters(processedPathParameters); final Map<PathItem.HttpMethod, Operation> operationMap = pathItem.readOperationsMap(); for (PathItem.HttpMethod httpMethod : operationMap.keySet()) { Operation operation = operationMap.get(httpMethod); operationProcessor.processOperation(operation); } } }
Example 8
Source File: OASParserUtil.java From carbon-apimgt with Apache License 2.0 | 5 votes |
private static void readPathsAndScopes(PathItem srcPathItem, URITemplate uriTemplate, final Set<Scope> allScopes, SwaggerUpdateContext context) { Map<PathItem.HttpMethod, Operation> srcOperations = srcPathItem.readOperationsMap(); PathItem.HttpMethod httpMethod = PathItem.HttpMethod.valueOf(uriTemplate.getHTTPVerb().toUpperCase()); Operation srcOperation = srcOperations.get(httpMethod); Paths paths = context.getPaths(); Set<Scope> aggregatedScopes = context.getAggregatedScopes(); if (!paths.containsKey(uriTemplate.getUriTemplate())) { paths.put(uriTemplate.getUriTemplate(), new PathItem()); } PathItem pathItem = paths.get(uriTemplate.getUriTemplate()); pathItem.operation(httpMethod, srcOperation); readReferenceObjects(srcOperation, context); List<SecurityRequirement> srcOperationSecurity = srcOperation.getSecurity(); if (srcOperationSecurity != null) { for (SecurityRequirement requirement : srcOperationSecurity) { List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY); if (scopes != null) { for (String scopeKey : scopes) { for (Scope scope : allScopes) { if (scope.getKey().equals(scopeKey)) { aggregatedScopes.add(scope); } } } } } } }
Example 9
Source File: AbstractOpenApiResource.java From springdoc-openapi with Apache License 2.0 | 4 votes |
/** * Calculate path. * * @param handlerMethod the handler method * @param routerOperation the router operation */ protected void calculatePath(HandlerMethod handlerMethod, RouterOperation routerOperation) { String operationPath = routerOperation.getPath(); Set<RequestMethod> requestMethods = new HashSet<>(Arrays.asList(routerOperation.getMethods())); io.swagger.v3.oas.annotations.Operation apiOperation = routerOperation.getOperation(); String[] methodConsumes = routerOperation.getConsumes(); String[] methodProduces = routerOperation.getProduces(); String[] headers = routerOperation.getHeaders(); Map<String, String> queryParams = routerOperation.getQueryParams(); OpenAPI openAPI = openAPIBuilder.getCalculatedOpenAPI(); Components components = openAPI.getComponents(); Paths paths = openAPI.getPaths(); Map<HttpMethod, Operation> operationMap = null; if (paths.containsKey(operationPath)) { PathItem pathItem = paths.get(operationPath); operationMap = pathItem.readOperationsMap(); } for (RequestMethod requestMethod : requestMethods) { Operation existingOperation = getExistingOperation(operationMap, requestMethod); Method method = handlerMethod.getMethod(); // skip hidden operations if (operationParser.isHidden(method)) continue; RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), RequestMapping.class); MethodAttributes methodAttributes = new MethodAttributes(springDocConfigProperties.getDefaultConsumesMediaType(), springDocConfigProperties.getDefaultProducesMediaType(), methodConsumes, methodProduces, headers); methodAttributes.setMethodOverloaded(existingOperation != null); if (reqMappingClass != null) { methodAttributes.setClassConsumes(reqMappingClass.consumes()); methodAttributes.setClassProduces(reqMappingClass.produces()); } methodAttributes.calculateConsumesProduces(method); Operation operation = (existingOperation != null) ? existingOperation : new Operation(); if (isDeprecated(method)) operation.setDeprecated(true); // Add documentation from operation annotation if (apiOperation == null || StringUtils.isBlank(apiOperation.operationId())) apiOperation = AnnotatedElementUtils.findMergedAnnotation(method, io.swagger.v3.oas.annotations.Operation.class); calculateJsonView(apiOperation, methodAttributes, method); if (apiOperation != null) openAPI = operationParser.parse(apiOperation, operation, openAPI, methodAttributes); fillParametersList(operation, queryParams, methodAttributes); // compute tags operation = openAPIBuilder.buildTags(handlerMethod, operation, openAPI); io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyDoc = AnnotatedElementUtils.findMergedAnnotation(method, io.swagger.v3.oas.annotations.parameters.RequestBody.class); // RequestBody in Operation requestBuilder.getRequestBodyBuilder() .buildRequestBodyFromDoc(requestBodyDoc, methodAttributes, components, methodAttributes.getJsonViewAnnotationForRequestBody()) .ifPresent(operation::setRequestBody); // requests operation = requestBuilder.build(handlerMethod, requestMethod, operation, methodAttributes, openAPI); // responses ApiResponses apiResponses = responseBuilder.build(components, handlerMethod, operation, methodAttributes); operation.setResponses(apiResponses); Set<io.swagger.v3.oas.annotations.callbacks.Callback> apiCallbacks = AnnotatedElementUtils.findMergedRepeatableAnnotations(method, io.swagger.v3.oas.annotations.callbacks.Callback.class); // callbacks buildCallbacks(openAPI, methodAttributes, operation, apiCallbacks); // allow for customisation customiseOperation(operation, handlerMethod); PathItem pathItemObject = buildPathItem(requestMethod, operation, operationPath, paths); paths.addPathItem(operationPath, pathItemObject); } }
Example 10
Source File: PhpZendExpressivePathHandlerServerCodegen.java From openapi-generator with Apache License 2.0 | 4 votes |
/** * Generate additional model definitions from query parameters * * @param openAPI OpenAPI object */ @Override public void preprocessOpenAPI(OpenAPI openAPI) { super.preprocessOpenAPI(openAPI); Map<String, PathItem> 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); Map<String, Schema> schemas = new HashMap<>(); if (operation == null || operation.getParameters() == null) { continue; } List<String> requiredProperties = new ArrayList<>(); for (Parameter parameter : operation.getParameters()) { Schema schema = convertParameterToSchema(parameter); if (schema != null) { schemas.put(schema.getName(), schema); if (Boolean.TRUE.equals(parameter.getRequired())) { requiredProperties.add(schema.getName()); } } } if (!schemas.isEmpty()) { ObjectSchema model = new ObjectSchema(); String operationId = getOrGenerateOperationId(operation, pathname, method.name()); model.setDescription("Query parameters for " + operationId); model.setProperties(schemas); model.setRequired(requiredProperties); //Add internal extension directly, because addExtension filters extension names addInternalExtensionToSchema(model, VEN_FROM_QUERY, Boolean.TRUE); String definitionName = generateUniqueDefinitionName(operationId + "QueryData", openAPI); openAPI.getComponents().addSchemas(definitionName, model); String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName); addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, definitionModel); addInternalExtensionToOperation(operation, VEN_HAS_QUERY_DATA, Boolean.TRUE); } } } } } }
Example 11
Source File: PythonAbstractConnexionServerCodegen.java From openapi-generator with Apache License 2.0 | 4 votes |
@Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { // XXX - Revert the original parameter (and path) names to make sure we have // a consistent REST interface across other server/client languages: // // XXX - Reverts `x-python-connexion-openapi-name` back to the original (query/path) parameter name. // We do not want to have our REST API itself being converted to pythonic params. // This would be incompatible with other server implementations. OpenAPI openAPI = (OpenAPI) objs.get("openAPI"); Map<String, PathItem> paths = openAPI.getPaths(); if (paths != null) { List<String> pathnames = new ArrayList(paths.keySet()); for (String pythonPathname : pathnames) { PathItem path = paths.get(pythonPathname); // Fix path parameters back to original casing Map<String, Object> pathExtensions = path.getExtensions(); if (pathExtensions != null) { // Get and remove the (temporary) vendor extension String openapiPathname = (String) pathExtensions.remove("x-python-connexion-openapi-name"); if (openapiPathname != null && !openapiPathname.equals(pythonPathname)) { LOGGER.info("Path '" + pythonPathname + "' is not consistant with the original OpenAPI definition. It will be replaced back by '" + openapiPathname + "'"); paths.remove(pythonPathname); paths.put(openapiPathname, path); } } Map<HttpMethod, Operation> operationMap = path.readOperationsMap(); if (operationMap != null) { for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); if (operation.getParameters() != null) { for (Parameter parameter : operation.getParameters()) { Map<String, Object> parameterExtensions = parameter.getExtensions(); if (parameterExtensions != null) { // Get and remove the (temporary) vendor extension String swaggerParameterName = (String) parameterExtensions.remove("x-python-connexion-openapi-name"); if (swaggerParameterName != null) { String pythonParameterName = parameter.getName(); if (!swaggerParameterName.equals(pythonParameterName)) { LOGGER.info("Reverting name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' back to '" + swaggerParameterName + "'"); parameter.setName(swaggerParameterName); } else { LOGGER.debug("Name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' was unchanged."); } } else { LOGGER.debug("x-python-connexion-openapi-name was not set on parameter '" + parameter.getName() + "' of operation '" + operation.getOperationId() + "'"); } } } } } } } // Sort path names after variable name fix List<String> recoveredPathnames = new ArrayList(paths.keySet()); Collections.sort(recoveredPathnames); for (String pathname : recoveredPathnames) { PathItem pathItem = paths.remove(pathname); paths.put(pathname, pathItem); } } generateJSONSpecFile(objs); generateYAMLSpecFile(objs); for (Map<String, Object> operations : getOperations(objs)) { @SuppressWarnings("unchecked") List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<Map<String, Object>> opsByPathList = sortOperationsByPath(ops); operations.put("operationsByPath", opsByPathList); } return super.postProcessSupportingFileData(objs); }
Example 12
Source File: NodeJSExpressServerCodegen.java From openapi-generator with Apache License 2.0 | 4 votes |
@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 13
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * This method returns URI templates according to the given swagger file(Swagger version 3) * * @param openAPI OpenAPI * @return OpenAPI * @throws APIManagementException */ private OpenAPI injectOtherResourceScopesToDefaultScheme(OpenAPI openAPI) throws APIManagementException { List<String> schemes = getOtherSchemes(); Paths paths = openAPI.getPaths(); for (String pathKey : paths.keySet()) { PathItem pathItem = paths.get(pathKey); Map<PathItem.HttpMethod, Operation> operationsMap = pathItem.readOperationsMap(); SecurityRequirement updatedDefaultSecurityRequirement = new SecurityRequirement(); for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) { PathItem.HttpMethod httpMethod = entry.getKey(); Operation operation = entry.getValue(); List<SecurityRequirement> securityRequirements = operation.getSecurity(); if (securityRequirements == null) { securityRequirements = new ArrayList<>(); } if (APIConstants.SUPPORTED_METHODS.contains(httpMethod.name().toLowerCase())) { List<String> opScopesDefault = new ArrayList<>(); List<String> opScopesDefaultInstance = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, operation); if (opScopesDefaultInstance != null) { opScopesDefault.addAll(opScopesDefaultInstance); } updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault); for (Map<String, List<String>> input : securityRequirements) { for (String scheme : schemes) { if (!OPENAPI_SECURITY_SCHEMA_KEY.equals(scheme)) { List<String> opScopesOthers = getScopeOfOperations(scheme, operation); if (opScopesOthers != null) { for (String scope : opScopesOthers) { if (!opScopesDefault.contains(scope)) { opScopesDefault.add(scope); } } } } updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault); } } securityRequirements.add(updatedDefaultSecurityRequirement); } operation.setSecurity(securityRequirements); entry.setValue(operation); operationsMap.put(httpMethod, operation); } paths.put(pathKey, pathItem); } openAPI.setPaths(paths); return openAPI; }