Java Code Examples for io.swagger.v3.oas.models.Operation#getParameters()
The following examples show how to use
io.swagger.v3.oas.models.Operation#getParameters() .
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: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testCookieExpandedObjectTestOnlyAdditionalPropertiesFailure() throws Exception { Operation op = testSpec.getPaths().get("/cookieTests/objectTests/onlyAdditionalProperties").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/cookieTests/objectTests/onlyAdditionalProperties", HttpMethod.GET, true, validationHandler, (routingContext) -> { routingContext.response().setStatusCode(200).setStatusMessage("OK").end(); } ); QueryStringEncoder params = new QueryStringEncoder("/"); params.addParam("param1", Integer.toString(5)); params.addParam("param2", "a"); params.addParam("wellKnownParam", "hello"); testRequestWithCookies(HttpMethod.GET, "/cookieTests/objectTests/onlyAdditionalProperties", params.toUri().getRawQuery(), 400, errorMessage(ValidationException.ErrorType.NO_MATCH)); }
Example 2
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testAdditionalPropertiesJson() throws Exception { Operation op = testSpec.getPaths().get("/additionalProperties") .getPost(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/additionalProperties", HttpMethod.POST, true, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); routingContext.response().setStatusCode(200) .setStatusMessage("OK") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .end(params.body().getJsonObject().encode()); }); JsonObject pet = new JsonObject(); pet.put("id", 14612); pet.put("name", "Willy"); pet.put("lazyness", "Highest"); testRequestWithJSON(HttpMethod.POST, "/additionalProperties", pet.toBuffer(), 400, errorMessage(ValidationException.ErrorType.JSON_INVALID)); }
Example 3
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testQueryParameterAnyOf() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/anyOfTest") .getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/anyOfTest", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); routingContext.response() .setStatusMessage(params.queryParameter("parameter") .getBoolean().toString()) .end(); }); testRequest(HttpMethod.GET, "/queryTests/anyOfTest?parameter=true", 200, "true"); }
Example 4
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testQueryExpandedObjectTestOnlyAdditionalProperties() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/objectTests/onlyAdditionalProperties").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/objectTests/onlyAdditionalProperties", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext.get("parsedParameters"); assertEquals("hello", params.queryParameter("wellKnownParam").getString()); RequestParameter param = params.queryParameter("params"); assertFalse(param.getObjectKeys().contains("wellKnownParam")); int res = param.getObjectValue("param2").getInteger() + param.getObjectValue("param1").getInteger(); routingContext.response().setStatusCode(200).setStatusMessage("Result: " + res).end(); } ); testRequest(HttpMethod.GET, "/queryTests/objectTests/onlyAdditionalProperties?param1=2¶m2=4&wellKnownParam=hello", 200, "Result: 6"); }
Example 5
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testAllowEmptyValueQueryParameter() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/defaultString") .getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/defaultString", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); routingContext .response().setStatusMessage(params .queryParameter("parameter").getString()) .end(); }); // Empty value should not be overwritten testRequest(HttpMethod.GET, "/queryTests/defaultString?parameter=", 200, ""); }
Example 6
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testDefaultStringQueryParameter() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/defaultString") .getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/defaultString", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); routingContext .response().setStatusMessage(params .queryParameter("parameter").getString()) .end(); }); testRequest(HttpMethod.GET, "/queryTests/defaultString", 200, "aString"); }
Example 7
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testQueryParameterArrayExploded() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/arrayTests/formExploded").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/arrayTests/formExploded", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext.get("parsedParameters"); List<String> result = new ArrayList<>(); for (RequestParameter r : params.queryParameter("parameter").getArray()) result.add(r.getInteger().toString()); routingContext.response().setStatusMessage(serializeInCSVStringArray(result)).end(); }); List<String> values = new ArrayList<>(); values.add("4"); values.add("2"); values.add("26"); StringBuilder stringBuilder = new StringBuilder(); for (String s : values) { stringBuilder.append("parameter=" + s + "&"); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); testRequest(HttpMethod.GET, "/queryTests/arrayTests/formExploded?" + stringBuilder, 200, serializeInCSVStringArray(values)); }
Example 8
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testPathParameterFailure() throws Exception { Operation op = testSpec.getPaths().get("/pets/{petId}").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/pets/:petId", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end()); testRequest(HttpMethod.GET, "/pets/three", 400, errorMessage(ValidationException.ErrorType.NO_MATCH)); }
Example 9
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testComplexMultipart() throws Exception { Operation op = testSpec.getPaths().get("/multipart/complex").getPost(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/multipart/complex", HttpMethod.POST, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext.get("parsedParameters"); assertNotNull(params.formParameter("param2").getJsonObject()); assertEquals("Willy", params.formParameter("param2").getJsonObject().getString("name")); assertEquals(4, params.formParameter("param4").getArray().size()); assertEquals((Integer)2, params.formParameter("param5").getInteger()); routingContext.response().setStatusMessage("ok").end(); }); JsonObject pet = new JsonObject(); pet.put("id", 14612); pet.put("name", "Willy"); List<String> valuesArray = new ArrayList<>(); for (int i = 0; i < 4; i++) valuesArray.add(getSuccessSample(ParameterType.FLOAT).getFloat().toString()); MultipartForm form = MultipartForm.create() .textFileUpload("param1", "random.txt", "src/test/resources/random.txt", "text/plain") .attribute("param2", pet.encode()) .textFileUpload("param3", "random.csv", "src/test/resources/random.txt", "text/csv") .attribute("param4", serializeInCSVStringArray(valuesArray)) .attribute("param5", "2") .binaryFileUpload("param1Binary", "random-file", "src/test/resources/random-file", "text/plain"); testRequestWithMultipartForm(HttpMethod.POST, "/multipart/complex", form, 200, "ok"); }
Example 10
Source File: PathsProcessor.java From swagger-parser with Apache License 2.0 | 5 votes |
private void addParametersToEachOperation(PathItem pathItem) { if (settings.addParametersToEachOperation()) { List<Parameter> parameters = pathItem.getParameters(); if (parameters != null) { // add parameters to each operation List<Operation> operations = pathItem.readOperations(); if (operations != null) { for (Operation operation : operations) { List<Parameter> parametersToAdd = new ArrayList<>(); List<Parameter> existingParameters = operation.getParameters(); if (existingParameters == null) { existingParameters = new ArrayList<>(); operation.setParameters(existingParameters); } for (Parameter parameterToAdd : parameters) { boolean matched = false; for (Parameter existingParameter : existingParameters) { if (parameterToAdd.getIn() != null && parameterToAdd.getIn().equals(existingParameter.getIn()) && parameterToAdd.getName().equals(existingParameter.getName())) { matched = true; } } if (!matched) { parametersToAdd.add(parameterToAdd); } } if (parametersToAdd.size() > 0) { operation.getParameters().addAll(0, parametersToAdd); } } } } // remove the shared parameters pathItem.setParameters(null); } }
Example 11
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testPathParameter() throws Exception { Operation op = testSpec.getPaths().get("/pets/{petId}").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/pets/:petId", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.pathParameter("petId").getInteger().toString()).end(); }); testRequest(HttpMethod.GET, "/pets/3", 200, "3"); }
Example 12
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testQueryExpandedObjectTestOnlyAdditionalPropertiesFailure() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/objectTests/onlyAdditionalProperties").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/objectTests/onlyAdditionalProperties", HttpMethod.GET, true, validationHandler, (routingContext) -> { routingContext.response().setStatusCode(200).setStatusMessage("OK").end(); } ); testRequest(HttpMethod.GET, "/queryTests/objectTests/onlyAdditionalProperties?param1=2¶m2=a&wellKnownParam=a", 400, errorMessage(ValidationException.ErrorType.NO_MATCH)); }
Example 13
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testPathParameterFailure() throws Exception { Operation op = testSpec.getPaths().get("/pets/{petId}").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/pets/:petId", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response() .setStatusMessage("ok").end()); testRequest(HttpMethod.GET, "/pets/three", 400, errorMessage(ValidationException.ErrorType.NO_MATCH)); }
Example 14
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testJsonBody() throws Exception { Operation op = testSpec.getPaths().get("/jsonBodyTest/sampleTest") .getPost(); if (op.getParameters() == null) op.setParameters(new ArrayList<>()); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/jsonBodyTest/sampleTest", HttpMethod.POST, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); routingContext.response().setStatusCode(200) .setStatusMessage("OK") .putHeader("Content-Type", "application/json") .end(params.body().getJsonObject().encode()); }); JsonObject object = new JsonObject(); object.put("id", "anId"); List<Integer> valuesArray = new ArrayList<>(); for (int i = 0; i < 4; i++) valuesArray.add(getSuccessSample(ParameterType.INT).getInteger()); object.put("values", valuesArray); testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest", object.toBuffer(), 200, "OK", object.toBuffer()); testRequestWithBufferResponse(HttpMethod.POST, "/jsonBodyTest/sampleTest", "application/json; charset=utf-8", object.toBuffer(), 200, "OK", "application/json", b -> assertEquals(object, b.toJsonObject())); testRequestWithBufferResponse(HttpMethod.POST, "/jsonBodyTest/sampleTest", "application/superapplication+json", object.toBuffer(), 200, "OK", "application/json", b -> assertEquals(object, b.toJsonObject())); }
Example 15
Source File: OpenAPI3MultipleFilesValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testFormArrayParameter() throws Exception { Operation op = testSpec.getPaths().get("/formTests/arraytest") .getPost(); if (op.getParameters() == null) op.setParameters(new ArrayList<>()); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl( op, op.getParameters(), testSpec, refsCache); loadHandlers("/formTests/arraytest", HttpMethod.POST, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext .get("parsedParameters"); List<String> result = new ArrayList<>(); for (RequestParameter r : params.formParameter("values") .getArray()) result.add(r.getInteger().toString()); routingContext.response() .setStatusMessage( params.formParameter("id").getString() + serializeInCSVStringArray(result)) .end(); }); String id = "anId"; List<String> valuesArray = new ArrayList<>(); for (int i = 0; i < 4; i++) valuesArray.add(getSuccessSample(ParameterType.INT).getInteger() .toString()); String values = serializeInCSVStringArray(valuesArray); MultiMap form = MultiMap.caseInsensitiveMultiMap(); form.add("id", id); form.add("values", values); testRequestWithForm(HttpMethod.POST, "/formTests/arraytest", FormType.FORM_URLENCODED, form, 200, id + values); }
Example 16
Source File: ResourceInterfaceGenerator.java From spring-openapi with MIT License | 5 votes |
private MethodSpec createMethod(OperationData operationData) { Operation operation = operationData.getOperation(); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getMethodName(operation)) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT); if (operation.getDescription() != null) { methodSpecBuilder.addJavadoc(operation.getDescription()); } if (operation.getParameters() != null) { operation.getParameters() .forEach(parameter -> methodSpecBuilder.addParameter( parseProperties(formatParameterName(parameter.getName()), parameter.getSchema()).build() )); } if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) { LinkedHashMap<String, MediaType> mediaTypes = operation.getRequestBody().getContent(); methodSpecBuilder.addParameter(parseProperties("requestBody", mediaTypes.entrySet().iterator().next().getValue().getSchema()).build()); } if (operation.getResponses() == null || CollectionUtils.isEmpty(operation.getResponses().entrySet())) { methodSpecBuilder.returns(TypeName.VOID); } else { ApiResponse apiResponse = operation.getResponses().entrySet().stream() .filter(responseEntry -> StringUtils.startsWith(responseEntry.getKey(), "2")) // HTTP 20x .findFirst() .map(Map.Entry::getValue) .orElse(null); if (apiResponse != null && apiResponse.getContent() != null && !apiResponse.getContent().isEmpty()) { MediaType mediaType = apiResponse.getContent().entrySet().iterator().next().getValue(); if (mediaType.getSchema() != null) { methodSpecBuilder.returns(determineTypeName(mediaType.getSchema())); return methodSpecBuilder.build(); } } methodSpecBuilder.returns(TypeName.VOID); } return methodSpecBuilder.build(); }
Example 17
Source File: OpenAPI3ValidationTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testQueryParameterByteFormat() throws Exception { Operation op = testSpec.getPaths().get("/queryTests/byteFormat").getGet(); OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache); loadHandlers("/queryTests/byteFormat", HttpMethod.GET, false, validationHandler, (routingContext) -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.queryParameter("parameter").getString()).end(); }); testRequest(HttpMethod.GET, "/queryTests/byteFormat?parameter=Zm9vYmFyCg==", 200, "Zm9vYmFyCg=="); }
Example 18
Source File: BallerinaOperation.java From product-microgateway with Apache License 2.0 | 4 votes |
@Override public BallerinaOperation buildContext(Operation operation, ExtendedAPI api) throws BallerinaServiceGenException, CLICompileTimeException { if (operation == null) { return getDefaultValue(); } // OperationId with spaces with special characters will cause errors in ballerina code. // Replacing it with uuid so that we can identify there was a ' ' when doing bal -> swagger operation.setOperationId(UUID.randomUUID().toString().replaceAll("-", "")); this.operationId = operation.getOperationId(); this.tags = operation.getTags(); this.summary = operation.getSummary(); this.description = operation.getDescription(); this.externalDocs = operation.getExternalDocs(); this.parameters = new ArrayList<>(); //to provide resource level security in dev-first approach ApplicationSecurity appSecurity = OpenAPICodegenUtils.populateApplicationSecurity(api.getName(), api.getVersion(), operation.getExtensions(), api.getMutualSSL()); this.authProviders = OpenAPICodegenUtils.getMgwResourceSecurity(operation, appSecurity); this.apiKeys = OpenAPICodegenUtils.generateAPIKeysFromSecurity(operation.getSecurity(), this.authProviders.contains(OpenAPIConstants.APISecurity.apikey.name())); ApplicationSecurity apiAppSecurity = api.getApplicationSecurity(); if (appSecurity != null && appSecurity.isOptional() != null) { // if app security is made optional at resource this.applicationSecurityOptional = appSecurity.isOptional(); } else if (apiAppSecurity != null && apiAppSecurity.isOptional() != null) { // if app security made optional at API level this.applicationSecurityOptional = apiAppSecurity.isOptional(); } //to set resource level scopes in dev-first approach this.scope = OpenAPICodegenUtils.getMgwResourceScope(operation); //set resource level endpoint configuration setEpConfigDTO(operation); Map<String, Object> exts = operation.getExtensions(); if (exts != null) { // set interceptor details Object reqExt = exts.get(OpenAPIConstants.REQUEST_INTERCEPTOR); Object resExt = exts.get(OpenAPIConstants.RESPONSE_INTERCEPTOR); if (reqExt != null) { reqInterceptorContext = new BallerinaInterceptor(reqExt.toString()); requestInterceptor = reqInterceptorContext.getInvokeStatement(); isJavaRequestInterceptor = BallerinaInterceptor.Type.JAVA == reqInterceptorContext.getType(); } if (resExt != null) { resInterceptorContext = new BallerinaInterceptor(resExt.toString()); responseInterceptor = resInterceptorContext.getInvokeStatement(); isJavaResponseInterceptor = BallerinaInterceptor.Type.JAVA == resInterceptorContext.getType(); } Optional<Object> scopes = Optional.ofNullable(exts.get(X_SCOPE)); scopes.ifPresent(value -> this.scope = "\"" + value.toString() + "\""); Optional<Object> authType = Optional.ofNullable(exts.get(X_AUTH_TYPE)); authType.ifPresent(value -> { if (AUTH_TYPE_NONE.equals(value)) { this.isSecured = false; } }); Optional<Object> resourceTier = Optional.ofNullable(exts.get(X_THROTTLING_TIER)); resourceTier.ifPresent(value -> this.resourceTier = value.toString()); //set dev-first resource level throttle policy if (this.resourceTier == null) { Optional<Object> extResourceTier = Optional.ofNullable(exts.get(OpenAPIConstants.THROTTLING_TIER)); extResourceTier.ifPresent(value -> this.resourceTier = value.toString()); } if (api.getApiLevelPolicy() != null && this.resourceTier != null) { //if api level policy exists then we are neglecting the resource level policies String message = "[WARN] : Resource level policy: " + this.resourceTier + " will be neglected due to the presence of API level policy: " + api.getApiLevelPolicy() + " for the API : " + api.getName() + "\n"; CmdUtils.appendMessagesToConsole(message); this.resourceTier = null; } Optional<Object> extDisableSecurity = Optional.ofNullable(exts.get(OpenAPIConstants.DISABLE_SECURITY)); extDisableSecurity.ifPresent(value -> { try { this.isSecured = !(Boolean) value; this.isSecuredAssignedFromOperation = true; } catch (ClassCastException e) { throw new CLIRuntimeException("The property '" + OpenAPIConstants.DISABLE_SECURITY + "' should be a boolean value. But provided '" + value.toString() + "'."); } }); } if (operation.getParameters() != null) { for (Parameter parameter : operation.getParameters()) { this.parameters.add(new BallerinaParameter().buildContext(parameter, api)); } } return this; }
Example 19
Source File: QuerydslPredicateOperationCustomizer.java From springdoc-openapi with Apache License 2.0 | 4 votes |
@Override public Operation customize(Operation operation, HandlerMethod handlerMethod) { if (operation.getParameters() == null) { return operation; } MethodParameter[] methodParameters = handlerMethod.getMethodParameters(); int parametersLength = methodParameters.length; List<Parameter> parametersToAddToOperation = new ArrayList<>(); for (int i = 0; i < parametersLength; i++) { MethodParameter parameter = methodParameters[i]; QuerydslPredicate predicate = parameter.getParameterAnnotation(QuerydslPredicate.class); if (predicate == null) { continue; } QuerydslBindings bindings = extractQdslBindings(predicate); Set<String> fieldsToAdd = Arrays.stream(predicate.root().getDeclaredFields()).map(Field::getName).collect(Collectors.toSet()); Map<String, Object> pathSpecMap = getPathSpec(bindings, "pathSpecs"); //remove blacklisted fields Set<String> blacklist = getFieldValues(bindings, "blackList"); fieldsToAdd.removeIf(blacklist::contains); Set<String> whiteList = getFieldValues(bindings, "whiteList"); Set<String> aliases = getFieldValues(bindings, "aliases"); fieldsToAdd.addAll(aliases); fieldsToAdd.addAll(whiteList); for (String fieldName : fieldsToAdd) { Type type = getFieldType(fieldName, pathSpecMap, predicate.root()); io.swagger.v3.oas.models.parameters.Parameter newParameter = buildParam(type, fieldName); parametersToAddToOperation.add(newParameter); } } operation.getParameters().addAll(parametersToAddToOperation); return operation; }
Example 20
Source File: OpenAPIV3ParserTest.java From swagger-parser with Apache License 2.0 | 4 votes |
private OpenAPI doRelativeFileTest(String location) { OpenAPIV3Parser parser = new OpenAPIV3Parser(); ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult readResult = parser.readLocation(location, null, options); if (readResult.getMessages().size() > 0) { Json.prettyPrint(readResult.getMessages()); } final OpenAPI openAPI = readResult.getOpenAPI(); final PathItem path = openAPI.getPaths().get("/health"); assertEquals(path.getClass(), PathItem.class); //we successfully converted the RefPath to a Path final List<Parameter> parameters = path.getParameters(); assertParamDetails(parameters, 0, QueryParameter.class, "param1", "query"); assertParamDetails(parameters, 1, HeaderParameter.class, "param2", "header"); final Operation operation = path.getGet(); final List<Parameter> operationParams = operation.getParameters(); assertParamDetails(operationParams, 0, PathParameter.class, "param3", "path"); assertParamDetails(operationParams, 1, HeaderParameter.class, "param4", "header"); final Map<String, ApiResponse> responsesMap = operation.getResponses(); assertResponse(openAPI, responsesMap, "200","application/json", "Health information from the server", "#/components/schemas/health"); assertResponse(openAPI, responsesMap, "400","*/*", "Your request was not valid", "#/components/schemas/error"); assertResponse(openAPI, responsesMap, "500","*/*", "An unexpected error occur during processing", "#/components/schemas/error"); final Map<String, Schema> definitions = openAPI.getComponents().getSchemas(); final Schema refInDefinitions = definitions.get("refInDefinitions"); assertEquals(refInDefinitions.getDescription(), "The example model"); expectedPropertiesInModel(refInDefinitions, "foo", "bar"); final ArraySchema arrayModel = (ArraySchema) definitions.get("arrayModel"); final Schema arrayModelItems = arrayModel.getItems(); assertEquals(arrayModelItems.get$ref(), "#/components/schemas/foo"); final Schema fooModel = definitions.get("foo"); assertEquals(fooModel.getDescription(), "Just another model"); expectedPropertiesInModel(fooModel, "hello", "world"); final ComposedSchema composedCat = (ComposedSchema) definitions.get("composedCat"); final Schema child = composedCat.getAllOf().get(2); expectedPropertiesInModel(child, "huntingSkill", "prop2", "reflexes", "reflexMap"); final ArraySchema reflexes = (ArraySchema) child.getProperties().get("reflexes"); final Schema reflexItems = reflexes.getItems(); assertEquals(reflexItems.get$ref(), "#/components/schemas/reflex"); assertTrue(definitions.containsKey(reflexItems.get$ref().substring(reflexItems.get$ref().lastIndexOf("/")+1))); final Schema reflexMap = (Schema) child.getProperties().get("reflexMap"); final Schema reflexMapAdditionalProperties = (Schema) reflexMap.getAdditionalProperties(); assertEquals(reflexMapAdditionalProperties.get$ref(), "#/components/schemas/reflex"); assertEquals(composedCat.getAllOf().size(), 3); assertEquals(composedCat.getAllOf().get(0).get$ref(), "#/components/schemas/pet"); assertEquals(composedCat.getAllOf().get(1).get$ref(), "#/components/schemas/foo_2"); return openAPI; }