Java Code Examples for io.swagger.v3.oas.models.media.StringSchema

The following examples show how to use io.swagger.v3.oas.models.media.StringSchema. These examples are extracted from open source projects. 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 Project: servicecomb-toolkit   Source File: OperationContext.java    License: Apache License 2.0 6 votes vote down vote up
private void processHeaders() {

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

    Arrays.stream(headers).forEach(header -> {
      String[] headMap = header.split("=");
      if (headMap.length == 2) {
        HeaderParameter headerParameter = new HeaderParameter();
        headerParameter.setName(headMap[0]);
        StringSchema value = new StringSchema();
        value.setDefault(headMap[1]);
        headerParameter.setSchema(value);
        operation.addParametersItem(headerParameter);
      }
    });
  }
 
Example 2
@Test
public void processParameterAnnotation() throws NoSuchMethodException, IllegalAccessException,
    InstantiationException {

  OasContext oasContext = new OasContext(null);
  Method parameterMethod = ParameterClass.class.getMethod("parameter", String.class);
  OperationContext operationContext = new OperationContext(parameterMethod, oasContext);
  java.lang.reflect.Parameter[] parameters = parameterMethod.getParameters();
  Assert.assertEquals(parameters.length, 1);
  java.lang.reflect.Parameter parameter = parameters[0];
  Parameter parameterDeclaredAnnotation = parameter.getDeclaredAnnotation(Parameter.class);

  ParameterContext parameterContext = new ParameterContext(operationContext, parameter);
  ParameterAnnotationProcessor parameterAnnotationProcessor = new ParameterAnnotationProcessor();

  parameterAnnotationProcessor.process(parameterDeclaredAnnotation, parameterContext);
  io.swagger.v3.oas.models.parameters.Parameter oasParameter = parameterContext.toParameter();
  Assert.assertEquals("param", oasParameter.getName());
  Assert.assertEquals(StringSchema.class, oasParameter.getSchema().getClass());
  Assert.assertTrue(parameterContext.isRequired());
  Assert.assertEquals(operationContext, parameterContext.getOperationContext());
  Assert.assertNull(parameterContext.getDefaultValue());
}
 
Example 3
@Test
public void testConvertStringArrayCSVWithEscapedValue() throws Exception {
    List<String> values = Arrays.asList("\"good, bad\",bad");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.FORM)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new StringSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(String.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<String> objs = (List<String>) o;

    assertTrue(objs.size() == 2);
    assertEquals(objs.get(0), "good, bad");
    assertEquals(objs.get(1), "bad");
}
 
Example 4
/**
 * Registers an OpenApiCustomiser and a jackson mixin to ensure the definition of `Links` matches the serialized
 * output. This is done because the customer serializer converts the data to a map before serializing it.
 *
 * @param halProvider the hal provider
 * @return the open api customiser
 * @see org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider) org.springframework.hateoas.mediatype.hal.Jackson2HalModule.HalLinkListSerializer#serialize(Links, JsonGenerator, SerializerProvider)
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
OpenApiCustomiser linksSchemaCustomiser(HateoasHalProvider halProvider) {
	if (!halProvider.isHalEnabled()) {
		return openApi -> {
		};
	}
	Json.mapper().addMixIn(RepresentationModel.class, RepresentationModelLinksOASMixin.class);

	ResolvedSchema resolvedLinkSchema = ModelConverters.getInstance()
			.resolveAsResolvedSchema(new AnnotatedType(Link.class));

	return openApi -> openApi
			.schema("Link", resolvedLinkSchema.schema)
			.schema("Links", new MapSchema()
					.additionalProperties(new StringSchema())
					.additionalProperties(new ObjectSchema().$ref(AnnotationsUtils.COMPONENTS_REF +"Link")));
}
 
Example 5
Source Project: springdoc-openapi   Source File: PropertyCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Schema customize(Schema property, AnnotatedType type) {
	Annotation[] ctxAnnotations = type.getCtxAnnotations();
	if (ctxAnnotations == null) {
		return property;
	}

	Optional<CustomizedProperty> propertyAnnotation = Stream.of(ctxAnnotations)
			.filter(CustomizedProperty.class::isInstance)
			.findFirst()
			.map(CustomizedProperty.class::cast);

	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType.getRawClass().equals(Duration.class)) {
		property = new StringSchema().format("duration").properties(Collections.emptyMap());
	}
	return property;
}
 
Example 6
Source Project: springdoc-openapi   Source File: AbstractOpenApiResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fill parameters list.
 *
 * @param operation the operation
 * @param queryParams the query params
 * @param methodAttributes the method attributes
 */
private void fillParametersList(Operation operation, Map<String, String> queryParams, MethodAttributes methodAttributes) {
	List<Parameter> parametersList = operation.getParameters();
	if (parametersList == null)
		parametersList = new ArrayList<>();
	Collection<Parameter> headersMap = AbstractRequestBuilder.getHeaders(methodAttributes, new LinkedHashMap<>());
	parametersList.addAll(headersMap);
	if (!CollectionUtils.isEmpty(queryParams)) {
		for (Map.Entry<String, String> entry : queryParams.entrySet()) {
			io.swagger.v3.oas.models.parameters.Parameter parameter = new io.swagger.v3.oas.models.parameters.Parameter();
			parameter.setName(entry.getKey());
			parameter.setSchema(new StringSchema()._default(entry.getValue()));
			parameter.setRequired(true);
			parameter.setIn(ParameterIn.QUERY.toString());
			GenericParameterBuilder.mergeParameter(parametersList, parameter);
		}
		operation.setParameters(parametersList);
	}
}
 
Example 7
/**
 * 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 8
Source Project: openapi-generator   Source File: JavaJaxrsBaseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void addDefaultValueDocumentationForNonContainers() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
            .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI();

    openAPI.getComponents().getParameters().get("operationsQueryParam").setSchema(new StringSchema()._default("default"));
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
    .openAPI(openAPI)
    .config(codegen);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(input).generate();

    assertFileContains(Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java"),  "DefaultValue");
}
 
Example 9
Source Project: openapi-generator   Source File: Swift4ModelEnumTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a java model with an reserved word string enum and a default value")
public void convertReservedWordStringDefaultValueTest() {
    final StringSchema enumSchema = new StringSchema();
    enumSchema.setEnum(Arrays.asList("1st", "2nd", "3rd"));
    enumSchema.setDefault("2nd");
    final Schema model = new Schema().type("object").addProperties("name", enumSchema);

    final DefaultCodegen codegen = new Swift4Codegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty enumVar = cm.vars.get(0);
    Assert.assertEquals(enumVar.baseName, "name");
    Assert.assertEquals(enumVar.dataType, "String");
    Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
    Assert.assertEquals(enumVar.name, "name");
    Assert.assertEquals(enumVar.defaultValue, "._2nd");
    Assert.assertEquals(enumVar.baseType, "String");
    Assert.assertTrue(enumVar.isEnum);
}
 
Example 10
Source Project: swagger-parser   Source File: InlineModelResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicInput() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema user = new Schema();
    user.addProperties("name", new StringSchema());

    openAPI.path("/foo/baz", new PathItem()
            .post(new Operation()
                    .requestBody(new RequestBody()
                            .content(new Content().addMediaType("*/*",new MediaType().schema(new Schema().$ref("User")))))));

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

    new InlineModelResolver().flatten(openAPI);
}
 
Example 11
Source Project: openapi-generator   Source File: Swift5ModelEnumTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a java model with an string enum and a default value")
public void convertStringDefaultValueTest() {
    final StringSchema enumSchema = new StringSchema();
    enumSchema.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3"));
    enumSchema.setDefault("VALUE2");
    final Schema model = new Schema().type("object").addProperties("name", enumSchema);

    final DefaultCodegen codegen = new Swift5ClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty enumVar = cm.vars.get(0);
    Assert.assertEquals(enumVar.baseName, "name");
    Assert.assertEquals(enumVar.dataType, "String");
    Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
    Assert.assertEquals(enumVar.name, "name");
    Assert.assertEquals(enumVar.defaultValue, ".value2");
    Assert.assertEquals(enumVar.baseType, "String");
    Assert.assertTrue(enumVar.isEnum);
}
 
Example 12
Source Project: openapi-generator   Source File: Swift5ModelEnumTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a java model with an reserved word string enum and a default value")
public void convertReservedWordStringDefaultValueTest() {
    final StringSchema enumSchema = new StringSchema();
    enumSchema.setEnum(Arrays.asList("1st", "2nd", "3rd"));
    enumSchema.setDefault("2nd");
    final Schema model = new Schema().type("object").addProperties("name", enumSchema);

    final DefaultCodegen codegen = new Swift5ClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty enumVar = cm.vars.get(0);
    Assert.assertEquals(enumVar.baseName, "name");
    Assert.assertEquals(enumVar.dataType, "String");
    Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
    Assert.assertEquals(enumVar.name, "name");
    Assert.assertEquals(enumVar.defaultValue, "._2nd");
    Assert.assertEquals(enumVar.baseType, "String");
    Assert.assertTrue(enumVar.isEnum);
}
 
Example 13
Source Project: openapi-generator   Source File: SerializerUtilsTest.java    License: Apache License 2.0 6 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 14
@Test
public void testKebabCasedModelFilenames() {
    TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();
    codegen.additionalProperties().put(TypeScriptAngularClientCodegen.FILE_NAMING, "kebab-case");
    codegen.processOpts();

    final String modelName = "FooResponse__links";
    final Schema schema = new Schema()
        .name(modelName)
        .description("an inline model with name previously prefixed with underscore")
        .addRequiredItem("self")
        .addProperties("self", new StringSchema());

    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("test", schema);
    codegen.setOpenAPI(openAPI);

    Assert.assertEquals(codegen.toModelImport(modelName), "model/foo-response-links");
    Assert.assertEquals(codegen.toModelFilename(modelName), "./foo-response-links");
}
 
Example 15
@Test
public void testConvertStringArrayPipesWithEscapedValue() throws Exception {
    List<String> values = Arrays.asList("\"good | bad\"|bad");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.PIPEDELIMITED)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new StringSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(String.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<String> objs = (List<String>) o;

    assertTrue(objs.size() == 2);
    assertEquals(objs.get(0), "good | bad");
    assertEquals(objs.get(1), "bad");
}
 
Example 16
@Test
public void testConvertStringArrayCSV() throws Exception {
    List<String> values = Arrays.asList("a,b");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.FORM)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new StringSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(String.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<String> objs = (List<String>) o;

    assertTrue(objs.size() == 2);
    assertEquals(objs.get(0), "a");
    assertEquals(objs.get(1), "b");
}
 
Example 17
Source Project: crnk-framework   Source File: OASUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEnumMetaLiteral() {
  MetaEnumType type = new MetaEnumType();
  type.setName("TestEnum");

  List<String> names = Arrays.asList("Remo", "Mac", "Ralph");
  List<MetaElement> people = new ArrayList<>();
  for (String name : names) {
    MetaLiteral person = new MetaLiteral();
    person.setName(name);
    people.add(person);
  }

  type.setChildren(people);
  Schema schema = OASUtils.transformMetaResourceField(type);
  Assert.assertTrue(schema instanceof StringSchema);
  for (int i = 0; i < 3; i++) {
    Assert.assertEquals(names.get(i), schema.getEnum().get(i));
  }
}
 
Example 18
Source Project: zap-extensions   Source File: DataGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static String generateDefaultValue(Parameter parameter) {
    List<String> enumValues = null;
    if (parameter.getSchema() instanceof StringSchema) {
        enumValues = ((StringSchema) (parameter.getSchema())).getEnum();
    }

    if (parameter.getSchema().getDefault() != null) {
        String strValue = parameter.getSchema().getDefault().toString();
        if (!strValue.isEmpty()) {
            return strValue;
        }
    }
    if (enumValues != null && !enumValues.isEmpty()) {
        return enumValues.get(0);
    }
    if (parameter.getExample() != null) {
        return parameter.getExample().toString();
    }
    return "";
}
 
Example 19
Source Project: swagger-parser   Source File: OpenAPIResolverTest.java    License: 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 20
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnArraySchema_When_GivenTypeIsAnArray() {
    ResolvedType arrayType = mock(ResolvedType.class);
    ResolvedArrayType arrayResolvedType = mock(ResolvedArrayType.class);
    ResolvedType stringType = mockReferencedTypeOf(String.class);

    when(arrayType.isArray()).thenReturn(true);
    when(arrayType.asArrayType()).thenReturn(arrayResolvedType);
    when(arrayResolvedType.getComponentType()).thenReturn(stringType);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(arrayType);
    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 21
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNotNullableArray_When_GivenTypeIsAListString() {
    ResolvedType resolvedType = mockReferencedTypeOf(Collection.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(String.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 22
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNullableOptional_When_GivenTypeIsAnOptionalString() {
    ResolvedType resolvedType = mockReferencedTypeOf(Optional.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(String.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof StringSchema);
    Assert.assertTrue(schema.getNullable());

    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 23
Source Project: swagger-inflector   Source File: BodyParamExtractionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertDoubleArrayBodyParam() throws Exception {
    Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class);

    RequestBody body = new RequestBody().
            content(new Content()
                    .addMediaType("application/json",new MediaType().schema(new ArraySchema()
                            .items(new ArraySchema().items(new StringSchema())))));


    JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0];
    assertNotNull(jt);

    assertEquals(jt.getRawClass(), List[].class);
    JavaType inner = jt.getContentType();
    assertEquals(inner.getRawClass(), List.class);
    assertEquals(inner.getContentType().getRawClass(), String.class);

}
 
Example 24
Source Project: swagger-inflector   Source File: StringTypeValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ValidationException.class)
public void testInvalidStringValueEnum() throws Exception {
    List<String> values = new ArrayList<>();
    for(int i = 1; i <= 3; i++) {
        String str = "allowable_" + i;
        values.add(str);
    }

    QueryParameter parameter = new QueryParameter();
        parameter.setName("test");
        parameter.setSchema(new StringSchema()._enum(values));

    converter.validate("allowable_4", parameter);
}
 
Example 25
Source Project: swagger-parser   Source File: InlineModelResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineModelTestWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());


    Schema objectSchema = new ObjectSchema();
    objectSchema.setTitle("UserAddressTitle");
    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 userAddressTitle = openAPI.getComponents().getSchemas().get("UserAddressTitle");
    assertNotNull(userAddressTitle);
    assertNotNull(userAddressTitle.getProperties().get("city"));
    assertNotNull(userAddressTitle.getProperties().get("street"));
}
 
Example 26
Source Project: springdoc-openapi   Source File: SpringDocTestApp.java    License: 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 27
Source Project: springdoc-openapi   Source File: SpringDocTestApp.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI defineOpenApi() {
	OpenAPI api = new OpenAPI();
	api.components(new Components().addResponses("Unauthorized",
			new ApiResponse().description("Unauthorized")
					.content(new Content().addMediaType(MediaType.APPLICATION_JSON_VALUE,
							new io.swagger.v3.oas.models.media.MediaType().schema(new StringSchema())))));
	return api;
}
 
Example 28
Source Project: swagger-parser   Source File: InlineModelResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitraryObjectModelInline() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema userSchema = new Schema();
    userSchema.setName("user");
    userSchema.setDescription("a common user");
    userSchema.addProperties("name", new StringSchema());

    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.setTitle("title");
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");

    userSchema.addProperties("arbitrary", objectSchema);
    List required = new ArrayList();
    required.add("arbitrary");
    userSchema.setRequired(required);


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

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");
    assertNotNull(user);
    Schema inlineProp = (Schema) user.getProperties().get("arbitrary");
    assertTrue(inlineProp instanceof ObjectSchema);
    assertNull(inlineProp.getProperties());
}
 
Example 29
Source Project: springdoc-openapi   Source File: AbstractRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets headers.
 *
 * @param methodAttributes the method attributes
 * @param map the map
 * @return the headers
 */
public static Collection<Parameter> getHeaders(MethodAttributes methodAttributes, Map<String, Parameter> map) {
	for (Map.Entry<String, String> entry : methodAttributes.getHeaders().entrySet()) {
		Parameter parameter = new Parameter().in(ParameterIn.HEADER.toString()).name(entry.getKey()).schema(new StringSchema().addEnumItem(entry.getValue()));
		if (map.containsKey(entry.getKey())) {
			parameter = map.get(entry.getKey());
			parameter.getSchema().addEnumItemObject(entry.getValue());
			parameter.setSchema(parameter.getSchema());
		}
		map.put(entry.getKey(), parameter);
	}
	return map.values();
}
 
Example 30
@Test
public void getStringArrayParameterClassTest() throws Exception {
    JavaType jt = utils.getTypeFromParameter(new QueryParameter()
                            .schema(new ArraySchema().items(new StringSchema())), null);

    assertEquals(jt.getRawClass(), List.class);
    assertEquals(jt.getContentType().getRawClass(), String.class);
}