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

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponse. 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: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue1177(@Injectable final List<AuthorizationValue> auths) {
    String path = "/issue-1177/swagger.yaml";

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation(path, auths, options).getOpenAPI();

    // $ref response with $ref header
    ApiResponse petsListApiResponse = openAPI.getPaths().get("/update-pets").getPost().getResponses().get("200");
    assertNotNull(petsListApiResponse);

    Header sessionIdHeader = petsListApiResponse.getHeaders().get("x-session-id");
    assertNotNull(sessionIdHeader);

    Schema petsListSchema = openAPI.getComponents().getSchemas().get("PetsList");
    assertNotNull(petsListSchema);

    assertNotNull(openAPI.getComponents().getHeaders());
    Header sessionIdHeaderComponent = openAPI.getComponents().getHeaders().get("x-session-id");
    assertTrue(sessionIdHeader == sessionIdHeaderComponent);

    assertTrue(petsListApiResponse.getContent().get("application/json").getSchema() == petsListSchema);
}
 
Example #3
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlinedArrayExample() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/array-example.yaml");

    ApiResponse response = openAPI.getPaths().get("/").getGet().getResponses().get("200");
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas());

    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "[ {\n" +
            "  \"id\" : 1,\n" +
            "  \"name\" : \"Arthur Dent\"\n" +
            "}, {\n" +
            "  \"id\" : 2,\n" +
            "  \"name\" : \"Ford Prefect\"\n" +
            "} ]");
}
 
Example #4
Source File: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
private void processProduces() {

    if (getProduces() == null) {
      return;
    }

    List<String> produceList = Arrays.stream(produces).filter(s -> !StringUtils.isEmpty(s))
        .collect(Collectors.toList());

    if (!produceList.isEmpty()) {
      ApiResponse apiResponse = new ApiResponse();
      Content content = new Content();
      MediaType mediaType = new MediaType();
      Schema schema = ModelConverter
          .getSchema(getMethod().getReturnType(), getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(schema);
      for (String produce : produceList) {
        content.addMediaType(produce, mediaType);
      }
      apiResponse.description("OK");
      apiResponse.setContent(content);
      addResponse(HttpStatuses.OK, apiResponse);
    }
  }
 
Example #5
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 #6
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdjacentComposedSchema(@Injectable List<AuthorizationValue> auth){

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oneOf-anyOf.yaml", auth, options);


    ApiResponse responseAdjacent = openAPI.getPaths().get("/adjacent").getGet().getResponses().get("200");
    Example exampleAdjacent = ExampleBuilder.fromSchema(responseAdjacent.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ);
    String outputAdjacent = Json.pretty(exampleAdjacent);
    assertEqualsIgnoreLineEnding(outputAdjacent, "[ {\n" +
            "  \"title\" : \"The Hitchhiker's Guide to the Galaxy\",\n" +
            "  \"authors\" : [ \"Douglas Adams\" ],\n" +
            "  \"isbn\" : \"0-330-25864-8\"\n" +
            "}, {\n" +
            "  \"title\" : \"Blade Runner\",\n" +
            "  \"directors\" : [ \"Ridley Scott\" ],\n" +
            "  \"year\" : 1982\n" +
            "} ]");

}
 
Example #7
Source File: PathsProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
protected void updateLocalRefs(ApiResponse response, String pathRef) {
    if (response.get$ref() != null){
        if(isLocalRef(response.get$ref())) {
            response.set$ref(computeLocalRef(response.get$ref(), pathRef));
        }
    }
    if(response.getContent() != null) {
        Map<String, MediaType> content = response.getContent();
        for (String key: content.keySet()) {
            MediaType mediaType = content.get(key);
            if (mediaType.getSchema() != null) {
                updateLocalRefs(mediaType.getSchema(), pathRef);
            }
            Map<String, Example> examples = content.get(key).getExamples();
            if (examples != null) {
                for( Example example:examples.values()){
                    updateLocalRefs(example, pathRef);
                }
            }
        }
    }
}
 
Example #8
Source File: CppRestSdkClientCodegen.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 methodResponse = findMethodResponse(operation.getResponses());

        if (methodResponse != null) {
            Schema response = ModelUtils.getSchemaFromResponse(methodResponse);
            response = ModelUtils.unaliasSchema(this.openAPI, response, importMapping);
            if (response != null) {
                CodegenProperty cm = fromProperty("response", response);
                op.vendorExtensions.put("x-codegen-response", cm);
                if ("std::shared_ptr<HttpContent>".equals(cm.dataType)) {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    return op;
}
 
Example #9
Source File: ResponseComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public StructuralNode apply(StructuralNode serverSection, Parameters params) {
    Map<String, ApiResponse> apiResponses = params.apiResponses;

    if (null == apiResponses || apiResponses.isEmpty()) return serverSection;

    TableImpl pathResponsesTable = new TableImpl(serverSection, new HashMap<>(), new ArrayList<>());
    pathResponsesTable.setOption("header");
    pathResponsesTable.setAttribute("caption", "", true);
    pathResponsesTable.setAttribute("cols", ".^2a,.^14a,.^4a", true);
    pathResponsesTable.setTitle(labels.getLabel(TABLE_TITLE_RESPONSES));
    pathResponsesTable.setHeaderRow(
            labels.getLabel(TABLE_HEADER_HTTP_CODE),
            labels.getLabel(TABLE_HEADER_DESCRIPTION),
            labels.getLabel(TABLE_HEADER_LINKS));

    apiResponses.forEach((httpCode, apiResponse) ->
            pathResponsesTable.addRow(
                    generateInnerDoc(pathResponsesTable, httpCode),
                    getResponseDescriptionColumnDocument(pathResponsesTable, apiResponse),
                    linkComponent.apply(pathResponsesTable, apiResponse.getLinks())
            ));
    serverSection.append(pathResponsesTable);
    return serverSection;
}
 
Example #10
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectsWithAnonymousObjectArrays() throws Exception {

    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/issue-171.yaml");

    ApiResponse response = openAPI.getPaths().get("/test").getGet().getResponses().get( "200" );
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), openAPI.getComponents().getSchemas());

    String output = Json.pretty(example);

    assertEqualsIgnoreLineEnding(output, "[ {\n" +
            "  \"id\" : \"string\",\n" +
            "  \"nestedArray\" : [ {\n" +
            "    \"id\" : \"string\",\n" +
            "    \"name\" : \"string\"\n" +
            "  } ]\n" +
            "} ]");


    response = openAPI.getPaths().get("/anothertest").getGet().getResponses().get( "200" );
    example = ExampleBuilder.fromSchema(response.getContent().get("*/*").getSchema(), openAPI.getComponents().getSchemas());

    output = new XmlExampleSerializer().serialize(example);
    assertEquals( output, "<?xml version='1.1' encoding='UTF-8'?><string>string</string>");
}
 
Example #11
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 #12
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the variable definition(s) for headers in the given response.
 */
private Optional<IVarDef> responseHeadersVar( OpenAPI api, String status, ApiResponse response)
  {
  return
    resultFor( "headers",
      () -> {
      List<String> headerNames =
        Optional.ofNullable( response.getHeaders())
        .map( headers -> headers.keySet().stream().filter( name -> !name.equals( "Content-Type")).collect( toList()))
        .orElse( emptyList());

      return
        Optional.ofNullable( headerNames.isEmpty()? null : headerNames)
        .map( names -> {
          return
            VarSetBuilder.with( "Headers")
            .members(
              names.stream()
              .map( name -> responseHeaderVar( api, status, name, resolveHeader( api, response.getHeaders().get( name)))))
            .build();
          });
      });
  }
 
Example #13
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 #14
Source File: AbstractAdaCodegen.java    From openapi-generator with Apache License 2.0 5 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 methodResponse = findMethodResponse(operation.getResponses());
        if (methodResponse != null && ModelUtils.getSchemaFromResponse(methodResponse) != null) {
            CodegenProperty cm = fromProperty("response", ModelUtils.getSchemaFromResponse(methodResponse));
            op.vendorExtensions.put("x-codegen-response", cm);
            if ("HttpContent".equals(cm.dataType)) {
                op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
            }
        }
    }

    // Add a vendor extension attribute that provides a map of auth methods and the scopes
    // which are expected by the operation.  This map is then used by postProcessOperationsWithModels
    // to build another vendor extension that provides a subset of the auth methods with only
    // the scopes required by the operation.
    final List<SecurityRequirement> securities = operation.getSecurity();
    if (securities != null && securities.size() > 0) {
        final Map<String, SecurityScheme> securitySchemes = this.openAPI.getComponents() != null ? this.openAPI.getComponents().getSecuritySchemes() : null;
        final List<SecurityRequirement> globalSecurities = this.openAPI.getSecurity();

        Map<String, List<String>> scopes = getAuthScopes(securities, securitySchemes);
        if (scopes.isEmpty() && globalSecurities != null) {
            scopes = getAuthScopes(globalSecurities, securitySchemes);
        }
        op.vendorExtensions.put("x-scopes", scopes);
    }
    return op;
}
 
Example #15
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static ApiResponse getApiResponse(OpenAPI openAPI, String name) {
    if (name == null) {
        return null;
    }

    if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getResponses() != null) {
        return openAPI.getComponents().getResponses().get(name);
    }
    return null;
}
 
Example #16
Source File: JavaClientCodegenTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReferencedHeader() {
    final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue855.yaml");
    JavaClientCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);

    ApiResponse ok_200 = openAPI.getComponents().getResponses().get("OK_200");
    CodegenResponse response = codegen.fromResponse("200", ok_200);

    Assert.assertEquals(1, response.headers.size());
    CodegenProperty header = response.headers.get(0);
    Assert.assertEquals("UUID", header.dataType);
    Assert.assertEquals("Request", header.baseName);
}
 
Example #17
Source File: JavaModelTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test(description = "convert an array schema in a RequestBody")
public void arraySchemaTestInRequestBody() {
    final Schema testSchema = new ArraySchema()
            .items(new Schema<>().$ref("#/components/schemas/Pet"));
    Operation operation = new Operation()
            .requestBody(new RequestBody()
                    .content(new Content().addMediaType("application/json",
                            new MediaType().schema(testSchema))))
            .responses(
                    new ApiResponses().addApiResponse("204", new ApiResponse()
                            .description("Ok response")));
    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.bodyParams.size(), 1);
    CodegenParameter cp1 = co.bodyParams.get(0);
    Assert.assertEquals(cp1.baseType, "Pet");
    Assert.assertEquals(cp1.dataType, "List<Pet>");
    Assert.assertTrue(cp1.isContainer);
    Assert.assertTrue(cp1.isListContainer);
    Assert.assertFalse(cp1.isMapContainer);
    Assert.assertEquals(cp1.items.baseType, "Pet");
    Assert.assertEquals(cp1.items.complexType, "Pet");
    Assert.assertEquals(cp1.items.dataType, "Pet");

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

    Assert.assertTrue(co.imports.contains("List"));
    Assert.assertTrue(co.imports.contains("Pet"));
}
 
Example #18
Source File: ModelUtilsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReferencedApiResponse() {
    ApiResponse otherApiResponse = new ApiResponse().description("Some Description");

    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.getComponents().addResponses("OtherApiResponse", otherApiResponse);

    ApiResponse notExistingApiResponse = new ApiResponse().$ref("NotExisting");
    ApiResponse result1 = ModelUtils.getReferencedApiResponse(openAPI, notExistingApiResponse);
    Assert.assertEquals(result1, notExistingApiResponse);

    ApiResponse result2 = ModelUtils.getReferencedApiResponse(openAPI, new ApiResponse().$ref("#/components/responses/OtherApiResponse"));
    Assert.assertEquals(result2, otherApiResponse);
}
 
Example #19
Source File: OpenApiUtils.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given response is defined by a reference, returns the referenced response. Otherwise, returns the given response.
 */
public static ApiResponse resolveResponse( OpenAPI api, ApiResponse response)
  {
  return
    Optional.ofNullable( response.get$ref())
    .map( ref -> componentResponseRef( api, ref))
    .orElse( response);
  }
 
Example #20
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new operation object using the URI template object
 *
 * @param resource API resource data
 * @return a new operation object using the URI template object
 */
private Operation createOperation(SwaggerData.Resource resource) {
    Operation operation = new Operation();
    populatePathParameters(operation, resource.getPath());
    updateOperationManagedInfo(resource, operation);

    ApiResponses apiResponses = new ApiResponses();
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.description("OK");
    apiResponses.addApiResponse(APIConstants.SWAGGER_RESPONSE_200, apiResponse);
    operation.setResponses(apiResponses);
    return operation;
}
 
Example #21
Source File: DefaultGeneratorTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessPaths() 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")))));
    openAPI.getPaths().addPathItem("/path3", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op3").addParametersItem(new QueryParameter().name("p2").schema(new IntegerSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
    openAPI.getPaths().addPathItem("/path4", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op4").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));

    ClientOptInput opts = new ClientOptInput();
    opts.setOpenAPI(openAPI);
    opts.setConfig(new DefaultCodegen());

    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(), 4);
    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);
    Assert.assertEquals(defaultList.get(2).path, "/path3");
    Assert.assertEquals(defaultList.get(2).allParams.size(), 2);
    Assert.assertEquals(defaultList.get(3).path, "/path4");
    Assert.assertEquals(defaultList.get(3).allParams.size(), 1);
}
 
Example #22
Source File: DataRestResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Add response.
 *
 * @param requestMethod the request method
 * @param operationPath the operation path
 * @param apiResponses the api responses
 * @param apiResponse the api response
 */
private void addResponse(RequestMethod requestMethod, String operationPath, ApiResponses apiResponses, ApiResponse apiResponse) {
	switch (requestMethod) {
		case GET:
			addResponse200(apiResponses, apiResponse);
			if (operationPath.contains("/{id}"))
				addResponse404(apiResponses);
			break;
		case POST:
			apiResponses.put(String.valueOf(HttpStatus.CREATED.value()), apiResponse.description(HttpStatus.CREATED.getReasonPhrase()));
			break;
		case DELETE:
			addResponse204(apiResponses);
			addResponse404(apiResponses);
			break;
		case PUT:
			addResponse200(apiResponses, apiResponse);
			apiResponses.put(String.valueOf(HttpStatus.CREATED.value()), new ApiResponse().content(apiResponse.getContent()).description(HttpStatus.CREATED.getReasonPhrase()));
			addResponse204(apiResponses);
			break;
		case PATCH:
			addResponse200(apiResponses, apiResponse);
			addResponse204(apiResponses);
			break;
		default:
			throw new IllegalArgumentException(requestMethod.name());
	}
}
 
Example #23
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1261InlineSchemaExample() throws Exception {
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/issue-1261.yaml");

    ApiResponse response = openAPI.getPaths().get("/user").getGet().getResponses().get("200");
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(), null);

    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "{\n" +
            "  \"id\" : 42,\n" +
            "  \"name\" : \"Arthur Dent\"\n" +
            "}");
}
 
Example #24
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 #25
Source File: ResolverCacheTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadInternalResponseRefWithSpaces(@Injectable ApiResponse mockedResponse) throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.components(new Components().addResponses("foo bar", mockedResponse));

    ResolverCache cache = new ResolverCache(openAPI, auths, null);
    ApiResponse actualResult = cache.loadRef("#/components/responses/foo bar", RefFormat.INTERNAL, ApiResponse.class);
    assertEquals(actualResult, mockedResponse);
}
 
Example #26
Source File: MethodAttributes.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate generic map response api responses.
 *
 * @param genericMapResponse the generic map response
 * @return the api responses
 */
public ApiResponses calculateGenericMapResponse(Map<String, ApiResponse> genericMapResponse) {
	ApiResponses apiResponses = new ApiResponses();
	genericMapResponse.forEach(apiResponses::addApiResponse);
	this.genericMapResponse = genericMapResponse;
	return apiResponses;
}
 
Example #27
Source File: ResourceReferenceResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceReferenceResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceReferenceResponseSchema",
      schema.get$ref()
  );
}
 
Example #28
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets generic map response.
 *
 * @param beanType the bean type
 * @return the generic map response
 */
private Map<String, ApiResponse> getGenericMapResponse(Class<?> beanType) {
	return controllerAdviceInfos.stream()
			.filter(controllerAdviceInfo -> new ControllerAdviceBean(controllerAdviceInfo.getControllerAdvice()).isApplicableToBeanType(beanType))
			.map(ControllerAdviceInfo::getApiResponseMap)
			.collect(LinkedHashMap::new, Map::putAll, Map::putAll);
}
 
Example #29
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveComposedOneOfRefSchema(@Injectable List<AuthorizationValue> auth){

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oneOf-anyOf.yaml", auth, options);

    ApiResponse response = openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200");
    Example example = ExampleBuilder.fromSchema(response.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ);
    String output = Json.pretty(example);
    assertEqualsIgnoreLineEnding(output, "{\n" +
            "  \"title\" : \"The Hitchhiker's Guide to the Galaxy\",\n" +
            "  \"authors\" : [ \"Douglas Adams\" ],\n" +
            "  \"isbn\" : \"0-330-25864-8\"\n" +
            "}");

    ApiResponse responseAnyOf = openAPI.getPaths().get("/anyOf").getGet().getResponses().get("200");
    Example exampleAnyOf = ExampleBuilder.fromSchema(responseAnyOf.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ);
    String outputAnyOf = Json.pretty(exampleAnyOf);
    assertEqualsIgnoreLineEnding(outputAnyOf, "{\n" +
            "  \"title\" : \"Blade Runner\",\n" +
            "  \"directors\" : [ \"Ridley Scott\" ],\n" +
            "  \"year\" : 1982\n" +
            "}");

}
 
Example #30
Source File: ResourceResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourceResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourceResponseSchema",
      schema.get$ref()
  );
}