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

The following examples show how to use io.swagger.v3.oas.models.Components. 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: OpenAPIBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Add security scheme.
 *
 * @param apiSecurityScheme the api security scheme
 * @param components the components
 */
private void addSecurityScheme(Set<io.swagger.v3.oas.annotations.security.SecurityScheme> apiSecurityScheme,
		Components components) {
	for (io.swagger.v3.oas.annotations.security.SecurityScheme securitySchemeAnnotation : apiSecurityScheme) {
		Optional<SecuritySchemePair> securityScheme = securityParser.getSecurityScheme(securitySchemeAnnotation);
		if (securityScheme.isPresent()) {
			Map<String, SecurityScheme> securitySchemeMap = new HashMap<>();
			if (StringUtils.isNotBlank(securityScheme.get().getKey())) {
				securitySchemeMap.put(securityScheme.get().getKey(), securityScheme.get().getSecurityScheme());
				if (!CollectionUtils.isEmpty(components.getSecuritySchemes())) {
					components.getSecuritySchemes().putAll(securitySchemeMap);
				}
				else {
					components.setSecuritySchemes(securitySchemeMap);
				}
			}
		}
	}
}
 
Example #2
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 #3
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 #4
Source File: OpenAPIParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue768() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIParser().readLocation("issue768-main.yaml", null, options);
    assertNotNull(result);

    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);

    Components components = openAPI.getComponents();
    assertNotNull(components);

    Map<String, Schema> schemas = components.getSchemas();
    assertNotNull(schemas);

    assertEquals(schemas.size(), 1);
}
 
Example #5
Source File: GenericParameterBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate schema schema.
 *
 * @param components the components
 * @param parameterInfo the parameter info
 * @param requestBodyInfo the request body info
 * @param jsonView the json view
 * @return the schema
 */
Schema calculateSchema(Components components, ParameterInfo parameterInfo, RequestBodyInfo requestBodyInfo, JsonView jsonView) {
	Schema schemaN;
	String paramName = parameterInfo.getpName();
	MethodParameter methodParameter = parameterInfo.getMethodParameter();

	if (parameterInfo.getParameterModel() == null || parameterInfo.getParameterModel().getSchema() == null) {
		Type type = ReturnTypeParser.getType(methodParameter);
		schemaN = SpringDocAnnotationsUtils.extractSchema(components, type, jsonView, methodParameter.getParameterAnnotations());
	}
	else
		schemaN = parameterInfo.getParameterModel().getSchema();

	if (requestBodyInfo != null) {
		schemaN = calculateRequestBodySchema(components, parameterInfo, requestBodyInfo, schemaN, paramName);
	}

	return schemaN;
}
 
Example #6
Source File: SecurityRequirementsDiff.java    From openapi-diff with Apache License 2.0 6 votes vote down vote up
private List<Pair<SecurityScheme.Type, SecurityScheme.In>> getListOfSecuritySchemes(
    Components components, SecurityRequirement securityRequirement) {
  return securityRequirement
      .keySet()
      .stream()
      .map(
          x -> {
            SecurityScheme result = components.getSecuritySchemes().get(x);
            if (result == null) {
              throw new IllegalArgumentException("Impossible to find security scheme: " + x);
            }
            return result;
          })
      .map(this::getPair)
      .distinct()
      .collect(Collectors.toList());
}
 
Example #7
Source File: JavaInheritanceTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a composed model with parent")
public void javaInheritanceTest() {
    final Schema parentModel = new Schema().name("Base");

    final Schema schema = new ComposedSchema()
            .addAllOfItem(new Schema().$ref("Base"))
            .name("composed");

    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.setComponents(new Components()
            .addSchemas(parentModel.getName(),parentModel)
            .addSchemas(schema.getName(), schema)
    );

    final JavaClientCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", schema);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.parent, "Base");
    Assert.assertEquals(cm.imports, Sets.newHashSet("Base"));
}
 
Example #8
Source File: ArraySchemaDiffResult.java    From openapi-diff with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Schema<X>, X> Optional<ChangedSchema> diff(
    HashSet<String> refSet,
    Components leftComponents,
    Components rightComponents,
    T left,
    T right,
    DiffContext context) {
  ArraySchema leftArraySchema = (ArraySchema) left;
  ArraySchema rightArraySchema = (ArraySchema) right;
  super.diff(refSet, leftComponents, rightComponents, left, right, context);
  openApiDiff
      .getSchemaDiff()
      .diff(
          refSet,
          leftArraySchema.getItems(),
          rightArraySchema.getItems(),
          context.copyWithRequired(true))
      .ifPresent(changedSchema::setItems);
  return isApplicable(context);
}
 
Example #9
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private OpenAPI createBasicModel() {
    OpenAPI openAPI = new OpenAPI();

    Info info = new Info();
    info.setTitle(configuration.getApplicationTitle());
    info.setVersion(configuration.getApplicationApiVersion());
    openAPI.setInfo(info);

    Paths paths = new Paths();
    openAPI.setPaths(paths);

    Server server = new Server();
    server.setUrl(configuration.getServerUrl());
    server.setDescription(configuration.getServerDescription());
    openAPI.setServers(Collections.singletonList(server));
    Components components = new Components();
    SecurityScheme vaadinConnectOAuth2Scheme = new SecurityScheme()
            .type(SecurityScheme.Type.OAUTH2)
            .flows(new OAuthFlows().password(new OAuthFlow()
                    .tokenUrl(VAADIN_CONNECT_OAUTH2_TOKEN_URL)
                    .scopes(new Scopes())));
    components.addSecuritySchemes(VAADIN_CONNECT_OAUTH2_SECURITY_SCHEME,
            vaadinConnectOAuth2Scheme);
    openAPI.components(components);
    return openAPI;
}
 
Example #10
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseExternalSchemaModelHavingReferenceToItsLocalModel() {
    // given
    String location = "src/test/resources/issue-1040/api.yaml";
    OpenAPIV3Parser tested = new OpenAPIV3Parser();

    // when
    OpenAPI result = tested.read(location);

    // then
    Components components = result.getComponents();
    Schema modelSchema = components.getSchemas().get("Value");

    assertThat(modelSchema, notNullValue());
    assertThat(modelSchema.getProperties().get("id"), instanceOf(Schema.class));
    assertThat(((Schema) modelSchema.getProperties().get("id")).get$ref(), equalTo("#/components/schemas/ValueId"));
}
 
Example #11
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Gets media type.
 *
 * @param schema the schema
 * @param components the components
 * @param jsonViewAnnotation the json view annotation
 * @param annotationContent the annotation content
 * @return the media type
 */
private static MediaType getMediaType(Schema schema, Components components, JsonView jsonViewAnnotation,
		io.swagger.v3.oas.annotations.media.Content annotationContent) {
	MediaType mediaType = new MediaType();
	if (!annotationContent.schema().hidden()) {
		if (components != null) {
			try {
				getSchema(annotationContent, components, jsonViewAnnotation).ifPresent(mediaType::setSchema);
			}
			catch (Exception e) {
				if (isArray(annotationContent))
					mediaType.setSchema(new ArraySchema().items(new StringSchema()));
				else
					mediaType.setSchema(new StringSchema());
			}
		}
		else {
			mediaType.setSchema(schema);
		}
	}
	return mediaType;
}
 
Example #12
Source File: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Build param parameter.
 *
 * @param parameterInfo the parameter info
 * @param components the components
 * @param requestInfo the request info
 * @param jsonView the json view
 * @return the parameter
 */
private Parameter buildParam(ParameterInfo parameterInfo, Components components, RequestInfo requestInfo,
		JsonView jsonView) {
	Parameter parameter;
	String pName = parameterInfo.getpName();
	String name = StringUtils.isBlank(requestInfo.value()) ? pName : requestInfo.value();
	parameterInfo.setpName(name);

	if (!ValueConstants.DEFAULT_NONE.equals(requestInfo.defaultValue()))
		parameter = this.buildParam(requestInfo.type(), components, parameterInfo, false,
				requestInfo.defaultValue(), jsonView);
	else
		parameter = this.buildParam(requestInfo.type(), components, parameterInfo, requestInfo.required(), null,
				jsonView);
	return parameter;
}
 
Example #13
Source File: GenericParameterBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate request body schema schema.
 *
 * @param components the components
 * @param parameterInfo the parameter info
 * @param requestBodyInfo the request body info
 * @param schemaN the schema n
 * @param paramName the param name
 * @return the schema
 */
private Schema calculateRequestBodySchema(Components components, ParameterInfo parameterInfo, RequestBodyInfo requestBodyInfo, Schema schemaN, String paramName) {
	if (schemaN != null && StringUtils.isEmpty(schemaN.getDescription()) && parameterInfo.getParameterModel() != null) {
		String description = parameterInfo.getParameterModel().getDescription();
		if (schemaN.get$ref() != null && schemaN.get$ref().contains(AnnotationsUtils.COMPONENTS_REF)) {
			String key = schemaN.get$ref().substring(21);
			Schema existingSchema = components.getSchemas().get(key);
			existingSchema.setDescription(description);
		}
		else
			schemaN.setDescription(description);
	}

	if (requestBodyInfo.getMergedSchema() != null) {
		requestBodyInfo.getMergedSchema().addProperties(paramName, schemaN);
		schemaN = requestBodyInfo.getMergedSchema();
	}
	else if (schemaN instanceof FileSchema || schemaN instanceof ArraySchema && ((ArraySchema) schemaN).getItems() instanceof FileSchema) {
		schemaN = new ObjectSchema().addProperties(paramName, schemaN);
		requestBodyInfo.setMergedSchema(schemaN);
	}
	else
		requestBodyInfo.addProperties(paramName, schemaN);
	return schemaN;
}
 
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 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 #15
Source File: SchemaDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
protected static Schema resolveComposedSchema(Components components, Schema schema) {
  if (schema instanceof ComposedSchema) {
    ComposedSchema composedSchema = (ComposedSchema) schema;
    List<Schema> allOfSchemaList = composedSchema.getAllOf();
    if (allOfSchemaList != null) {
      for (Schema allOfSchema : allOfSchemaList) {
        allOfSchema = refPointer.resolveRef(components, allOfSchema, allOfSchema.get$ref());
        allOfSchema = resolveComposedSchema(components, allOfSchema);
        schema = addSchema(schema, allOfSchema);
      }
      composedSchema.setAllOf(null);
    }
  }
  return schema;
}
 
Example #16
Source File: ResolverCacheTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadInternalParameterRef(@Injectable Parameter mockedParameter) throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.components(new Components().addParameters("foo", mockedParameter));

    ResolverCache cache = new ResolverCache(openAPI, auths, null);
    Parameter actualResult = cache.loadRef("#/components/parameters/foo", RefFormat.INTERNAL, Parameter.class);
    assertEquals(actualResult, mockedParameter);

    assertNull(cache.loadRef("#/components/parameters/bar", RefFormat.INTERNAL, Parameter.class));
    assertNull(cache.loadRef("#/params/foo", RefFormat.INTERNAL, Parameter.class));
}
 
Example #17
Source File: ResolverCacheTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadInternalResponseRef(@Injectable ApiResponse mockedResponse) throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.components(new Components().addResponses("foo", mockedResponse));

    ResolverCache cache = new ResolverCache(openAPI, auths, null);
    ApiResponse actualResult = cache.loadRef("#/components/responses/foo", RefFormat.INTERNAL, ApiResponse.class);
    assertEquals(actualResult, mockedResponse);

    assertNull(cache.loadRef("#/components/responses/bar", RefFormat.INTERNAL, ApiResponse.class));
}
 
Example #18
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void testArrayRemoteModelProperty(String remoteRef) {

        final OpenAPI swagger = new OpenAPI();
        swagger.components(new Components().addSchemas("Sample", new Schema()
                .addProperties("remoteRef", new ArraySchema().items(new Schema().$ref(remoteRef)))));

        final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
        final Schema prop = (Schema) resolved.getComponents().getSchemas().get("Sample").getProperties().get("remoteRef");
        assertTrue(prop instanceof ArraySchema);
        final ArraySchema ap = (ArraySchema) prop;
        assertEquals(ap.getItems().get$ref(), "#/components/schemas/Tag");
        assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
    }
 
Example #19
Source File: PythonAbstractConnexionServerCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private void addSecurityExtensions(OpenAPI openAPI) {
    Components components = openAPI.getComponents();
    if (components != null && components.getSecuritySchemes() != null) {
        Map<String, SecurityScheme> securitySchemes = components.getSecuritySchemes();
        for (String securityName : securitySchemes.keySet()) {
            SecurityScheme securityScheme = securitySchemes.get(securityName);
            String baseFunctionName = controllerPackage + ".security_controller_.";
            switch (securityScheme.getType()) {
                case APIKEY:
                    addSecurityExtension(securityScheme, "x-apikeyInfoFunc", baseFunctionName + "info_from_" + securityName);
                    break;
                case HTTP:
                    if ("basic".equals(securityScheme.getScheme())) {
                        addSecurityExtension(securityScheme, "x-basicInfoFunc", baseFunctionName + "info_from_" + securityName);
                    } else if ("bearer".equals(securityScheme.getScheme())) {
                        addSecurityExtension(securityScheme, "x-bearerInfoFunc", baseFunctionName + "info_from_" + securityName);
                    }
                    break;
                case OPENIDCONNECT:
                    LOGGER.warn("Security type " + securityScheme.getType().toString() + " is not supported by connextion yet");
                case OAUTH2:
                    addSecurityExtension(securityScheme, "x-tokenInfoFunc", baseFunctionName + "info_from_" + securityName);
                    addSecurityExtension(securityScheme, "x-scopeValidateFunc", baseFunctionName + "validate_scope_" + securityName);
                    break;
                default:
                    LOGGER.warn("Unknown security type " + securityScheme.getType().toString());
            }
        }
    }
}
 
Example #20
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve schema from type schema.
 *
 * @param schemaImplementation the schema implementation
 * @param components the components
 * @param jsonView the json view
 * @param annotations the annotations
 * @return the schema
 */
public static Schema resolveSchemaFromType(Class<?> schemaImplementation, Components components,
		JsonView jsonView, Annotation[] annotations) {
	Schema schemaObject = extractSchema(components, schemaImplementation, jsonView, annotations);
	if (schemaObject != null && StringUtils.isBlank(schemaObject.get$ref())
			&& StringUtils.isBlank(schemaObject.getType()) && !(schemaObject instanceof ComposedSchema)) {
		// default to string
		schemaObject.setType("string");
	}
	return schemaObject;
}
 
Example #21
Source File: SpringDocAnnotationsUtils.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets content.
 *
 * @param annotationContents the annotation contents
 * @param classTypes the class types
 * @param methodTypes the method types
 * @param schema the schema
 * @param components the components
 * @param jsonViewAnnotation the json view annotation
 * @return the content
 */
public static Optional<Content> getContent(io.swagger.v3.oas.annotations.media.Content[] annotationContents,
		String[] classTypes, String[] methodTypes, Schema schema, Components components,
		JsonView jsonViewAnnotation) {
	if (ArrayUtils.isEmpty(annotationContents)) {
		return Optional.empty();
	}
	// Encapsulating Content model
	Content content = new Content();

	for (io.swagger.v3.oas.annotations.media.Content annotationContent : annotationContents) {
		MediaType mediaType = getMediaType(schema, components, jsonViewAnnotation, annotationContent);
		ExampleObject[] examples = annotationContent.examples();
		setExamples(mediaType, examples);
		addExtension(annotationContent, mediaType);
		io.swagger.v3.oas.annotations.media.Encoding[] encodings = annotationContent.encoding();
		addEncodingToMediaType(jsonViewAnnotation, mediaType, encodings);
		if (StringUtils.isNotBlank(annotationContent.mediaType())) {
			content.addMediaType(annotationContent.mediaType(), mediaType);
		}
		else {
			if (mediaType.getSchema() != null)
				applyTypes(classTypes, methodTypes, content, mediaType);
		}
	}

	if (content.size() == 0 && annotationContents.length != 1) {
		return Optional.empty();
	}
	return Optional.of(content);
}
 
Example #22
Source File: ResolverCacheTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadInternalParameterRefWithSpaces(@Injectable Parameter mockedParameter) throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.components(new Components().addParameters("foo bar", mockedParameter));

    ResolverCache cache = new ResolverCache(openAPI, auths, null);
    Parameter actualResult = cache.loadRef("#/components/parameters/foo bar", RefFormat.INTERNAL, Parameter.class);
    assertEquals(actualResult, mockedParameter);
}
 
Example #23
Source File: SpringDocTestApp.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI customOpenAPI() {
	return new OpenAPI()
			.components(new Components()
					.addSecuritySchemes("basicScheme",
							new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
					.addParameters("myHeader1",
							new Parameter().in("header").schema(new StringSchema()).name("myHeader1"))
					.addHeaders("myHeader2",
							new Header().description("myHeader2 header").schema(new StringSchema())))
			.info(new Info().title("Petstore API").version("v0").description(
					"This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.")
					.termsOfService("http://swagger.io/terms/")
					.license(new License().name("Apache 2.0").url("http://springdoc.org")));
}
 
Example #24
Source File: SpringDocApp68Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI customOpenAPI() {
	return new OpenAPI()
			.components(new Components().addSecuritySchemes("basicScheme",
					new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
			.info(new Info().title("Tweet API").version("v0")
					.license(new License().name("Apache 2.0").url("http://springdoc.org")));
}
 
Example #25
Source File: ParametersDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public static Optional<Parameter> contains(
    Components components, List<Parameter> parameters, Parameter parameter) {
  return parameters
      .stream()
      .filter(param -> same(refPointer.resolveRef(components, param, param.get$ref()), parameter))
      .findFirst();
}
 
Example #26
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineModelTestWithoutTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());


    Schema objectSchema = new ObjectSchema();
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");
    objectSchema.addProperties("street", new StringSchema());
    objectSchema.addProperties("city", new StringSchema());

    Schema schema =  new Schema();
    schema.setName("user");
    schema.setDescription("a common user");
    List<String> required = new ArrayList<>();
    required.add("address");
    schema.setRequired(required);
    schema.addProperties("name", new StringSchema());
    schema.addProperties("address", objectSchema);


    openAPI.getComponents().addSchemas("User", schema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");
    assertTrue((address.get$ref()!= null));
    Schema userAddress = openAPI.getComponents().getSchemas().get("User_address");
    assertNotNull(userAddress);
    assertNotNull(userAddress.getProperties().get("city"));
    assertNotNull(userAddress.getProperties().get("street"));
}
 
Example #27
Source File: SpringDocApp76Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI openAPI() {
	return new OpenAPI()
			.components(new Components().addSecuritySchemes("bearer-jwt",
					new SecurityScheme()
							.type(SecurityScheme.Type.HTTP)
							.scheme("bearer")
							.bearerFormat("JWT"))
			)
			.addSecurityItem(
					new SecurityRequirement().addList("bearer-jwt", Arrays.asList("read", "write")));
}
 
Example #28
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitraryObjectModelWithArrayInlineWithoutTitle() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema items = new ObjectSchema();
    items.setDefault("default");
    items.setReadOnly(false);
    items.setDescription("description");
    items.setName("name");
    items.addProperties("arbitrary", new ObjectSchema());

    openAPI.getComponents().addSchemas("User", new ArraySchema().items(items).addRequiredItem("name"));

    new InlineModelResolver().flatten(openAPI);

    Schema model = openAPI.getComponents().getSchemas().get("User");
    assertTrue(model instanceof ArraySchema);
    ArraySchema am = (ArraySchema) model;
    Schema inner = am.getItems();
    assertTrue(inner.get$ref() != null);

    Schema userInner = openAPI.getComponents().getSchemas().get("User_inner");
    assertNotNull(userInner);
    Schema inlineProp = (Schema)userInner.getProperties().get("arbitrary");
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example #29
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void testSimpleRemoteModelProperty(String remoteRef) {
    final OpenAPI swagger = new OpenAPI();
    swagger.components(new Components().addSchemas("Sample", new Schema()
            .addProperties("remoteRef", new Schema().$ref(remoteRef))));


    final OpenAPI resolved = new OpenAPIResolver(swagger, null).resolve();
    final Schema prop = (Schema) resolved.getComponents().getSchemas().get("Sample").getProperties().get("remoteRef");
    assertTrue(prop.get$ref() != null);

    assertEquals(prop.get$ref(), "#/components/schemas/Tag");
    assertNotNull(swagger.getComponents().getSchemas().get("Tag"));
}
 
Example #30
Source File: SpringDocApp105Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI customOpenAPI() {
	return new OpenAPI()
			.components(new Components().addSecuritySchemes("basicScheme",
					new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
			.info(new Info().title("Petstore API").version("v0").description(
					"This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.")
					.termsOfService("http://swagger.io/terms/")
					.license(new License().name("Apache 2.0").url("http://springdoc.org")));
}