io.swagger.v3.oas.models.Operation Java Examples

The following examples show how to use io.swagger.v3.oas.models.Operation. 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 vote down vote up
@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 #2
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllOfQueryParamWithDefault() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/allOfTest").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/allOfTest", HttpMethod.GET, false, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext.response().setStatusMessage(params.queryParameter("parameter").getObjectValue("a").getInteger()
      .toString() + params.queryParameter("parameter").getObjectValue("b").getBoolean().toString()).end();
  });

  String a = "5";
  String b = "";

  String parameter = "parameter=a," + a + ",b," + b;

  testRequest(HttpMethod.GET, "/queryTests/allOfTest?" + parameter, 200, a + "false");
}
 
Example #3
Source File: OpenApiOperationValidationsTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "OpenAPI v2 converter - Conversion param extensions should be preserved")
public void testIssue820() throws Exception {
    final OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_820_YAML);
    assertNotNull(oas);
    Operation post = oas.getPaths().get("/issue820").getPost();
    assertNotNull(post.getRequestBody().getContent().get("multipart/form-data"));
    assertNotNull(post.getRequestBody().getContent().get("multipart/form-data").getSchema());
    Map<String, Schema> properties = post.getRequestBody().getContent().get("multipart/form-data").getSchema().getProperties();
    assertNotNull(properties);
    assertEquals(properties.size(), 3, "size");
    Schema foo = properties.get("foo");
    assertNotNull(foo);
    assertNotNull(foo.getExtensions());
    assertEquals(foo.getExtensions().get("x-ext"), "some foo");
    assertEquals(foo.getNullable(), null);
    Schema bar = properties.get("bar");
    assertNotNull(bar);
    assertNotNull(bar.getExtensions());
    assertEquals(bar.getExtensions().get("x-ext"), "some bar");
    assertEquals(bar.getNullable(), Boolean.TRUE);
    Schema baz = properties.get("baz");
    assertNotNull(baz);
    assertNotNull(baz.getExtensions());
    assertEquals(baz.getExtensions().get("x-ext"), "some baz");
    assertEquals(baz.getNullable(), Boolean.FALSE);
}
 
Example #5
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: CppPistacheServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        ApiResponse apiResponse = findMethodResponse(operation.getResponses());

        if (apiResponse != null) {
            Schema response = ModelUtils.getSchemaFromResponse(apiResponse);
            if (response != null) {
                CodegenProperty cm = fromProperty("response", response);
                op.vendorExtensions.put("x-codegen-response", cm);
                if ("HttpContent".equals(cm.dataType)) {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1");
    op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);

    return op;
}
 
Example #7
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testExample1() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/examples.yaml");
    final DefaultCodegen codegen = new DefaultCodegen();

    Operation operation = openAPI.getPaths().get("/example1/singular").getGet();
    CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
    codegen.setParameterExampleValue(codegenParameter, operation.getParameters().get(0));

    Assert.assertEquals(codegenParameter.example, "example1 value");

    Operation operation2 = openAPI.getPaths().get("/example1/plural").getGet();
    CodegenParameter codegenParameter2 = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
    codegen.setParameterExampleValue(codegenParameter2, operation2.getParameters().get(0));

    Assert.assertEquals(codegenParameter2.example, "An example1 value");
}
 
Example #8
Source File: PathItemTransformer.java    From swagger-brake with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<PathDetail> transform(PathItem from) {
    Collection<PathDetail> result = new ArrayList<>();
    for (Map.Entry<HttpMethod, Function<PathItem, Operation>> e : MAPPERS.entrySet()) {
        Operation operation = e.getValue().apply(from);
        if (operation != null) {
            HttpMethod key = e.getKey();

            boolean isDeprecated = BooleanUtils.isTrue(operation.getDeprecated());
            boolean isBetaApi = getBetaApiValue(operation);
            Request requestBody = getRequestBody(operation);
            List<RequestParameter> requestParameters = getRequestParameters(operation);
            List<Response> responses = getResponses(operation);
            PathDetail detail = new PathDetail(key, requestBody, requestParameters, responses, isDeprecated, isBetaApi);
            result.add(detail);
        }
    }
    return result;
}
 
Example #9
Source File: PathItemOperationsValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testCodegenPetstore() {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    final OpenAPI openAPI = parser.read("src/test/resources/petstore-codegen.yaml");
    Schema enumModel =  openAPI.getComponents().getSchemas().get("Enum_Test");
    assertNotNull(enumModel);
    Schema enumProperty = (Schema)enumModel.getProperties().get("enum_integer");
    assertNotNull(enumProperty);

    assertTrue(enumProperty instanceof IntegerSchema);
    IntegerSchema enumIntegerProperty = (IntegerSchema) enumProperty;
    List<Number> integers =  enumIntegerProperty.getEnum();
    assertEquals(integers.get(0), new Integer(1));
    assertEquals(integers.get(1), new Integer(-1));

    Operation getOrderOperation = openAPI.getPaths().get("/store/order/{orderId}").getGet();
    assertNotNull(getOrderOperation);
    Parameter orderId = getOrderOperation.getParameters().get(0);
    assertTrue(orderId instanceof PathParameter);
    PathParameter orderIdPathParam = (PathParameter) orderId;
    assertNotNull(orderIdPathParam.getSchema().getMinimum());

    BigDecimal minimum = orderIdPathParam.getSchema().getMinimum();
    assertEquals(minimum.toString(), "1");
}
 
Example #11
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void exposeConfigurationTest() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false).setOperationModelKey("fooBarKey"));

      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        Operation operation = routingContext.get("fooBarKey");

        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("OK")
          .end(operation.getOperationId());
      });

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets", 200, "OK", "listPets");
}
 
Example #12
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testComposedSchemaMyPetsOneOfDiscriminatorMap() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml");

    DefaultCodegen codegen = new DefaultCodegen();
    codegen.setLegacyDiscriminatorBehavior(false);
    codegen.setOpenAPI(openAPI);

    String path = "/mypets";

    Operation operation = openAPI.getPaths().get(path).getGet();
    CodegenOperation codegenOperation = codegen.fromOperation(path, "GET", operation, null);
    verifyMyPetsDiscriminator(codegenOperation.discriminator);

    Schema pet = openAPI.getComponents().getSchemas().get("MyPets");
    CodegenModel petModel = codegen.fromModel("MyPets", pet);
    verifyMyPetsDiscriminator(petModel.discriminator);
}
 
Example #13
Source File: V2ConverterTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "Nice to have: Convert x-nullable to nullable")
public void testIssue35() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_35_JSON);
    Operation getOperation = oas.getPaths().get(FOO_PATH).getGet();
    assertNotNull(getOperation);
    List<Parameter> parameters = getOperation.getParameters();
    assertNotNull(parameters);
    assertEquals(parameters.get(0).getSchema().getNullable(), Boolean.TRUE);
    assertEquals(parameters.get(1).getSchema().getNullable(), Boolean.FALSE);
    assertEquals(parameters.get(2).getSchema().getNullable(), Boolean.TRUE);
    assertEquals(getOperation.getResponses().get("200").getContent().get("*/*").getSchema().getNullable(),
            Boolean.TRUE);
    Schema user = oas.getComponents().getSchemas().get(USER_MODEL);
    assertNotNull(user);
    assertEquals(user.getNullable(), Boolean.TRUE);
    assertEquals(((Schema) user.getProperties().get(ID)).getNullable(), Boolean.TRUE);
}
 
Example #14
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseWithNoSchemaInHeaders() {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    ApiResponse response2XX = new ApiResponse()
            .description("OK")
            .addHeaderObject("x-custom-header", new Header()
                    .description("a custom header")
                    .style(Header.StyleEnum.SIMPLE));
    Operation operation1 = new Operation().operationId("op1").responses(new ApiResponses().addApiResponse("2XX", response2XX));
    openAPI.path("/here", new PathItem().get(operation1));
    final DefaultCodegen codegen = new DefaultCodegen();
    codegen.setOpenAPI(openAPI);

    CodegenResponse cr = codegen.fromResponse("2XX", response2XX);
    Assert.assertNotNull(cr);
    Assert.assertTrue(cr.hasHeaders);
}
 
Example #15
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue853() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    final OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-837-853-1131/main.yaml", null, options).getOpenAPI();
    Assert.assertNotNull(openAPI);

    Operation post = openAPI.getPaths().get("/guests").getPost();
    Assert.assertNotNull(post);

    Content content = post.getResponses().get("201").getContent();
    Assert.assertNotNull(content);

    Map<String, Example> examples = content.get("application/json").getExamples();
    Assert.assertEquals(examples.size(), 1);
    assertNotNull(openAPI.getComponents());
    assertNotNull(openAPI.getComponents().getExamples());
    assertNotNull(openAPI.getComponents().getExamples().get("testExample"));
    assertEquals(((LinkedHashMap<String, Object>)openAPI.getComponents().getExamples().get("testExample").getValue()).get("test"),"value");
}
 
Example #16
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Fill parameters list.
 *
 * @param operation the operation
 * @param queryParams the query params
 * @param methodAttributes the method attributes
 */
private void fillParametersList(Operation operation, Map<String, String> queryParams, MethodAttributes methodAttributes) {
	List<Parameter> parametersList = operation.getParameters();
	if (parametersList == null)
		parametersList = new ArrayList<>();
	Collection<Parameter> headersMap = AbstractRequestBuilder.getHeaders(methodAttributes, new LinkedHashMap<>());
	parametersList.addAll(headersMap);
	if (!CollectionUtils.isEmpty(queryParams)) {
		for (Map.Entry<String, String> entry : queryParams.entrySet()) {
			io.swagger.v3.oas.models.parameters.Parameter parameter = new io.swagger.v3.oas.models.parameters.Parameter();
			parameter.setName(entry.getKey());
			parameter.setSchema(new StringSchema()._default(entry.getValue()));
			parameter.setRequired(true);
			parameter.setIn(ParameterIn.QUERY.toString());
			GenericParameterBuilder.mergeParameter(parametersList, parameter);
		}
		operation.setParameters(parametersList);
	}
}
 
Example #17
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultResponseShouldBeLast() {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    Operation myOperation = new Operation().operationId("myOperation").responses(
        new ApiResponses()
        .addApiResponse(
            "default", new ApiResponse().description("Default"))
        .addApiResponse(
            "422", new ApiResponse().description("Error"))
        );
    openAPI.path("/here", new PathItem().get(myOperation));
    final DefaultCodegen codegen = new DefaultCodegen();
    codegen.setOpenAPI(openAPI);

    CodegenOperation co = codegen.fromOperation("/here", "get", myOperation, null);
    Assert.assertEquals(co.responses.get(0).message, "Error");
    Assert.assertEquals(co.responses.get(1).message, "Default");
}
 
Example #18
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testArbitraryObjectResponseMapInline() {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema());

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .description("it works!")
                            .content(new Content().addMediaType("*/*", new MediaType().schema(schema)))))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertTrue(property.getAdditionalProperties() instanceof  Schema);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    Schema inlineProp = (Schema)property.getAdditionalProperties();
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example #19
Source File: JavascriptClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "test isDefualt in the response")
public void testResponseIsDefault() throws Exception {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/petstore.yaml");
    final DefaultCodegen codegen = new DefaultCodegen();
    codegen.setOpenAPI(openAPI);

    Operation textOperation = openAPI.getPaths().get("/user").getPost();
    CodegenOperation coText = codegen.fromOperation("/user", "post", textOperation, null);

    for (CodegenResponse cr : coText.responses) {
        Assert.assertTrue(cr.isDefault);
    }

    Assert.assertEquals(coText.responses.size(), 1);

}
 
Example #20
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Merge operation operation.
 *
 * @param operation the operation
 * @param operationModel the operation model
 * @return the operation
 */
public Operation mergeOperation(Operation operation, Operation operationModel) {
	if (operationModel.getOperationId().length() < operation.getOperationId().length()) {
		operation.setOperationId(operationModel.getOperationId());
	}

	ApiResponses apiResponses = operation.getResponses();
	for (Entry<String, ApiResponse> apiResponseEntry : operationModel.getResponses().entrySet()) {
		if (apiResponses.containsKey(apiResponseEntry.getKey())) {
			Content existingContent = apiResponses.get(apiResponseEntry.getKey()).getContent();
			Content newContent = apiResponseEntry.getValue().getContent();
			if (newContent != null)
				newContent.forEach((mediaTypeStr, mediaType) -> SpringDocAnnotationsUtils.mergeSchema(existingContent, mediaType.getSchema(), mediaTypeStr));
		}
		else
			apiResponses.addApiResponse(apiResponseEntry.getKey(), apiResponseEntry.getValue());
	}
	return operation;
}
 
Example #21
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayParam(@Injectable final List<AuthorizationValue> auths) throws IOException{
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    String pathFile = FileUtils.readFileToString(new File("./src/test/swagger/oas3.yaml"),"UTF-8");
    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);
    OpenAPI openAPI = result.getOpenAPI();

    new ExtensionsUtil().addExtensions(openAPI);

    Operation operation = openAPI.getPaths().get("/pet").getPost();
    RequestBody body = operation.getRequestBody();

    assertNotNull(body);
    Schema model = body.getContent().get("application/json").getSchema();
    assertEquals("object", model.getType());
}
 
Example #22
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve operation parameter remote refs")
public void testOperationParameterRemoteRefs() {
    final OpenAPI swagger = new OpenAPI();
    List<Parameter> parameters = new ArrayList<>();

    parameters.add(new Parameter().$ref("#/components/parameters/SampleParameter"));

    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(parameters)));

    swagger.components(new Components().addParameters("SampleParameter", new QueryParameter()
            .name("skip")
            .schema(new IntegerSchema())));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();

    final List<Parameter> params = swagger.getPaths().get("/fun").getGet().getParameters();
    assertEquals(params.size(), 1);
    final Parameter param = params.get(0);
    assertEquals(param.getName(), "skip");
}
 
Example #23
Source File: CallbackProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
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 #24
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullJson() throws Exception {
  Operation op = testSpec.getPaths().get("/pets").getPost();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/pets", 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());
  });

  // An empty body should be a non parsable json, not an empty object invalid
  testRequestWithJSON(HttpMethod.POST, "/pets", null, 400, errorMessage(ValidationException.ErrorType.JSON_INVALID));

  // An empty json object should be invalid, because some fields are required
  testRequestWithJSON(HttpMethod.POST, "/pets", new JsonObject().toBuffer(),400, errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #25
Source File: ReflectionUtilsTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetControllerNameWithMultipleTags() throws Exception {

    ReflectionUtils utils = new ReflectionUtils();
    utils.setConfiguration( Configuration.defaultConfiguration());

    ReflectionUtils.ClassNameValidator verifier = mock(ReflectionUtils.ClassNameValidator.class);
    utils.setClassNameValidator( verifier );

    Configuration configuration = utils.getConfiguration();
    when( verifier.isValidClassname( configuration.getControllerPackage() + ".Two")).thenReturn( true );

    Operation operation = new Operation().tags(Lists.newArrayList("one", " two "));
    String controllerName = utils.getControllerName(operation);
    assertEquals(controllerName, "io.swagger.oas.sample.controllers.Two");

    when( verifier.isValidClassname( configuration.getControllerPackage() + ".Two")).thenReturn( false );
    when( verifier.isValidClassname( configuration.getControllerPackage() + ".OneController")).thenReturn( true );

    operation = new Operation().tags(Lists.newArrayList("one", " two "));
    controllerName = utils.getControllerName(operation);
    assertEquals(controllerName, "io.swagger.oas.sample.controllers.OneController");

    when( verifier.isValidClassname( configuration.getControllerPackage() + ".OneController")).thenReturn( false );

    operation = new Operation().tags(Lists.newArrayList("one", " two "));
    controllerName = utils.getControllerName(operation);
    assertEquals(controllerName, "io.swagger.oas.sample.controllers.Default");
}
 
Example #26
Source File: SerializableParamExtractionTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void getMethodGenerationNameTest() throws Exception {
    Operation operation = new Operation();
    String methodName = utils.getMethodName("/foo/bar", "GET", operation);

    assertEquals(methodName, "fooBarGET");
}
 
Example #27
Source File: ReflectionUtilsTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOperationNameWithSpace() throws Exception {
    Operation operation = new Operation()
      .addTagsItem("my tag");

    String controllerName = utils.getControllerName(operation);
    assertEquals(controllerName, "io.swagger.oas.sample.controllers.My_tag");
}
 
Example #28
Source File: AbstractOperation.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
void addFilters(MetaResource metaResource, Operation operation) {
  // TODO: Pull these out into re-usable parameter groups when https://github.com/OAI/OpenAPI-Specification/issues/445 lands
  List<Parameter> parameters = operation.getParameters();
  parameters.add(new NestedFilter().$ref());

  // Add filter[<>] parameters
  // Only the most basic filters are documented
  OASUtils.filterAttributes(metaResource, true)
      .forEach(e -> parameters.add(new FieldFilter(metaResource, e).parameter()));
}
 
Example #29
Source File: HeadersGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void generateCustomHeader(Operation operation, List<HttpHeaderField> headers) {
    if (operation.getParameters() != null) {
        for (Parameter parameter : operation.getParameters()) {
            if (parameter == null) {
                continue;
            }
            if (HEADER.equals(parameter.getIn())) {
                String name = parameter.getName();
                String value = dataGenerator.generate(name, parameter);
                HttpHeaderField header = new HttpHeaderField(name, value);
                headers.add(header);
            }
        }
    }
}
 
Example #30
Source File: AbstractOpenApiResource.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets existing operation.
 *
 * @param operationMap the operation map
 * @param requestMethod the request method
 * @return the existing operation
 */
private Operation getExistingOperation(Map<HttpMethod, Operation> operationMap, RequestMethod requestMethod) {
	Operation existingOperation = null;
	if (!CollectionUtils.isEmpty(operationMap)) {
		// Get existing operation definition
		switch (requestMethod) {
			case GET:
				existingOperation = operationMap.get(HttpMethod.GET);
				break;
			case POST:
				existingOperation = operationMap.get(HttpMethod.POST);
				break;
			case PUT:
				existingOperation = operationMap.get(HttpMethod.PUT);
				break;
			case DELETE:
				existingOperation = operationMap.get(HttpMethod.DELETE);
				break;
			case PATCH:
				existingOperation = operationMap.get(HttpMethod.PATCH);
				break;
			case HEAD:
				existingOperation = operationMap.get(HttpMethod.HEAD);
				break;
			case OPTIONS:
				existingOperation = operationMap.get(HttpMethod.OPTIONS);
				break;
			default:
				// Do nothing here
				break;
		}
	}
	return existingOperation;
}