Java Code Examples for io.swagger.v3.oas.models.media.ArraySchema#getItems()

The following examples show how to use io.swagger.v3.oas.models.media.ArraySchema#getItems() . 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: AbstractKotlinCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Provides a strongly typed declaration for simple arrays of some type and arrays of arrays of some type.
 *
 * @param arr Array schema
 * @return type declaration of array
 */
private String getArrayTypeDeclaration(ArraySchema arr) {
    // TODO: collection type here should be fully qualified namespace to avoid model conflicts
    // This supports arrays of arrays.
    String arrayType;
    if (ModelUtils.isSet(arr)) {
        arrayType = typeMapping.get("set");
    } else {
        arrayType = typeMapping.get("array");
    }
    StringBuilder instantiationType = new StringBuilder(arrayType);
    Schema items = arr.getItems();
    String nestedType = getTypeDeclaration(items);
    additionalProperties.put("nestedType", nestedType);
    // TODO: We may want to differentiate here between generics and primitive arrays.
    instantiationType.append("<").append(nestedType).append(">");
    return instantiationType.toString();
}
 
Example 2
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveComposedSchema(@Injectable final List<AuthorizationValue> auths){

    ParseOptions options = new ParseOptions();
    options.setResolveCombinators(false);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/oneof-anyof.yaml",auths,options).getOpenAPI();


    assertTrue(openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema) openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(arraySchema.getItems() instanceof ComposedSchema);
    ComposedSchema oneOf = (ComposedSchema) arraySchema.getItems();
    assertEquals(oneOf.getOneOf().get(0).getType(), "string");

    //System.out.println(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() );
    assertTrue(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ComposedSchema);
    ComposedSchema oneOfSchema = (ComposedSchema) openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertEquals(oneOfSchema.getOneOf().get(0).getType(), "object");

}
 
Example 3
Source File: ArrayGenerator.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
public String generate(
        String name, ArraySchema property, String collectionType, boolean isPath) {

    if (property == null) {
        return "";
    }
    if (collectionType.isEmpty()) {
        collectionType = "csv";
    }
    String valueType = property.getItems().getType();
    if (dataGenerator.isArray(valueType)) {
        if (property.getItems() instanceof ArraySchema) {
            return generate(name, (ArraySchema) property.getItems(), collectionType, isPath);
        } else {
            return "";
        }
    }
    String value = dataGenerator.generateValue(name, property.getItems(), isPath);
    return ARRAY_BEGIN + value + ARRAY_END;
}
 
Example 4
Source File: AbstractCSharpCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Provides C# strongly typed declaration for simple arrays of some type and arrays of arrays of some type.
 *
 * @param arr The input array property
 * @return The type declaration when the type is an array of arrays.
 */
private String getArrayTypeDeclaration(ArraySchema arr) {
    // TODO: collection type here should be fully qualified namespace to avoid model conflicts
    // This supports arrays of arrays.
    String arrayType = typeMapping.get("array");
    StringBuilder instantiationType = new StringBuilder(arrayType);
    Schema items = arr.getItems();
    String nestedType = getTypeDeclaration(items);
    // TODO: We may want to differentiate here between generics and primitive arrays.
    instantiationType.append("<").append(nestedType).append(">");
    return instantiationType.toString();
}
 
Example 5
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testPetstore() throws Exception {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = parser.readLocation("src/test/resources/petstore.yaml", null, options);

    assertNotNull(result);
    assertTrue(result.getMessages().size()==2);

    OpenAPI openAPI = result.getOpenAPI();
    Map<String, Schema> definitions = openAPI.getComponents().getSchemas();
    Set<String> expectedDefinitions = new HashSet<String>();
    expectedDefinitions.add("User");
    expectedDefinitions.add("Category");
    expectedDefinitions.add("Pet");
    expectedDefinitions.add("Tag");
    expectedDefinitions.add("Order");
    expectedDefinitions.add("PetArray");
    assertEquals(definitions.keySet(), expectedDefinitions);

    Schema petModel = definitions.get("Pet");
    Set<String> expectedPetProps = new HashSet<String>();
    expectedPetProps.add("id");
    expectedPetProps.add("category");
    expectedPetProps.add("name");
    expectedPetProps.add("photoUrls");
    expectedPetProps.add("tags");
    expectedPetProps.add("status");
    assertEquals(petModel.getProperties().keySet(), expectedPetProps);

    ArraySchema petArrayModel = (ArraySchema) definitions.get("PetArray");
    assertEquals(petArrayModel.getType(), "array");
    Schema refProp = petArrayModel.getItems();
    assertEquals(refProp.get$ref(), "#/components/schemas/Pet");
    assertNull(petArrayModel.getProperties());
}
 
Example 6
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitraryObjectModelWithArrayInlineWithTitle() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema items = new ObjectSchema();
    items.setTitle("InnerUserTitle");
    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("InnerUserTitle");
    assertNotNull(userInner);
    Schema inlineProp = (Schema) userInner.getProperties().get("arbitrary");
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example 7
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 8
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 9
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public void processArraySchema(ArraySchema arraySchema) {

        final Schema items = arraySchema.getItems();
        if (items.get$ref() != null) {
            processReferenceSchema(items);
        }else{
            processSchemaType(items);
        }
    }
 
Example 10
Source File: ExampleGenerator.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private List<Map<String, String>> generateFromResponseSchema(Schema responseSchema, Set<String> producesInfo) {
    if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !ModelUtils.isArraySchema(responseSchema)) {
        // no example provided
        return null;
    }

    if (responseSchema.getExample() != null && !(responseSchema.getExample() instanceof Map)) {
        return generate(responseSchema.getExample(), new ArrayList<>(producesInfo));
    }

    if (ModelUtils.isArraySchema(responseSchema)) { // array of schema
        ArraySchema as = (ArraySchema) responseSchema;
        if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types
            return generate((Map<String, Object>) responseSchema.getExample(),
                    new ArrayList<String>(producesInfo), as.getItems());
        } else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model
            return generate((Map<String, Object>) responseSchema.getExample(),
                    new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(as.getItems().get$ref()));
        } else {
            // TODO log warning message as such case is not handled at the moment
            return null;
        }
    } else if (StringUtils.isEmpty(responseSchema.get$ref())) { // primtiive type (e.g. integer, string)
        return generate((Map<String, Object>) responseSchema.getExample(),
                new ArrayList<String>(producesInfo), responseSchema);
    } else { // model
        return generate((Map<String, Object>) responseSchema.getExample(),
                new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(responseSchema.get$ref()));
    }
}
 
Example 11
Source File: AbstractFSharpCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Provides F# strongly typed declaration for simple arrays of some type and arrays of arrays of some type.
 *
 * @param arr The input array property
 * @return The type declaration when the type is an array of arrays.
 */
private String getArrayTypeDeclaration(ArraySchema arr) {
    // TODO: collection type here should be fully qualified namespace to avoid model conflicts
    // This supports arrays of arrays.
    String arrayType = typeMapping.get("array");
    StringBuilder instantiationType = new StringBuilder(arrayType);
    Schema items = arr.getItems();
    String nestedType = getTypeDeclaration(items);
    // TODO: We may want to differentiate here between generics and primitive arrays.
    return nestedType + "[]";
}
 
Example 12
Source File: DefaultConverter.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
public Object cast(List<String> arguments, Parameter parameter, JavaType javaType, Map<String, Schema> definitions) throws ConversionException {
    if (arguments == null || arguments.size() == 0) {
        return null;
    }
    Class<?> cls = javaType.getRawClass();

    LOGGER.debug("converting array `" + arguments + "` to `" + cls + "`");
    if (javaType.isArrayType()) {
        if (parameter.getSchema() != null) {
            List<Object> output = new ArrayList<>();
            if (parameter.getSchema() instanceof ArraySchema) {
                ArraySchema arraySchema = (ArraySchema) parameter.getSchema();
                if (arraySchema.getItems() != null) {
                    Schema inner = arraySchema.getItems();

                    // TODO: this does not need to be done this way, update the helper method
                    Parameter innerParam = new QueryParameter().schema(inner);
                    JavaType innerClass = getTypeFromParameter(innerParam, definitions);
                    for (String obj : arguments) {
                        String[] parts = new String[0];
                        CSVFormat format = null;
                        if (Parameter.StyleEnum.FORM.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj) && parameter.getExplode() == false) {
                            format = CSVFormat.DEFAULT;
                        } else if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                            format = CSVFormat.newFormat('|').withQuote('"');
                        } else if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                            format = CSVFormat.newFormat(' ').withQuote('"');
                        }
                        if (format != null) {
                            try {
                                for (CSVRecord record : CSVParser.parse(obj, format).getRecords()) {
                                    List<String> it = new ArrayList<String>();
                                    for (Iterator<String> x = record.iterator(); x.hasNext(); ) {
                                        it.add(x.next());
                                    }
                                    parts = it.toArray(new String[it.size()]);
                                }
                            } catch (IOException e) {
                            }
                        } else {
                            parts = new String[1];
                            parts[0] = obj;
                        }
                        for (String p : parts) {
                            Object ob = cast(p, inner, innerClass);
                            if (ob != null) {
                                output.add(ob);
                            }
                        }

                    }

                    return output;
                }
            }
        }
    } else if (parameter != null) {
        return cast(arguments.get(0), parameter.getSchema(), javaType);
    }
    return null;
}
 
Example 13
Source File: DefaultConverter.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
public Object coerceValue(List<String> arguments, Parameter parameter, Class<?> cls) throws ConversionException {
    if (arguments == null || arguments.size() == 0) {
        return null;
    }

    LOGGER.debug("casting `" + arguments + "` to " + cls);
    if (List.class.equals(cls)) {
        if (parameter.getSchema() != null) {
            List<Object> output = new ArrayList<>();
            if (parameter.getSchema() instanceof ArraySchema) {
                ArraySchema arraySchema = ((ArraySchema) parameter.getSchema());
                Schema inner = arraySchema.getItems();


                // TODO: this does not need to be done this way, update the helper method
                Parameter innerParam = new QueryParameter();
                innerParam.setSchema(inner);
                JavaType innerClass = getTypeFromParameter(innerParam, definitions);
                for (String obj : arguments) {
                    String[] parts = new String[0];

                    if (Parameter.StyleEnum.FORM.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj) && parameter.getExplode() == false ) {
                        parts = obj.split(",");
                    }
                    if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                        parts = obj.split("|");
                    }
                    if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj)) {
                        parts = obj.split(" ");
                    }
                    if (Parameter.StyleEnum.FORM.equals(parameter.getStyle()) && !StringUtils.isEmpty(obj) && parameter.getExplode() == true) {
                        parts = new String[1];
                        parts[0]= obj;
                    }
                    for (String p : parts) {
                        Object ob = cast(p, inner, innerClass);
                        if (ob != null) {
                            output.add(ob);
                        }
                    }
                }
            }
            return output;
        }
    } else if (parameter.getSchema() != null) {
        TypeFactory tf = Json.mapper().getTypeFactory();

        return cast(arguments.get(0), parameter.getSchema(), tf.constructType(cls));

    }
    return null;
}
 
Example 14
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue85(@Injectable final List<AuthorizationValue> auths) {
    String yaml =
            "openapi: '3.0.1'\n" +
                    "paths: \n" +
                    "  /test/method: \n" +
                    "    post: \n" +
                    "      parameters: \n" +
                    "        - \n" +
                    "          in: \"path\"\n" +
                    "          name: \"body\"\n" +
                    "          required: false\n" +
                    "          schema: \n" +
                    "            $ref: '#/components/Schemas/StructureA'\n" +
                    "components: \n" +
                    "   schemas:\n" +
                    "       StructureA: \n" +
                    "           type: object\n" +
                    "           properties: \n" +
                    "               someProperty: \n" +
                    "                   type: string\n" +
                    "               arrayOfOtherType: \n" +
                    "                   type: array\n" +
                    "                   items: \n" +
                    "                       $ref: '#/definitions/StructureB'\n" +
                    "       StructureB: \n" +
                    "           type: object\n" +
                    "           properties: \n" +
                    "               someProperty: \n" +
                    "                   type: string\n";

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

    OpenAPI openAPI = new OpenAPIV3Parser().readContents(yaml,auths,options).getOpenAPI();
    ResolverFully resolverUtil = new ResolverFully();
    resolverUtil.resolveFully(openAPI);
    Parameter param = openAPI.getPaths().get("/test/method").getPost().getParameters().get(0);

    Schema schema = param.getSchema();
    assertNotNull(schema.getProperties().get("someProperty"));

    ArraySchema am = (ArraySchema) schema.getProperties().get("arrayOfOtherType");
    assertNotNull(am);
    Schema prop = am.getItems();
    assertTrue(prop instanceof Schema);
}
 
Example 15
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveInlineArrayResponse() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    ObjectSchema items = new ObjectSchema();
    items.addExtension("x-ext", "ext-items");
    items.addProperties("name", new StringSchema());


    ArraySchema schema = new ArraySchema()
            .items(items);
    schema.addExtension("x-ext", "ext-prop");

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

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

    new InlineModelResolver().flatten(openAPI);

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

    assertNotNull(apiResponse.getContent().get("*/*").getSchema());
    Schema responseProperty = apiResponse.getContent().get("*/*").getSchema();

    // no need to flatten more
    assertTrue(responseProperty instanceof ArraySchema);

    ArraySchema ap = (ArraySchema) responseProperty;
    assertEquals(1, ap.getExtensions().size());
    assertEquals("ext-prop", ap.getExtensions().get("x-ext"));

    Schema p = ap.getItems();

    assertNotNull(p);

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

    assertEquals(1, p.getExtensions().size());
    assertEquals("ext-items", p.getExtensions().get("x-ext"));

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

    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example 16
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveInlineArrayResponseWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    ApiResponse apiResponse  = new ApiResponse();
    apiResponse.addExtension("x-foo", "bar");
    apiResponse.description("it works!");

    Map<String,Schema> properties = new HashMap<>();
    properties.put("name", new StringSchema());

    apiResponse.content(new Content().addMediaType("*/*", new MediaType().schema(new ArraySchema()
                    .items(new ObjectSchema()
                            .title("FooBar")
                            .properties(properties)))));

    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");
    assertNotNull(response);

    assertNotNull(response.getContent().get("*/*").getSchema());
    Schema responseProperty = response.getContent().get("*/*").getSchema();

    // no need to flatten more
    assertTrue(responseProperty instanceof ArraySchema);

    ArraySchema ap = (ArraySchema) responseProperty;
    Schema p = ap.getItems();

    assertNotNull(p);

    assertEquals(p.get$ref(), "#/components/schemas/"+ "FooBar");


    Schema inline = openAPI.getComponents().getSchemas().get("FooBar");
    assertNotNull(inline);
    assertTrue(inline instanceof Schema);
    assertNotNull(inline.getProperties().get("name"));
    assertTrue(inline.getProperties().get("name") instanceof StringSchema);
}
 
Example 17
Source File: XmlExampleGenerator.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
protected String toXml(String name, Schema schema, int indent, Collection<String> path) {
    if (schema == null) {
        return "";
    }
    StringBuilder sb = new StringBuilder();

    if (ModelUtils.isArraySchema(schema)) {
        ArraySchema as = (ArraySchema) schema;
        Schema inner = as.getItems();
        boolean wrapped = false;
        if (schema.getXml() != null && schema.getXml().getWrapped() != null && schema.getXml().getWrapped()) {
            wrapped = true;
        }
        if (wrapped) {
            String prefix = EMPTY;
            if (name != null) {
                sb.append(indent(indent));
                sb.append(openTag(name));
                prefix = NEWLINE;
            }
            final String asXml = toXml(name, inner, indent + 1, path);
            if (StringUtils.isNotEmpty(asXml)) {
                sb.append(prefix).append(asXml);
            }
            if (name != null) {
                sb.append(NEWLINE);
                sb.append(indent(indent));
                sb.append(closeTag(name));
            }
        } else {
            sb.append(toXml(name, inner, indent, path));
        }
    } else if (StringUtils.isNotEmpty(schema.get$ref())) {
        Schema actualSchema = examples.get(schema.get$ref());
        sb.append(toXml(actualSchema, indent, path));
    } else {
        if (name != null) {
            sb.append(indent(indent));
            sb.append(openTag(name));
        }
        sb.append(getExample(schema));
        if (name != null) {
            sb.append(closeTag(name));
        }
    }
    return sb.toString();
}
 
Example 18
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldParseApiWithParametersUsingContentvsSchema() {
    // Tests that the content method of specifying the format of a parameter
    // gets resolved.
    // Test checks if an API's single parameter of array type gets fully resolved to 
    // referenced definitions.
    String location = "src/test/resources/issue-1078/api.yaml";
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    // This test uses an Array in the parameters, test if it get's fully resolved.
    options.setResolveFully(true);
    OpenAPIV3Parser tested = new OpenAPIV3Parser();
    
    // Parse yaml
    SwaggerParseResult result = tested.readLocation(location, emptyList(), options);

    OpenAPI api = result.getOpenAPI();
    Paths paths = api.getPaths();

    // First ensure all schemas were resolved, this is important when this library 
    // is used to generate code
    Components components = api.getComponents();
    assertNotNull(components);
    assertThat(components.getSchemas().size(), equalTo(4));
    assertNotNull(components.getSchemas().get("LocationType"));
    assertNotNull(components.getSchemas().get("Lat"));
    assertNotNull(components.getSchemas().get("Long"));
    assertNotNull(components.getSchemas().get("SearchResult"));
    
    PathItem apiEndpoint = paths.get("/api-endpoint-1");
    List<Parameter> parameters = apiEndpoint.getGet().getParameters();
    
    // Ensure there's only one parameter in this test
    assertThat(parameters.size(), equalTo(1));
    
    // We are testing content for a parameter so make sure its there.
    Content content = parameters.get(0).getContent();
    assertNotNull(content);
    // spec says only one content is permitted in 3.x
    assertThat( content.size(), equalTo(1));

    // Ensure there's a media type
    MediaType mediaType = content.entrySet().iterator().next().getValue();
    assertNotNull(mediaType);

    // This test has a single parameter of type array
    Schema parameterSchema = mediaType.getSchema();
    Assert.assertTrue(parameterSchema instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema)parameterSchema;

    // Test if the item schema was resolved properly
    Schema itemSchema = arraySchema.getItems();
    assertNotNull(itemSchema);
    Assert.assertTrue(itemSchema instanceof ObjectSchema);

    // Ensure the referenced item's schema has been resolved.
    ObjectSchema objSchema = (ObjectSchema)itemSchema;
    Map<String, Schema> objectItemSchemas = objSchema.getProperties();
    assertThat( objectItemSchemas.size(), equalTo(2));
    Assert.assertTrue(objectItemSchemas.get("lat") instanceof IntegerSchema);
    Assert.assertTrue(objectItemSchemas.get("long") instanceof IntegerSchema);
}
 
Example 19
Source File: AbstractTypeScriptClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected String getParameterDataType(Parameter parameter, Schema p) {
    // handle enums of various data types
    Schema inner;
    if (ModelUtils.isArraySchema(p)) {
        ArraySchema mp1 = (ArraySchema) p;
        inner = mp1.getItems();
        return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
    } else if (ModelUtils.isMapSchema(p)) {
        inner = getAdditionalProperties(p);
        return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
    } else if (ModelUtils.isStringSchema(p)) {
        // Handle string enums
        if (p.getEnum() != null) {
            return enumValuesToEnumTypeUnion(p.getEnum(), "string");
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        // Handle integer enums
        if (p.getEnum() != null) {
            return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
        }
    } else if (ModelUtils.isNumberSchema(p)) {
        // Handle double enums
        if (p.getEnum() != null) {
            return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
        }
    }
    /* TODO revise the logic below
    else if (ModelUtils.isDateSchema(p)) {
        // Handle date enums
        DateSchema sp = (DateSchema) p;
        if (sp.getEnum() != null) {
            return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
        }
    } else if (ModelUtils.isDateTimeSchema(p)) {
        // Handle datetime enums
        DateTimeSchema sp = (DateTimeSchema) p;
        if (sp.getEnum() != null) {
            return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
        }
    }*/
    return this.getTypeDeclaration(p);
}
 
Example 20
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
private OpenAPI doRelativeFileTest(String location) {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult readResult = parser.readLocation(location, null, options);

    if (readResult.getMessages().size() > 0) {
        Json.prettyPrint(readResult.getMessages());
    }
    final OpenAPI openAPI = readResult.getOpenAPI();
    final PathItem path = openAPI.getPaths().get("/health");
    assertEquals(path.getClass(), PathItem.class); //we successfully converted the RefPath to a Path

    final List<Parameter> parameters = path.getParameters();
    assertParamDetails(parameters, 0, QueryParameter.class, "param1", "query");
    assertParamDetails(parameters, 1, HeaderParameter.class, "param2", "header");

    final Operation operation = path.getGet();
    final List<Parameter> operationParams = operation.getParameters();
    assertParamDetails(operationParams, 0, PathParameter.class, "param3", "path");
    assertParamDetails(operationParams, 1, HeaderParameter.class, "param4", "header");

    final Map<String, ApiResponse> responsesMap = operation.getResponses();

    assertResponse(openAPI, responsesMap, "200","application/json", "Health information from the server", "#/components/schemas/health");
    assertResponse(openAPI, responsesMap, "400","*/*", "Your request was not valid", "#/components/schemas/error");
    assertResponse(openAPI, responsesMap, "500","*/*", "An unexpected error occur during processing", "#/components/schemas/error");

    final Map<String, Schema> definitions = openAPI.getComponents().getSchemas();
    final Schema refInDefinitions = definitions.get("refInDefinitions");
    assertEquals(refInDefinitions.getDescription(), "The example model");
    expectedPropertiesInModel(refInDefinitions, "foo", "bar");

    final ArraySchema arrayModel = (ArraySchema) definitions.get("arrayModel");
    final Schema arrayModelItems = arrayModel.getItems();
    assertEquals(arrayModelItems.get$ref(), "#/components/schemas/foo");

    final Schema fooModel = definitions.get("foo");
    assertEquals(fooModel.getDescription(), "Just another model");
    expectedPropertiesInModel(fooModel, "hello", "world");

    final ComposedSchema composedCat = (ComposedSchema) definitions.get("composedCat");
    final Schema child =  composedCat.getAllOf().get(2);
    expectedPropertiesInModel(child, "huntingSkill", "prop2", "reflexes", "reflexMap");
    final ArraySchema reflexes = (ArraySchema) child.getProperties().get("reflexes");
    final Schema reflexItems = reflexes.getItems();
    assertEquals(reflexItems.get$ref(), "#/components/schemas/reflex");
    assertTrue(definitions.containsKey(reflexItems.get$ref().substring(reflexItems.get$ref().lastIndexOf("/")+1)));

    final Schema reflexMap = (Schema) child.getProperties().get("reflexMap");
    final Schema reflexMapAdditionalProperties = (Schema) reflexMap.getAdditionalProperties();
    assertEquals(reflexMapAdditionalProperties.get$ref(), "#/components/schemas/reflex");

    assertEquals(composedCat.getAllOf().size(), 3);
    assertEquals(composedCat.getAllOf().get(0).get$ref(), "#/components/schemas/pet");
    assertEquals(composedCat.getAllOf().get(1).get$ref(), "#/components/schemas/foo_2");

    return openAPI;
}