Java Code Examples for io.swagger.v3.oas.models.PathItem#HttpMethod
The following examples show how to use
io.swagger.v3.oas.models.PathItem#HttpMethod .
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: OpenApiOperationValidationsTest.java From openapi-generator with Apache License 2.0 | 6 votes |
@Test(dataProvider = "getOrHeadWithBodyExpectations") public void testGetOrHeadWithBodyWithDisabledRule(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) { RuleConfiguration config = new RuleConfiguration(); config.setEnableApiRequestUriWithBodyRecommendation(false); OpenApiOperationValidations validator = new OpenApiOperationValidations(config); Operation op = new Operation().operationId(operationId); RequestBody body = new RequestBody(); if (StringUtils.isNotEmpty(ref) || content != null) { body.$ref(ref); body.content(content); op.setRequestBody(body); } ValidationResult result = validator.validate(new OperationWrapper(null, op, method)); Assert.assertNotNull(result.getWarnings()); List<Invalid> warnings = result.getWarnings().stream() .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription())) .collect(Collectors.toList()); Assert.assertNotNull(warnings); Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation."); }
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: OpenAPI3RouterFactoryImpl.java From vertx-web with Apache License 2.0 | 6 votes |
public OpenAPI3RouterFactoryImpl(Vertx vertx, OpenAPI spec, ResolverCache refsCache) { super(vertx, spec); this.refsCache = refsCache; this.operations = new LinkedHashMap<>(); this.securityHandlers = new SecurityHandlersStore(); /* --- Initialization of all arrays and maps --- */ for (Map.Entry<String, ? extends PathItem> pathEntry : spec.getPaths().entrySet()) { for (Map.Entry<PathItem.HttpMethod, ? extends Operation> opEntry : pathEntry.getValue().readOperationsMap().entrySet()) { if (opEntry.getValue().getOperationId() != null) { this.operations.put(opEntry.getValue().getOperationId(), new OperationValue( HttpMethod.valueOf(opEntry.getKey().name()), pathEntry.getKey(), opEntry.getValue(), pathEntry.getValue() )); } else if (LOG.isWarnEnabled()) { LOG.warn("The operation '"+ opEntry.getKey() + "' from path '" + pathEntry.getKey()+"' is being ignored because it doesn't have an operationId"); } } } }
Example 4
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 5
Source File: SchemaGenerator.java From Poseidon with Apache License 2.0 | 6 votes |
private static PathItem.HttpMethod getHttpMethod(HttpMethod httpMethod) { switch (httpMethod) { case GET: return PathItem.HttpMethod.GET; case POST: return PathItem.HttpMethod.POST; case PUT: return PathItem.HttpMethod.PUT; case DELETE: return PathItem.HttpMethod.DELETE; case PATCH: return PathItem.HttpMethod.PATCH; case HEAD: return PathItem.HttpMethod.HEAD; case OPTIONS: return PathItem.HttpMethod.OPTIONS; case TRACE: return PathItem.HttpMethod.TRACE; default: throw new UnsupportedOperationException(); } }
Example 6
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 7
Source File: OpenApiOperationValidationsTest.java From openapi-generator with Apache License 2.0 | 5 votes |
@Test(dataProvider = "getOrHeadWithBodyExpectations") public void testGetOrHeadWithBody(PathItem.HttpMethod method, String operationId, String ref, Content content, boolean shouldTriggerFailure) { RuleConfiguration config = new RuleConfiguration(); config.setEnableRecommendations(true); OpenApiOperationValidations validator = new OpenApiOperationValidations(config); Operation op = new Operation().operationId(operationId); RequestBody body = new RequestBody(); if (StringUtils.isNotEmpty(ref) || content != null) { body.$ref(ref); body.content(content); op.setRequestBody(body); } ValidationResult result = validator.validate(new OperationWrapper(null, op, method)); Assert.assertNotNull(result.getWarnings()); List<Invalid> warnings = result.getWarnings().stream() .filter(invalid -> "API GET/HEAD defined with request body".equals(invalid.getRule().getDescription())) .collect(Collectors.toList()); Assert.assertNotNull(warnings); if (shouldTriggerFailure) { Assert.assertEquals(warnings.size(), 1, "Expected warnings to include recommendation."); } else { Assert.assertEquals(warnings.size(), 0, "Expected warnings not to include recommendation."); } }
Example 8
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Remove MG related information * * @param openAPI OpenAPI */ private void removePublisherSpecificInfo(OpenAPI openAPI) { Map<String, Object> extensions = openAPI.getExtensions(); OASParserUtil.removePublisherSpecificInfo(extensions); for (String pathKey : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathKey); for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) { Operation operation = entry.getValue(); OASParserUtil.removePublisherSpecificInfofromOperation(operation.getExtensions()); } } }
Example 9
Source File: EndpointUtils.java From openapi-diff with Apache License 2.0 | 5 votes |
public static Collection<? extends Endpoint> convert2Endpoints( String pathUrl, Map<PathItem.HttpMethod, Operation> map) { List<Endpoint> endpoints = new ArrayList<Endpoint>(); if (null == map) return endpoints; for (Map.Entry<PathItem.HttpMethod, Operation> entry : map.entrySet()) { PathItem.HttpMethod httpMethod = entry.getKey(); Operation operation = entry.getValue(); Endpoint endpoint = convert2Endpoint(pathUrl, httpMethod, operation); endpoints.add(endpoint); } return endpoints; }
Example 10
Source File: EndpointUtils.java From openapi-diff with Apache License 2.0 | 5 votes |
public static Endpoint convert2Endpoint( String pathUrl, PathItem.HttpMethod httpMethod, Operation operation) { Endpoint endpoint = new Endpoint(); endpoint.setPathUrl(pathUrl); endpoint.setMethod(httpMethod); endpoint.setSummary(operation.getSummary()); endpoint.setOperation(operation); return endpoint; }
Example 11
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 12
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Update OAS operations for Store * * @param openAPI OpenAPI to be updated */ private void updateOperations(OpenAPI openAPI) { for (String pathKey : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathKey); for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getExtensions(); if (extensions != null) { // remove mediation extension if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) { extensions.remove(APIConstants.SWAGGER_X_MEDIATION_SCRIPT); } // set x-scope value to security definition if it not there. if (extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) { String scope = (String) extensions.get(APIConstants.SWAGGER_X_WSO2_SCOPES); 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 || !requirement .get(OPENAPI_SECURITY_SCHEMA_KEY).contains(scope)) { requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.singletonList(scope)); } } } } } } }
Example 13
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 14
Source File: DiffContext.java From openapi-diff with Apache License 2.0 | 4 votes |
public PathItem.HttpMethod getMethod() { return method; }
Example 15
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 * * @param resourceConfigsJSON swaggerJSON * @return URI Templates * @throws APIManagementException */ @Override public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException { OpenAPI openAPI = getOpenAPI(resourceConfigsJSON); Set<URITemplate> urlTemplates = new LinkedHashSet<>(); Set<Scope> scopes = getScopes(resourceConfigsJSON); for (String pathKey : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathKey); for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) { Operation operation = entry.getValue(); URITemplate template = new URITemplate(); if (APIConstants.SUPPORTED_METHODS.contains(entry.getKey().name().toLowerCase())) { template.setHTTPVerb(entry.getKey().name().toUpperCase()); template.setHttpVerbs(entry.getKey().name().toUpperCase()); template.setUriTemplate(pathKey); List<String> opScopes = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, operation); if (!opScopes.isEmpty()) { if (opScopes.size() == 1) { String firstScope = opScopes.get(0); 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> extensios = operation.getExtensions(); if (extensios != null) { if (extensios.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) { String scopeKey = (String) extensios.get(APIConstants.SWAGGER_X_AUTH_TYPE); template.setAuthType(scopeKey); template.setAuthTypes(scopeKey); } else { template.setAuthType("Any"); template.setAuthTypes("Any"); } if (extensios.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) { String throttlingTier = (String) extensios.get(APIConstants.SWAGGER_X_THROTTLING_TIER); template.setThrottlingTier(throttlingTier); template.setThrottlingTiers(throttlingTier); } if (extensios.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) { String mediationScript = (String) extensios.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT); template.setMediationScript(mediationScript); template.setMediationScripts(template.getHTTPVerb(), mediationScript); } } urlTemplates.add(template); } } } return urlTemplates; }
Example 16
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * 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 17
Source File: DiffContext.java From openapi-diff with Apache License 2.0 | 4 votes |
private DiffContext setMethod(PathItem.HttpMethod method) { this.method = method; return this; }
Example 18
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; }
Example 19
Source File: OperationWrapper.java From openapi-generator with Apache License 2.0 | 2 votes |
/** * Gets the http method associated with the operation * * @return The http method */ public PathItem.HttpMethod getHttpMethod() { return httpMethod; }
Example 20
Source File: OperationWrapper.java From openapi-generator with Apache License 2.0 | 2 votes |
/** * Constructs a new instance of {@link OperationWrapper} * * @param operation The operation instances to wrap * @param httpMethod The http method to wrap */ OperationWrapper(OpenAPI specification, Operation operation, PathItem.HttpMethod httpMethod) { this.specification = specification; this.operation = operation; this.httpMethod = httpMethod; }