io.swagger.v3.oas.models.responses.ApiResponses Java Examples

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponses. 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: SerializerUtilsTest.java    From openapi-generator with Apache License 2.0 7 votes vote down vote up
private OpenAPI createCompleteExample() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setInfo(new Info().title("Some title").description("Some description"));
    openAPI.setExternalDocs(new ExternalDocumentation().url("http://abcdef.com").description("a-description"));
    openAPI.setServers(Arrays.asList(
            new Server().url("http://www.server1.com").description("first server"),
            new Server().url("http://www.server2.com").description("second server")
        ));
    openAPI.setSecurity(Arrays.asList(
            new SecurityRequirement().addList("some_auth", Arrays.asList("write", "read"))
        ));
    openAPI.setTags(Arrays.asList(
            new Tag().name("tag1").description("some 1 description"),
            new Tag().name("tag2").description("some 2 description"),
            new Tag().name("tag3").description("some 3 description")
        ));
    openAPI.path("/ping/pong", new PathItem().get(new Operation()
            .description("Some description")
            .operationId("pingOp")
            .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("Ok")))));
    openAPI.components(new Components().addSchemas("SomeObject", new ObjectSchema().description("An Obj").addProperties("id", new StringSchema())));
    openAPI.setExtensions(new LinkedHashMap<>()); // required because swagger-core is using HashMap instead of LinkedHashMap internally.
    openAPI.addExtension("x-custom", "value1");
    openAPI.addExtension("x-other", "value2");
    return openAPI;
}
 
Example #2
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsistentParameterNameAfterUniquenessRename() throws Exception {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    Operation operation = new Operation()
            .operationId("opId")
            .addParametersItem(new QueryParameter().name("myparam").schema(new StringSchema()))
            .addParametersItem(new QueryParameter().name("myparam").schema(new StringSchema()))
            .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("OK")));

    DefaultCodegen codegen = new DefaultCodegen();
    codegen.setOpenAPI(openAPI);
    CodegenOperation co = codegen.fromOperation("/some/path", "get", operation, null);
    Assert.assertEquals(co.path, "/some/path");
    Assert.assertEquals(co.allParams.size(), 2);
    List<String> allParamsNames = co.allParams.stream().map(p -> p.paramName).collect(Collectors.toList());
    Assert.assertTrue(allParamsNames.contains("myparam"));
    Assert.assertTrue(allParamsNames.contains("myparam2"));
    List<String> queryParamsNames = co.queryParams.stream().map(p -> p.paramName).collect(Collectors.toList());
    Assert.assertTrue(queryParamsNames.contains("myparam"));
    Assert.assertTrue(queryParamsNames.contains("myparam2"));
}
 
Example #3
Source File: ApiResponseDiff.java    From openapi-diff with Apache License 2.0 6 votes vote down vote up
public Optional<ChangedApiResponse> diff(
    ApiResponses left, ApiResponses right, DiffContext context) {
  MapKeyDiff<String, ApiResponse> responseMapKeyDiff = MapKeyDiff.diff(left, right);
  List<String> sharedResponseCodes = responseMapKeyDiff.getSharedKey();
  Map<String, ChangedResponse> resps = new LinkedHashMap<>();
  for (String responseCode : sharedResponseCodes) {
    openApiDiff
        .getResponseDiff()
        .diff(left.get(responseCode), right.get(responseCode), context)
        .ifPresent(changedResponse -> resps.put(responseCode, changedResponse));
  }
  ChangedApiResponse changedApiResponse =
      new ChangedApiResponse(left, right, context)
          .setIncreased(responseMapKeyDiff.getIncreased())
          .setMissing(responseMapKeyDiff.getMissing())
          .setChanged(resps);
  openApiDiff
      .getExtensionsDiff()
      .diff(left.getExtensions(), right.getExtensions(), context)
      .ifPresent(changedApiResponse::setExtensions);
  return isChanged(changedApiResponse);
}
 
Example #4
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the value definitions for the response status code variable.
 */
private Stream<VarValueDef> responseStatusValues( ApiResponses responses)
  {
  List<String> statusCodes =
    responses.keySet().stream()
    .filter( status -> !status.equals( "default"))
    .collect( toList());
  
  return
    Stream.concat(
      // One for each specified status code...
      statusCodes.stream()
      .map( status -> VarValueDefBuilder.with( status).properties( statusCodeProperty( status)).build()),

      // And one for any unspecified status code...
      Stream.of( VarValueDefBuilder.with( "Other").has( "excluded", statusCodes.stream()).properties( statusCodeProperty( "Other")).build()));
  }
 
Example #5
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the variable definitions for the given response definitions.
 */
private Stream<IVarDef> responseVars( OpenAPI api, ApiResponses responses)
  {
  return
    responses.keySet().stream()
    .map( status -> {
      return
        resultFor( status,
          () ->  {
          ApiResponse response = resolveResponse( api, responses.get( status));
          String statusValueName = status.equals( "default")? "Other" : status;
          return
            VarSetBuilder.with( statusValueName)
            .when( has( statusCodeProperty( statusValueName)))
            .type( "response")
            .members( iterableOf( responseHeadersVar( api, status, response)))
            .members( responseContentVar( api, status, response))
            .build();
          });
      });
  }
 
Example #6
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert an array schema in an ApiResponse")
public void arraySchemaTestInOperationResponse() {
    final Schema testSchema = new ArraySchema()
                    .items(new Schema<>().$ref("#/components/schemas/Pet"));
    Operation operation = new Operation().responses(
            new ApiResponses().addApiResponse("200", new ApiResponse()
                    .description("Ok response")
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(testSchema)))));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Pet", new ObjectSchema().addProperties("name", new StringSchema()));
    final DefaultCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, null);

    Assert.assertEquals(co.responses.size(), 1);
    CodegenResponse cr = co.responses.get(0);
    Assert.assertEquals(cr.baseType, "Pet");
    Assert.assertEquals(cr.dataType, "List<Pet>");
    Assert.assertEquals(cr.containerType, "array");

    Assert.assertTrue(co.imports.contains("Pet"));
}
 
Example #7
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert an array schema in an ApiResponse")
public void arrayOfArraySchemaTestInOperationResponse() {
    final Schema testSchema = new ArraySchema()
            .items(new ArraySchema()
                    .items(new Schema<>().$ref("#/components/schemas/Pet")));
    Operation operation = new Operation().responses(
            new ApiResponses().addApiResponse("200", new ApiResponse()
                    .description("Ok response")
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(testSchema)))));
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Pet", new ObjectSchema().addProperties("name", new StringSchema()));
    final DefaultCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenOperation co = codegen.fromOperation("testSchema", "GET", operation, null);

    Assert.assertEquals(co.responses.size(), 1);
    CodegenResponse cr = co.responses.get(0);
    Assert.assertEquals(cr.baseType, "Pet");
    Assert.assertEquals(cr.dataType, "List<List<Pet>>");
    Assert.assertEquals(cr.containerType, "array");

    Assert.assertTrue(co.imports.contains("Pet"));
}
 
Example #8
Source File: DefaultCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasBodyParameter() {
    final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");
    Operation pingOperation = new Operation()
            .responses(
                    new ApiResponses().addApiResponse("204", new ApiResponse()
                            .description("Ok response")));
    Operation createOperation = new Operation()
            .requestBody(new RequestBody()
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(refSchema))))
            .responses(
                    new ApiResponses().addApiResponse("201", new ApiResponse()
                            .description("Created response")));
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());
    openAPI.getComponents().addSchemas("Pet", new ObjectSchema());

    final DefaultCodegen codegen = new DefaultCodegen();

    Assert.assertEquals(codegen.hasBodyParameter(openAPI, pingOperation), false);
    Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true);
}
 
Example #9
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 #10
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 #11
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve array response remote refs in yaml")
public void testYamlArrayResponseRemoteRefs() {
    final OpenAPI swagger = new OpenAPI();
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .content(new Content().addMediaType("*/*",new MediaType().schema(
                                    new ArraySchema().items(
                                            new Schema().$ref(replacePort(REMOTE_REF_YAML))))))))));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final ApiResponse response = swagger.getPaths().get("/fun").getGet().getResponses().get("200");
    final ArraySchema array = (ArraySchema) response.getContent().get("*/*").getSchema();
    assertNotNull(array.getItems());

    assertEquals(array.getItems().get$ref(), "#/components/schemas/Tag");
    assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
}
 
Example #12
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 #13
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve top-level parameters")
public void testSharedSwaggerParametersTest() {
    final OpenAPI swagger = new OpenAPI();
    List<Parameter> parameters = new ArrayList<>();
    parameters.add(0,new Parameter().$ref("username"));
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(parameters)
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("ok!")))));

    swagger.components(new Components().addParameters("username", new QueryParameter()
            .name("username")
            .schema(new StringSchema())));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    assertTrue(resolved.getComponents().getParameters().size() == 1);
    assertTrue(resolved.getPaths().get("/fun").getGet().getParameters().size() == 1);
}
 
Example #14
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test(description = "resolve top-level responses")
public void testSharedResponses() {
    final OpenAPI swagger = new OpenAPI();
    List<Parameter> parameters = new ArrayList<>();
    parameters.add(0,new Parameter().$ref("username"));
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .parameters(parameters)
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse().$ref("#/components/responses/foo")))));

    swagger.components(new Components().addResponses("foo", new ApiResponse().description("ok!")));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    ApiResponse response = resolved.getPaths().get("/fun").getGet().getResponses().get("200");
    assertTrue(response.getDescription().equals("ok!"));
    assertTrue(response instanceof ApiResponse);
}
 
Example #15
Source File: ResponsesResponsesValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  ApiResponses oasObject) {

  List<OasViolation> violations = new ArrayList<>();

  for (Map.Entry<String, ApiResponse> entry : oasObject.entrySet()) {
    String statusCode = entry.getKey();
    ApiResponse response = entry.getValue();
    OasObjectPropertyLocation responseLoc = location.property(statusCode, OasObjectType.RESPONSE);
    violations.addAll(OasObjectValidatorUtils.doValidateProperty(context, responseLoc, response, responseValidators));
  }

  return violations;

}
 
Example #16
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 #17
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonStrictProcessPaths() throws Exception {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.getPaths().addPathItem("path1/", new PathItem().get(new Operation().operationId("op1").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("path2/", new PathItem().get(new Operation().operationId("op2").addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));

    ClientOptInput opts = new ClientOptInput();
    opts.setOpenAPI(openAPI);
    CodegenConfig config = new DefaultCodegen();
    config.setStrictSpecBehavior(false);
    opts.setConfig(config);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(opts);
    Map<String, List<CodegenOperation>> result = generator.processPaths(openAPI.getPaths());
    Assert.assertEquals(result.size(), 1);
    List<CodegenOperation> defaultList = result.get("Default");
    Assert.assertEquals(defaultList.size(), 2);
    Assert.assertEquals(defaultList.get(0).path, "path1/");
    Assert.assertEquals(defaultList.get(0).allParams.size(), 0);
    Assert.assertEquals(defaultList.get(1).path, "path2/");
    Assert.assertEquals(defaultList.get(1).allParams.size(), 1);
}
 
Example #18
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Map<String, PathItem> createPathItems(String endpointName,
        ClassOrInterfaceDeclaration typeDeclaration) {
    Map<String, PathItem> newPathItems = new HashMap<>();
    for (MethodDeclaration methodDeclaration : typeDeclaration
            .getMethods()) {
        if (isAccessForbidden(typeDeclaration, methodDeclaration)) {
            continue;
        }
        String methodName = methodDeclaration.getNameAsString();

        Operation post = createPostOperation(methodDeclaration);
        if (methodDeclaration.getParameters().isNonEmpty()) {
            post.setRequestBody(createRequestBody(methodDeclaration));
        }

        ApiResponses responses = createApiResponses(methodDeclaration);
        post.setResponses(responses);
        post.tags(Collections
                .singletonList(typeDeclaration.getNameAsString()));
        PathItem pathItem = new PathItem().post(post);

        String pathName = "/" + endpointName + "/" + methodName;
        pathItem.readOperationsMap()
                .forEach((httpMethod, operation) -> operation
                        .setOperationId(String.join("_", endpointName,
                                methodName, httpMethod.name())));
        newPathItems.put(pathName, pathItem);
    }
    return newPathItems;
}
 
Example #19
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void setRefOfApiResponseHeaders(ApiResponses responses, SwaggerUpdateContext context) {
    if (responses != null) {
        for (ApiResponse response : responses.values()) {
            Map<String, Header> headers = response.getHeaders();

            if (headers != null) {
                for (Header header : headers.values()) {
                    Content content = header.getContent();

                    extractReferenceFromContent(content, context);
                }
            }
        }
    }
}
 
Example #20
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineMapResponseWithObjectSchema() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema()
            .addProperties("name", new StringSchema()));
    schema.addExtension("x-ext", "ext-prop");

    ApiResponse apiResponse = new ApiResponse()
            .description("it works!")
            .content(new Content().addMediaType("*/*",new MediaType().schema(schema)));
    apiResponse.addExtension("x-foo", "bar");

    ApiResponses apiResponses = new ApiResponses().addApiResponse("200",apiResponse);

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(apiResponses)));

    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);
    assertEquals(1, property.getExtensions().size());
    assertEquals("ext-prop", property.getExtensions().get("x-ext"));
    assertTrue(openAPI.getComponents().getSchemas().size() == 1);

    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_map200");
    assertTrue(inline instanceof Schema);
    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example #21
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test(description = "resolve shared path parameters")
public void testSharedPathParametersTest() {
    final OpenAPI swagger = new OpenAPI();
    Operation operation = new Operation()
            .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("ok!")));
    PathItem path = new PathItem().get(operation);
    path.addParametersItem(new QueryParameter()
            .name("username")
            .schema(new StringSchema()));
    swagger.path("/fun", path);

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    assertNull(resolved.getPaths().get("/fun").getParameters());
    assertTrue(resolved.getPaths().get("/fun").getGet().getParameters().size() == 1);
}
 
Example #22
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void testResponseRemoteRefs(String remoteRef) {
    final OpenAPI swagger = new OpenAPI();
    swagger.path("/fun", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse( "200", new ApiResponse()
                            .content(new Content().addMediaType("*/*",new MediaType().schema(new Schema().$ref(remoteRef))))))));

    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final ApiResponse response = swagger.getPaths().get("/fun").getGet().getResponses().get("200");
    final Schema ref = response.getContent().get("*/*").getSchema();
    assertEquals(ref.get$ref(), "#/components/schemas/Tag");
    assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
}
 
Example #23
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayResponse() {
    OpenAPI openAPI = new OpenAPI();


    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.addProperties("name", new StringSchema());
    ArraySchema schema = new ArraySchema();
    schema.setItems(objectSchema);

    ApiResponse apiResponse = new ApiResponse();
    apiResponse.addExtension("x-foo", "bar");
    apiResponse.setDescription("it works!");
    apiResponse.setContent(new Content().addMediaType("*/*", new MediaType().schema(schema)));

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", apiResponse))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    assertTrue(response.getContent().get("*/*").getSchema() instanceof ArraySchema);

    ArraySchema am = (ArraySchema) response.getContent().get("*/*").getSchema();
    Schema items = am.getItems();
    assertTrue(items.get$ref() != null);

    assertEquals(items.get$ref(), "#/components/schemas/inline_response_200");


    Schema inline = openAPI.getComponents().getSchemas().get("inline_response_200");
    assertTrue(inline instanceof Schema);

    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example #24
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void setRefOfApiResponses(ApiResponses responses, SwaggerUpdateContext context) {
    if (responses != null) {
        for (ApiResponse response : responses.values()) {
            Content content = response.getContent();

            extractReferenceFromContent(content, context);
        }
    }
}
 
Example #25
Source File: ChangedApiResponse.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public ChangedApiResponse(
    ApiResponses oldApiResponses, ApiResponses newApiResponses, DiffContext context) {
  this.oldApiResponses = oldApiResponses;
  this.newApiResponses = newApiResponses;
  this.context = context;
  this.missing = new LinkedHashMap<>();
  this.increased = new LinkedHashMap<>();
  this.changed = new LinkedHashMap<>();
}
 
Example #26
Source File: OpenAPIGeneratorTestBase.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private static void assertOperationResponseCodes(Operation operation, List<String> codes) {
  // Some operations will be null in cases where a JsonApiResource has postable, patchable,
  // readable, deleteable set to false. In that case, do not perform any response checks
  if(operation == null) { return; }

  ApiResponses responses = operation.getResponses();
  for (String code : codes) {
    Assert.assertTrue("Operation missing response code " + code, responses.containsKey(code));
  }
}
 
Example #27
Source File: Reader.java    From proteus with Apache License 2.0 5 votes vote down vote up
public Operation parseMethod(
								Method method,
								List<Parameter> globalParameters,
								Produces methodProduces,
								Produces classProduces,
								Consumes methodConsumes,
								Consumes classConsumes,
								List<SecurityRequirement> classSecurityRequirements,
								Optional<io.swagger.v3.oas.models.ExternalDocumentation> classExternalDocs,
								Set<String> classTags,
								List<io.swagger.v3.oas.models.servers.Server> classServers,
								boolean isSubresource,
								RequestBody parentRequestBody,
								ApiResponses parentResponses,
								JsonView jsonViewAnnotation,
								io.swagger.v3.oas.annotations.responses.ApiResponse[] classResponses)
{
	JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass());
	return parseMethod(
						classType.getClass(),
						method,
						globalParameters,
						methodProduces,
						classProduces,
						methodConsumes,
						classConsumes,
						classSecurityRequirements,
						classExternalDocs,
						classTags,
						classServers,
						isSubresource,
						parentRequestBody,
						parentResponses,
						jsonViewAnnotation,
						classResponses);
}
 
Example #28
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Add openAPI path item to the the openAPI object.
 *
 * @param path            name of the pathItem
 * @param scopes          array of operation scopes
 * @param throttlingTier throttling tier
 */
void addOpenAPIPath(String path, String[] scopes, String throttlingTier) {
    PathItem pathItem = new PathItem();
    Operation operation = new Operation();
    operation.setOperationId(UUID.randomUUID().toString());
    addOauth2SecurityRequirement(operation, scopes);
    if (StringUtils.isNotEmpty(throttlingTier)) {
        operation.addExtension(OpenAPIConstants.THROTTLING_TIER, throttlingTier);
    }
    //needs to add the basic Auth Requirement to the operation level because if scopes are mentioned,
    // there would be oauth2 security requirement in method level.
    if (isBasicAuthEnabled) {
        addBasicAuthSecurityRequirement(operation);
    }
    if (isAPIKeyEnabled) {
        addAPIKeySecurityRequirement(operation);
    }
    //For each path, the only available http method is "post" according to the grpc mapping.
    pathItem.setPost(operation);
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    //as Responses object is mandatory
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.setDescription(ProtoToOpenAPIConstants.RESPONSE_DESCRIPTION);
    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse(ProtoToOpenAPIConstants.SUCCESS_RESPONSE_CODE, apiResponse);
    operation.setResponses(apiResponses);
    //append forward slash to preserve openAPI syntax
    openAPI.getPaths().addPathItem(ProtoToOpenAPIConstants.PATH_SEPARATOR + path, pathItem);
}
 
Example #29
Source File: TypeScriptAngularClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testOperationIdParser() {
    OpenAPI openAPI = TestUtils.createOpenAPI();
    Operation operation1 = new Operation().operationId("123_test_@#$%_special_tags").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")));
    openAPI.path("another-fake/dummy/", new PathItem().get(operation1));
    final TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();
    codegen.setOpenAPI(openAPI);

    CodegenOperation co1 = codegen.fromOperation("/another-fake/dummy/", "get", operation1, null);
    org.testng.Assert.assertEquals(co1.operationId, "_123testSpecialTags");

}
 
Example #30
Source File: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
public void correctResponse(ApiResponses apiResponses) {

    if (apiResponses == null) {
      return;
    }

    // no annotations are processed
    // generate a default response based on the method return value
    if (apiResponses.get(HttpStatuses.OK) == null) {
      ApiResponse apiResponse = new ApiResponse();

      Class<?> returnType = method.getReturnType();
      if (returnType == Void.TYPE || returnType == Void.class) {
        return;
      }

      MediaType mediaType = new MediaType();

      Schema refSchema = ModelConverter.getSchema(returnType, getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(refSchema);

      Content content = new Content();
      content.addMediaType(MediaTypes.APPLICATION_JSON, mediaType);
      apiResponse.description("OK");
      apiResponse.setContent(content);
      apiResponses.addApiResponse(HttpStatuses.OK, apiResponse);
    }
  }