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

The following examples show how to use io.swagger.v3.oas.models.media.Schema#getExample() . 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: DataGenerator.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
public String generateValue(String name, Schema<?> schema, boolean isPath) {
    String value = "";
    if (schema.getExample() != null) {
        value = schema.getExample().toString();
    } else if (isEnumValue(schema)) {
        value = getEnumValue(schema);
    } else if (isDateTime(schema)) {
        value = "1970-01-01T00:00:00.001Z";
    } else if (isDate(schema)) {
        value = "1970-01-01";
    }

    value = generators.getValueGenerator().getValue(name, schema.getType(), value);

    if (value.isEmpty()) {
        value = getExampleValue(isPath, schema.getType(), name);
    } else {
        if (!isPath && "string".equalsIgnoreCase(schema.getType())) {
            value = "\"" + value + "\"";
        }
    }
    if (value == null || value.isEmpty()) {
        value = generators.getBodyGenerator().generate(schema);
    }
    return value;
}
 
Example 3
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-method")
public Schema modelFromProperty(Schema object, @SuppressWarnings("unused") String path) {
    String description = object.getDescription();
    String example = null;

    Object obj = object.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    ArraySchema model = new ArraySchema();
    model.setDescription(description);
    model.setExample(example);
    if (object.getAdditionalProperties() != null && !(object.getAdditionalProperties() instanceof Boolean)) {
        model.setItems((Schema)  object.getAdditionalProperties());
    }
    return model;
}
 
Example 4
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testComposedSchemaAdjacentWithExamples(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/anyOf_OneOf.yaml", auths, options);

    Assert.assertNotNull(openAPI);

    Assert.assertTrue(openAPI.getComponents().getSchemas().size() == 2);

    Schema schemaPath = openAPI.getPaths().get("/path").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schemaPath instanceof Schema);
    Assert.assertTrue(schemaPath.getProperties().size() == 5);
    Assert.assertTrue(schemaPath.getExample() instanceof HashSet);
    Set<Object> examples = (HashSet) schemaPath.getExample();
    Assert.assertTrue(examples.size() == 2);
}
 
Example 5
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String toExampleValue(Schema p) {
    if (p.getExample() != null) {
        return escapeText(p.getExample().toString());
    } else {
        return null;
    }
}
 
Example 6
Source File: AbstractCSharpCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Return the example value of the property
 *
 * @param p OpenAPI property object
 * @return string presentation of the example value of the property
 */
@Override
public String toExampleValue(Schema p) {
    if (ModelUtils.isStringSchema(p)) {
        if (p.getExample() != null) {
            return "\"" + p.getExample().toString() + "\"";
        }
    } else if (ModelUtils.isBooleanSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    } else if (ModelUtils.isDateSchema(p)) {
        // TODO
    } else if (ModelUtils.isDateTimeSchema(p)) {
        // TODO
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    }

    return null;
}
 
Example 7
Source File: AbstractFSharpCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Return the example value of the property
 *
 * @param p OpenAPI property object
 * @return string presentation of the example value of the property
 */
@Override
public String toExampleValue(Schema p) {
    if (ModelUtils.isStringSchema(p)) {
        if (p.getExample() != null) {
            return "\"" + p.getExample().toString() + "\"";
        }
    } else if (ModelUtils.isBooleanSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    } else if (ModelUtils.isDateSchema(p)) {
        // TODO
    } else if (ModelUtils.isDateTimeSchema(p)) {
        // TODO
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getExample() != null) {
            return p.getExample().toString();
        }
    }

    return null;
}
 
Example 8
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 9
Source File: XmlExampleGenerator.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Get the example string value for the given schema.
 *
 * If an example value was not provided in the specification, a default will be generated.
 *
 * @param schema Schema to get example string for
 * @return Example String
 */
protected String getExample(Schema schema) {
    if (schema.getExample() != null) {
        return schema.getExample().toString();
    } else if (ModelUtils.isDateTimeSchema(schema)) {
        return "2000-01-23T04:56:07.000Z";
    } else if (ModelUtils.isDateSchema(schema)) {
        return "2000-01-23";
    } else if (ModelUtils.isBooleanSchema(schema)) {
        return "true";
    } else if (ModelUtils.isNumberSchema(schema)) {
        if (ModelUtils.isFloatSchema(schema)) { // float
            return "1.3579";
        } else { // double
            return "3.149";
        }
    } else if (ModelUtils.isPasswordSchema(schema)) {
        return "********";
    } else if (ModelUtils.isUUIDSchema(schema)) {
        return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
    } else if (ModelUtils.isURISchema(schema)) {
        return "https://openapi-generator.tech";
        // do these last in case the specific types above are derived from these classes
    } else if (ModelUtils.isStringSchema(schema)) {
        return "aeiou";
    } else if (ModelUtils.isIntegerSchema(schema)) {
        if (ModelUtils.isLongSchema(schema)) { // long
            return "123456789";
        } else { //integer
            return "123";
        }
    } else {
        LOGGER.debug("default example value not implemented for {}. Default to UNDEFINED_EXAMPLE_VALUE", schema);
        return "UNDEFINED_EXAMPLE_VALUE";
    }
}
 
Example 10
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 11
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 12
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 13
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;
    }
}