Java Code Examples for io.swagger.v3.oas.models.media.Schema#setExample()

The following examples show how to use io.swagger.v3.oas.models.media.Schema#setExample() . 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: ExampleGenerator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private Object resolveModelToExample(String name, String mediaType, Schema schema, Set<String> processedModels) {
    if (processedModels.contains(name)) {
        return schema.getExample();
    }

    processedModels.add(name);
    Map<String, Object> values = new HashMap<>();
    LOGGER.debug("Resolving model '{}' to example", name);
    if (schema.getExample() != null) {
        LOGGER.debug("Using example from spec: {}", schema.getExample());
        return schema.getExample();
    } else if (schema.getProperties() != null) {
        LOGGER.debug("Creating example from model values");
        for (Object propertyName : schema.getProperties().keySet()) {
            Schema property = (Schema) schema.getProperties().get(propertyName.toString());
            values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, property, processedModels));
        }
        schema.setExample(values);
        return schema.getExample();
    } else {
        // TODO log an error message as the model does not have any properties
        return null;
    }
}
 
Example 2
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public void testInvalidExample(Schema property, String invalidValue, Object defaultValue, Object sampleValue ) throws Exception {
    property.setExample( invalidValue);

    Schema model = new Schema();
    model.addProperties("test", property);


    Map<String, Schema> definitions = new HashMap<>();
    definitions.put("Test", model);

    // validate that the internal default value is returned if an invalid value is set
    ObjectExample rep = (ObjectExample) ExampleBuilder.fromSchema(new Schema().$ref("Test"), definitions);
    AbstractExample example = (AbstractExample) rep.get( "test" );
    System.out.println(example);
    assertEquals( example.asString(), String.valueOf(defaultValue) );

    // validate that a specified default value is returned if an invalid value is set
    if( sampleValue != null ) {
        property.setDefault(String.valueOf(sampleValue));
        rep = (ObjectExample) ExampleBuilder.fromSchema(new Schema().$ref("Test"), definitions);
        example = (AbstractExample) rep.get("test");
        assertEquals(String.valueOf(sampleValue), example.asString());
    }
}
 
Example 3
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexArray() throws Exception {
    Map<String, Schema> definitions = new HashMap<>();

    Schema address = new Schema()
            .xml(new XML().name("address"));

    Schema propertyDefinition1 = new StringSchema();
    propertyDefinition1.setName("street");
    propertyDefinition1.setExample("12345 El Monte Blvd");

    Schema propertyDefinition2 = new StringSchema();
    propertyDefinition2.setName("city");
    propertyDefinition2.setExample("Los Altos Hills");

    Schema propertyDefinition3 = new StringSchema();
    propertyDefinition3.setName("state");
    propertyDefinition3.setExample("CA");
    propertyDefinition3.setMinLength(2);
    propertyDefinition3.setMaxLength(2);

    Schema propertyDefinition4 = new StringSchema();
    propertyDefinition4.setName("zip");
    propertyDefinition4.setExample("94022");

    address.addProperties("street",propertyDefinition1);
    address.addProperties("city",propertyDefinition2);
    address.addProperties("state",propertyDefinition3);
    address.addProperties("zip",propertyDefinition4);

    definitions.put("Address", address);

    Example rep = (Example) ExampleBuilder.fromSchema(new ArraySchema().$ref("Address"), definitions);

    String json = Json.pretty(rep);

    assertEqualsIgnoreLineEnding(json,"{\n  \"street\" : \"12345 El Monte Blvd\",\n  \"city\" : \"Los Altos Hills\",\n  \"state\" : \"CA\",\n  \"zip\" : \"94022\"\n}");
}
 
Example 4
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
/**
 * This function fix models that are string (mostly enum). Before this fix, the example
 * would look something like that in the doc: "\"example from def\""
 * @param m Model implementation
 */
private void fixStringModel(Schema m) {
    if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) {
        String example = m.getExample().toString();
        if (example.substring(0, 1).equals("\"") &&
                example.substring(example.length() - 1).equals("\"")) {
            m.setExample(example.substring(1, example.length() - 1));
        }
    }
}
 
Example 5
Source File: AbstractApexCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public String toExampleValue(Schema p) {
    if (p == null) {
        return "";
    }

    Object obj = p.getExample();
    String example = obj == null ? "" : obj.toString();

    if (ModelUtils.isArraySchema(p)) {
        example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
                ((ArraySchema) p).getItems()) + "}";
    } else if (ModelUtils.isBooleanSchema(p)) {
        example = String.valueOf(!"false".equals(example));
    } else if (ModelUtils.isByteArraySchema(p)) {
        if (example.isEmpty()) {
            example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
        }
        p.setExample(example);
        example = "EncodingUtil.base64Decode('" + example + "')";
    } else if (ModelUtils.isDateSchema(p)) {
        if (example.matches("^\\d{4}(-\\d{2}){2}")) {
            example = example.substring(0, 10).replaceAll("-0?", ", ");
        } else if (example.isEmpty()) {
            example = "2000, 1, 23";
        } else {
            LOGGER.warn(String.format(Locale.ROOT, "The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p
                    .getName(), example));
            example = "2000, 1, 23";
        }
        example = "Date.newInstance(" + example + ")";
    } else if (ModelUtils.isDateTimeSchema(p)) {
        if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
            example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
        } else if (example.isEmpty()) {
            example = "2000, 1, 23, 4, 56, 7";
        } else {
            LOGGER.warn(String.format(Locale.ROOT, "The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p
                    .getName(), example));
            example = "2000, 1, 23, 4, 56, 7";
        }
        example = "Datetime.newInstanceGmt(" + example + ")";
    } else if (ModelUtils.isNumberSchema(p)) {
        example = example.replaceAll("[^-0-9.]", "");
        example = example.isEmpty() ? "1.3579" : example;
    } else if (ModelUtils.isFileSchema(p)) {
        if (example.isEmpty()) {
            example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
            p.setExample(example);
        }
        example = "EncodingUtil.base64Decode(" + example + ")";
    } else if (ModelUtils.isEmailSchema(p)) {
        if (example.isEmpty()) {
            example = "[email protected]";
            p.setExample(example);
        }
        example = "'" + example + "'";
    } else if (ModelUtils.isLongSchema(p)) {
        example = example.isEmpty() ? "123456789L" : example + "L";
    } else if (ModelUtils.isMapSchema(p)) {
        example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(getAdditionalProperties(p)) + "}";

    } else if (ModelUtils.isPasswordSchema(p)) {
        example = example.isEmpty() ? "password123" : escapeText(example);
        p.setExample(example);
        example = "'" + example + "'";
    } else if (ModelUtils.isStringSchema(p)) {
        List<String> enums = p.getEnum();
        if (enums != null && example.isEmpty()) {
            example = enums.get(0);
            p.setExample(example);
        } else if (example.isEmpty()) {
            example = "";
        } else {
            example = escapeText(example);
            p.setExample(example);
        }
        example = "'" + example + "'";
    } else if (ModelUtils.isUUIDSchema(p)) {
        example = example.isEmpty()
                ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
                : "'" + escapeText(example) + "'";
    } else if (ModelUtils.isIntegerSchema(p)) {
        example = example.matches("^-?\\d+$") ? example : "0";
    } else if (ModelUtils.isObjectSchema(p)) {
        example = example.isEmpty() ? "null" : example;
    } else {
        example = getTypeDeclaration(p) + ".getExample()";
    }
    return example;
}
 
Example 6
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Schema mergeSchema(Schema thisSchema, Schema thatSchema) {
  if (thatSchema == null) {
    return thisSchema;
  }
  // Overwriting `implementation` is explicitly disallowed
  // Overwriting `not` is explicitly disallowed
  // Overwriting `oneOf` is explicitly disallowed
  // Overwriting `anyOf` is explicitly disallowed
  // Overwriting `allOf` is explicitly disallowed
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getTitle() != null) {
    thisSchema.setTitle(thatSchema.getTitle());
  }
  // Overwriting `multipleOf` is explicitly disallowed
  if (thatSchema.getMaximum() != null) {
    thisSchema.setMaximum(thatSchema.getMaximum());
  }
  if (thatSchema.getExclusiveMaximum() != null) {
    thisSchema.setExclusiveMaximum(thatSchema.getExclusiveMaximum());
  }

  if (thatSchema.getMinimum() != null) {
    thisSchema.setMinimum(thatSchema.getMinimum());
  }
  if (thatSchema.getExclusiveMinimum() != null) {
    thisSchema.setExclusiveMinimum(thatSchema.getExclusiveMinimum());
  }
  if (thatSchema.getMaxLength() != null) {
    thisSchema.setMaxLength(thatSchema.getMaxLength());
  }
  if (thatSchema.getMinLength() != null) {
    thisSchema.setMinLength(thatSchema.getMinLength());
  }
  if (thatSchema.getPattern() != null) {
    thisSchema.setPattern(thatSchema.getPattern());
  }
  if (thatSchema.getMaxProperties() != null) {
    thisSchema.setMaxProperties(thatSchema.getMaxProperties());
  }
  if (thatSchema.getMinProperties() != null) {
    thisSchema.setMinProperties(thatSchema.getMinProperties());
  }
  // RequiredProperties
  if (thatSchema.getRequired() != null) {
    thisSchema.setRequired(thatSchema.getRequired());
  }
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getDescription() != null) {
    thisSchema.setDescription(thatSchema.getDescription());
  }
  if (thatSchema.getFormat() != null) {
    thisSchema.setFormat(thatSchema.getFormat());
  }
  // Overwriting `ref` is explicitly disallowed
  if (thatSchema.getNullable() != null) {
    thisSchema.setNullable(thatSchema.getNullable());
  }
  // Overwriting `AccessMode` is explicitly disallowed
  if (thatSchema.getExample() != null) {
    thisSchema.setExample(thatSchema.getExample());
  }
  if (thatSchema.getExternalDocs() != null) {
    thisSchema.setExternalDocs(thatSchema.getExternalDocs());
  }
  if (thatSchema.getDeprecated() != null) {
    thisSchema.setDeprecated(thatSchema.getDeprecated());
  }
  if (thatSchema.getType() != null) {
    thisSchema.setType(thatSchema.getType());
  }
  if (thatSchema.getEnum() != null) {
    thisSchema.setEnum(thatSchema.getEnum());
  }
  if (thatSchema.getDefault() != null) {
    thisSchema.setDefault(thatSchema.getDefault());
  }
  // Overwriting `discriminator` is explicitly disallowed
  // Overwriting `hidden` is explicitly disallowed
  // Overwriting `subTypes` is explicitly disallowed
  if (thatSchema.getExtensions() != null) {
    thisSchema.setExtensions(thatSchema.getExtensions());
  }
  return thisSchema;
}
 
Example 7
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
@Test
public void testXmlJackson() throws Exception {
    Schema model = new Schema()
            .xml(new XML()
                    .name("user"));

    Schema property1 = new StringSchema();
    property1.setName("username");
    property1.setExample("fehguy");
    property1.setXml(new XML()
            .name("userName"));

    ArraySchema property2 = new ArraySchema();
    property2.setName("addresses");
    property2.setXml(new XML().wrapped(true));
    property2.setItems(new Schema().$ref("Address"));
    Schema property3 = new Schema();
    property3.setName("managers");
    property3.setAdditionalProperties(new StringSchema().example("SVP Engineering"));
    ArraySchema property4 = new ArraySchema();
    property4.setName("kidsAges");
    property4.setItems(new IntegerSchema().example(9));

    model.addProperties("username",property1);
    model.addProperties("addresses",property2);
    model.addProperties("managers",property3);
    model.addProperties("kidsAges",property4);

    Map<String, Schema> definitions = new HashMap<>();
    definitions.put("User", model);

    Schema address = new Schema()
            .xml(new XML().name("address"));

    Schema propertyDefinition1 = new StringSchema();
    propertyDefinition1.setName("street");
    propertyDefinition1.setExample("12345 El Monte Blvd");

    Schema propertyDefinition2 = new StringSchema();
    propertyDefinition2.setName("city");
    propertyDefinition2.setExample("Los Altos Hills");

    Schema propertyDefinition3 = new StringSchema();
    propertyDefinition3.setName("state");
    propertyDefinition3.setExample("CA");
    propertyDefinition3.setMinLength(2);
    propertyDefinition3.setMaxLength(2);

    Schema propertyDefinition4 = new StringSchema();
    propertyDefinition4.setName("zip");
    propertyDefinition4.setExample("94022");

    address.addProperties("street",propertyDefinition1);
    address.addProperties("city",propertyDefinition2);
    address.addProperties("state",propertyDefinition3);
    address.addProperties("zip",propertyDefinition4);

    definitions.put("Address", address);

    Example rep = ExampleBuilder.fromSchema(new Schema().$ref("User"), definitions);

    String xmlString = new XmlExampleSerializer().serialize(rep);
    assertEqualsIgnoreLineEnding(xmlString, "<?xml version='1.1' encoding='UTF-8'?><user><userName>fehguy</userName><addressess><address><street>12345 El Monte Blvd</street><city>Los Altos Hills</city><state>CA</state><zip>94022</zip></address></addressess><managers><additionalProp1>SVP Engineering</additionalProp1><additionalProp2>SVP Engineering</additionalProp2><additionalProp3>SVP Engineering</additionalProp3></managers><kidsAges>9</kidsAges></user>");
    assertEqualsIgnoreLineEnding(Yaml.pretty().writeValueAsString(rep),"username: fehguy\naddresses:\n- street: 12345 El Monte Blvd\n  city: Los Altos Hills\n  state: CA\n  zip: \"94022\"\nmanagers:\n  additionalProp1: SVP Engineering\n  additionalProp2: SVP Engineering\n  additionalProp3: SVP Engineering\nkidsAges:\n- 9\n");
}
 
Example 8
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
@Test
public void testComplexArrayWithExample() throws Exception {
    Map<String, Schema> definitions = new HashMap<>();

    Schema address = new Schema()
      .example("{\"foo\":\"bar\"}")
      .xml(new XML()
        .name("address"));

    Schema propertyDefinition1 = new StringSchema();
    propertyDefinition1.setName("street");
    propertyDefinition1.setExample("12345 El Monte Blvd");

    Schema propertyDefinition2 = new StringSchema();
    propertyDefinition2.setName("city");
    propertyDefinition2.setExample("Los Altos Hills");

    Schema propertyDefinition3 = new StringSchema();
    propertyDefinition3.setName("state");
    propertyDefinition3.setExample("CA");
    propertyDefinition3.setMinLength(2);
    propertyDefinition3.setMaxLength(2);

    Schema propertyDefinition4 = new StringSchema();
    propertyDefinition4.setName("zip");
    propertyDefinition4.setExample("94022");

    address.addProperties("street",propertyDefinition1);
    address.addProperties("city",propertyDefinition2);
    address.addProperties("state",propertyDefinition3);
    address.addProperties("zip",propertyDefinition4);


    definitions.put("Address", address);

    // register the JSON serializer
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new JsonNodeExampleSerializer());
    simpleModule.addDeserializer(Example.class, new JsonExampleDeserializer());
    Json.mapper().registerModule(simpleModule);

    Example rep = (Example) ExampleBuilder.fromSchema(new StringSchema().addEnumItem("hello").example("fun"), definitions);
    assertEqualsIgnoreLineEnding(Json.pretty(rep), "\"fun\"");
}
 
Example 9
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public Schema createModelFromProperty(Schema schema, String path) {
    String description = schema.getDescription();
    String example = null;
    List<String> requiredList = schema.getRequired();


    Object obj = schema.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    String name = schema.getName();
    XML xml = schema.getXml();
    Map<String, Schema> properties = schema.getProperties();


    if (schema instanceof ComposedSchema && this.flattenComposedSchemas){
        ComposedSchema composedModel = (ComposedSchema) schema;

        composedModel.setDescription(description);
        composedModel.setExample(example);
        composedModel.setName(name);
        composedModel.setXml(xml);
        composedModel.setType(schema.getType());
        composedModel.setRequired(requiredList);

        return composedModel;


    } else {
        Schema model = new Schema();//TODO Verify this!
        model.setDescription(description);
        model.setExample(example);
        model.setName(name);
        model.setXml(xml);
        model.setType(schema.getType());
        model.setRequired(requiredList);

        if (properties != null) {
            flattenProperties(properties, path);
            model.setProperties(properties);
        }

        return model;
    }
}