下面列出了com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat#com.fasterxml.jackson.module.jsonSchema.JsonSchema 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 完善JsonSchema信息 */
private static void completeJsonSchema(JsonSchema schema,
MetaProperty property) {
schema.setDescription(property.getLabel());
if (property.isReadOnly()) {
schema.setReadonly(true);
}
if (property.isNotNull()) {
schema.setRequired(true);
}
if (MetaConstant.isEnum(property)
&& schema instanceof ValueTypeSchema) {
Set<String> enums = new HashSet<>();
for (EnumItem item : property.getEnumList()) {
enums.add(item.getValue());
}
((ValueTypeSchema) schema).setEnums(enums);
}
}
/** 根据schema转换 */
public static Object convert(Object src, JsonSchema schema,
boolean checkReadOnly, boolean ignoreException, String path) {
if (src == null) {
return null;
}
if (schema.isArraySchema()) {
return convertArray(src, schema.asArraySchema(), checkReadOnly,
ignoreException, path);
} else if (schema.isObjectSchema()) {
return convertObject(src, schema.asObjectSchema(), checkReadOnly,
ignoreException, path);
} else if (schema.isBooleanSchema()) {
return TypeUtil.cast(src, Boolean.class);
} else if (schema.isIntegerSchema()) {
return TypeUtil.cast(src, Long.class);
} else if (schema.isNumberSchema()) {
return TypeUtil.cast(src, Double.class);
} else if (schema.isStringSchema()) {
return TypeUtil.cast(src, String.class);
} else if (schema.isNullSchema()) {
return null;
} else {
return src;
}
}
/** 根据schema转换 */
private static Object convertArrayItem(Object src, Items items,
boolean checkReadOnly, boolean ignoreException, String path) {
if (src == null) {
return null;
}
if (items.isSingleItems()) {
JsonSchema schema = items.asSingleItems().getSchema();
if (schema == null) {
return src;
}
return convert(src, schema, checkReadOnly, ignoreException, path);
} else if (items.isArrayItems()) {
return src;
} else {
return src;
}
}
/** 完善JsonSchema信息 */
private static void completeJsonSchema(JsonSchema schema,
MetaProperty property) {
schema.setDescription(property.getLabel());
if (property.isReadOnly()) {
schema.setReadonly(true);
}
if (property.isNotNull()) {
schema.setRequired(true);
}
if (MetaConstant.isEnum(property)
&& schema instanceof ValueTypeSchema) {
Set<String> enums = new HashSet<>();
for (EnumItem item : property.getEnumList()) {
enums.add(item.getValue());
}
((ValueTypeSchema) schema).setEnums(enums);
}
}
/** 根据schema转换 */
public static Object convert(Object src, JsonSchema schema,
boolean checkReadOnly, boolean ignoreException, String path) {
if (src == null) {
return null;
}
if (schema.isArraySchema()) {
return convertArray(src, schema.asArraySchema(), checkReadOnly,
ignoreException, path);
} else if (schema.isObjectSchema()) {
return convertObject(src, schema.asObjectSchema(), checkReadOnly,
ignoreException, path);
} else if (schema.isBooleanSchema()) {
return TypeUtil.cast(src, Boolean.class);
} else if (schema.isIntegerSchema()) {
return TypeUtil.cast(src, Long.class);
} else if (schema.isNumberSchema()) {
return TypeUtil.cast(src, Double.class);
} else if (schema.isStringSchema()) {
return TypeUtil.cast(src, String.class);
} else if (schema.isNullSchema()) {
return null;
} else {
return src;
}
}
/** 根据schema转换 */
private static Object convertArrayItem(Object src, Items items,
boolean checkReadOnly, boolean ignoreException, String path) {
if (src == null) {
return null;
}
if (items.isSingleItems()) {
JsonSchema schema = items.asSingleItems().getSchema();
if (schema == null) {
return src;
}
return convert(src, schema, checkReadOnly, ignoreException, path);
} else if (items.isArrayItems()) {
return src;
} else {
return src;
}
}
@Test
public void shouldMapValuesFromMessageHeaders() throws Exception {
String schemaStr = JsonUtils.writer().forType(JsonSchema.class).writeValueAsString(schema);
JsonNode schemaNode = JsonUtils.reader().forType(JsonNode.class).readTree(schemaStr);
final HttpRequestWrapperProcessor processor = new HttpRequestWrapperProcessor(schemaNode);
final Exchange exchange = mock(Exchange.class);
final Message message = mock(Message.class);
final ExtendedCamelContext camelContext = mock(ExtendedCamelContext.class);
when(camelContext.adapt(ExtendedCamelContext.class)).thenReturn(camelContext);
when(camelContext.getHeadersMapFactory()).thenReturn(mock(HeadersMapFactory.class));
when(exchange.getIn()).thenReturn(message);
when(exchange.getContext()).thenReturn(camelContext);
when(message.getBody()).thenReturn(givenBody);
when(message.getHeader("param1", String[].class)).thenReturn(new String[] {"param_value1"});
when(message.getHeader("param2", String[].class)).thenReturn(new String[] {"param_value2_1", "param_value2_2"});
processor.process(exchange);
final ArgumentCaptor<Message> replacement = ArgumentCaptor.forClass(Message.class);
verify(exchange).setIn(replacement.capture());
assertThat(replacement.getValue().getBody()).isEqualTo(replacedBody);
}
@Test
public void shouldMapValuesFromHttpRequest() throws Exception {
final String schemaStr = JsonUtils.writer().forType(JsonSchema.class).writeValueAsString(schema);
final JsonNode schemaNode = JsonUtils.reader().forType(JsonNode.class).readTree(schemaStr);
final HttpRequestWrapperProcessor processor = new HttpRequestWrapperProcessor(schemaNode);
final Exchange exchange = mock(Exchange.class);
final Message message = mock(Message.class);
final ExtendedCamelContext camelContext = mock(ExtendedCamelContext.class);
when(camelContext.adapt(ExtendedCamelContext.class)).thenReturn(camelContext);
when(camelContext.getHeadersMapFactory()).thenReturn(mock(HeadersMapFactory.class));
when(exchange.getIn()).thenReturn(message);
when(exchange.getContext()).thenReturn(camelContext);
final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
when(message.getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class)).thenReturn(servletRequest);
when(message.getBody()).thenReturn(givenBody);
when(servletRequest.getParameterValues("param1")).thenReturn(new String[] {"param_value1"});
when(servletRequest.getParameterValues("param2")).thenReturn(new String[] {"param_value2_1", "param_value2_2"});
processor.process(exchange);
final ArgumentCaptor<Message> replacement = ArgumentCaptor.forClass(Message.class);
verify(exchange).setIn(replacement.capture());
assertThat(replacement.getValue().getBody()).isEqualTo(replacedBody);
}
private static Map<String, JsonSchema> checkShape(DataShape dataShape, Class<? extends ContainerTypeSchema> expectedShapeClass) throws IOException, JsonParseException, JsonMappingException {
assertNotNull(dataShape);
assertEquals(DataShapeKinds.JSON_SCHEMA, dataShape.getKind());
assertNotNull(dataShape.getSpecification());
ContainerTypeSchema schema = JsonUtils.copyObjectMapperConfiguration().readValue(
dataShape.getSpecification(), expectedShapeClass);
Map<String, JsonSchema> propSchemaMap = null;
if (schema instanceof ArraySchema) {
propSchemaMap = ((ArraySchema) schema).getItems().asSingleItems().getSchema().asObjectSchema().getProperties();
} else if (schema instanceof ObjectSchema) {
propSchemaMap = ((ObjectSchema) schema).getProperties();
}
assertNotNull(propSchemaMap);
return propSchemaMap;
}
private static void checkTestServerSchemaMap(Map<String, JsonSchema> schemaMap) {
JsonSchema descSchema = schemaMap.get("Description");
JsonSchema specSchema = schemaMap.get("Specification");
assertNotNull(descSchema);
assertNotNull(schemaMap.get("ID"));
assertNotNull(schemaMap.get("Name"));
assertNotNull(specSchema);
JsonFormatTypes descType = descSchema.getType();
assertNotNull(descType);
assertEquals(JsonFormatTypes.STRING, descType);
assertEquals(false, descSchema.getRequired());
JsonFormatTypes specType = specSchema.getType();
assertNotNull(specType);
assertEquals(JsonFormatTypes.OBJECT, specType);
assertEquals(false, specSchema.getRequired());
assertThat(specSchema).isInstanceOf(ObjectSchema.class);
ObjectSchema specObjSchema = specSchema.asObjectSchema();
assertEquals(4, specObjSchema.getProperties().size());
}
public static JsonSchema createSchema(String range, String majorDimension, boolean split, String ... columnNames) {
ObjectSchema spec = new ObjectSchema();
spec.setTitle("VALUE_RANGE");
spec.putProperty("spreadsheetId", new JsonSchemaFactory().stringSchema());
RangeCoordinate coordinate = RangeCoordinate.fromRange(range);
if (ObjectHelper.equal(RangeCoordinate.DIMENSION_ROWS, majorDimension)) {
createSchemaFromRowDimension(spec, coordinate, columnNames);
} else if (ObjectHelper.equal(RangeCoordinate.DIMENSION_COLUMNS, majorDimension)) {
createSchemaFromColumnDimension(spec, coordinate);
}
if (split) {
spec.set$schema(JSON_SCHEMA_ORG_SCHEMA);
return spec;
} else {
ArraySchema arraySpec = new ArraySchema();
arraySpec.set$schema(JSON_SCHEMA_ORG_SCHEMA);
arraySpec.setItemsSchema(spec);
return arraySpec;
}
}
public SalesforceMetadataRetrievalTest() {
final Map<String, JsonSchema> objectProperties = new HashMap<>();
objectProperties.put("simpleProperty", new StringSchema());
objectProperties.put("anotherProperty", new NumberSchema());
final StringSchema uniqueProperty1 = new StringSchema();
uniqueProperty1.setDescription("idLookup,autoNumber");
uniqueProperty1.setTitle("Unique property 1");
final StringSchema uniqueProperty2 = new StringSchema();
uniqueProperty2.setDescription("calculated,idLookup");
uniqueProperty2.setTitle("Unique property 2");
objectProperties.put("uniqueProperty1", uniqueProperty1);
objectProperties.put("uniqueProperty2", uniqueProperty2);
final ObjectSchema objectSchema = new ObjectSchema();
objectSchema.setId("urn:jsonschema:org:apache:camel:component:salesforce:dto:SimpleObject");
objectSchema.setProperties(objectProperties);
payload = new ObjectSchema();
payload.setOneOf(Collections.singleton(objectSchema));
}
static void fetchPaths(final String context, final List<String> paths, final Map<String, JsonSchema> properties) {
for (final Map.Entry<String, JsonSchema> entry : properties.entrySet()) {
final JsonSchema subschema = entry.getValue();
String path;
final String key = entry.getKey();
if (context == null) {
path = key;
} else {
path = context + "." + key;
}
if (subschema.isValueTypeSchema()) {
paths.add(path);
} else if (subschema.isObjectSchema()) {
fetchPaths(path, paths, subschema.asObjectSchema().getProperties());
} else if (subschema.isArraySchema()) {
COLLECTION_PATHS.stream().map(p -> path + "." + p).forEach(paths::add);
ObjectSchema itemSchema = getItemSchema(subschema.asArraySchema());
if (itemSchema != null) {
fetchPaths(path + ARRAY_CONTEXT, paths, itemSchema.getProperties());
}
}
}
}
/**
* Converts unified Json body specification. Unified Json schema specifications hold
* the actual body specification in a property. This method converts this body specification
* from array to single element if necessary.
*/
private static String adaptUnifiedJsonBodySpecToSingleElement(String specification) throws IOException {
JsonSchema schema = JsonSchemaUtils.reader().readValue(specification);
if (schema.isObjectSchema()) {
JsonSchema bodySchema = schema.asObjectSchema().getProperties().get(BODY);
if (bodySchema != null && bodySchema.isArraySchema()) {
ArraySchema.Items items = bodySchema.asArraySchema().getItems();
if (items.isSingleItems()) {
schema.asObjectSchema().getProperties().put(BODY, items.asSingleItems().getSchema());
return JsonUtils.writer().writeValueAsString(schema);
}
}
}
return specification;
}
/**
* Converts unified Json body specification. Unified Json schema specifications hold
* the actual body specification in a property. This method converts this body specification
* from single element to collection if necessary.
*/
private static String adaptUnifiedJsonBodySpecToCollection(String specification) throws IOException {
JsonSchema schema = JsonSchemaUtils.reader().readValue(specification);
if (schema.isObjectSchema()) {
JsonSchema bodySchema = schema.asObjectSchema().getProperties().get(BODY);
if (bodySchema != null && bodySchema.isObjectSchema()) {
ArraySchema arraySchema = new ArraySchema();
arraySchema.set$schema(JSON_SCHEMA_ORG_SCHEMA);
arraySchema.setItemsSchema(bodySchema);
schema.asObjectSchema().getProperties().put(BODY, arraySchema);
return JsonUtils.writer().writeValueAsString(schema);
}
}
return specification;
}
/**
* Extract unified Json body specification from data shape specification. Unified Json schema specifications hold
* the actual body specification in a property. This method extracts this property as new body specification.
*/
private static String extractUnifiedJsonBodySpec(String specification) throws IOException {
JsonSchema schema = JsonSchemaUtils.reader().readValue(specification);
if (schema.isObjectSchema()) {
JsonSchema bodySchema = schema.asObjectSchema().getProperties().get("body");
if (bodySchema != null) {
if (bodySchema.isArraySchema()) {
ArraySchema.Items items = bodySchema.asArraySchema().getItems();
if (items.isSingleItems()) {
JsonSchema itemSchema = items.asSingleItems().getSchema();
itemSchema.set$schema(schema.get$schema());
return JsonUtils.writer().writeValueAsString(itemSchema);
}
} else {
return JsonUtils.writer().writeValueAsString(bodySchema);
}
}
}
return specification;
}
/**
* This method creates a copy of the default ObjectMapper configuration and adds special Json schema compatibility handlers
* for supporting draft-03, draft-04 and draft-06 level at the same time.
*
* Auto converts "$id" to "id" property for draft-04 compatibility.
*
* In case the provided schema specification to read uses draft-04 and draft-06 specific features such as "examples" or a list of "required"
* properties as array these information is more or less lost and auto converted to draft-03 compatible defaults. This way we can
* read the specification to draft-03 compatible objects and use those.
* @return duplicated ObjectR
*/
public static ObjectReader reader() {
return JsonUtils.copyObjectMapperConfiguration()
.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleUnexpectedToken(DeserializationContext ctxt, Class<?> targetType, JsonToken t,
JsonParser p, String failureMsg) throws IOException {
if (t == JsonToken.START_ARRAY && targetType.equals(Boolean.class)) {
// handle Json schema draft-04 array type for required field and resolve to default value (required=true).
String[] requiredProps = new StringArrayDeserializer().deserialize(p, ctxt);
LOG.warn("Auto convert Json schema draft-04 \"required\" array value '{}' to default \"required=false\" value for draft-03 parser compatibility reasons", Arrays.toString(requiredProps));
return null;
}
return super.handleUnexpectedToken(ctxt, ctxt.constructType(targetType), t, p, failureMsg);
}
})
.addMixIn(JsonSchema.class, MixIn.Draft6.class)
.reader()
.forType(JsonSchema.class);
}
@Override
public void customizeSchema(BeanProperty property, JsonSchema jsonschema) {
Optional.ofNullable(property.getAnnotation(Password.class)).ifPresent(annotation -> {
if (annotation.title() != null) {
((StringSchema) jsonschema).setTitle(annotation.title());
}
if (annotation.pattern() != null) {
((StringSchema) jsonschema).setPattern(annotation.pattern());
}
if (annotation.minLenght() != 0) {
((StringSchema) jsonschema).setMinLength(annotation.minLenght());
}
if (annotation.maxLenght() != Integer.MAX_VALUE) {
((StringSchema) jsonschema).setMaxLength(annotation.maxLenght());
}
});
}
@Override
public void customizeSchema(BeanProperty property, JsonSchema jsonschema) {
TextField annotation = property.getAnnotation(TextField.class);
if (annotation != null) {
if (annotation.title() != null) {
((StringSchema) jsonschema).setTitle(annotation.title());
}
if (annotation.pattern() != null) {
((StringSchema) jsonschema).setPattern(annotation.pattern());
}
if (annotation.minLenght() != 0) {
((StringSchema) jsonschema).setMinLength(annotation.minLenght());
}
if (annotation.maxLenght() != Integer.MAX_VALUE) {
((StringSchema) jsonschema).setMaxLength(annotation.maxLenght());
}
}
}
private void findRefs(JsonSchema schema, Map<String, JsonSchema> refs, Set<String> referenced) {
addRef(schema, refs);
if (schema instanceof ReferenceSchema) {
referenced.add(schema.get$ref());
} else if (schema.isArraySchema()) {
ArraySchema as = schema.asArraySchema();
if (as.getItems() != null) {
if (as.getItems().isSingleItems()) {
findRefs(as.getItems().asSingleItems().getSchema(), refs, referenced);
} else if (as.getItems().isArrayItems()) {
ArrayItems items = as.getItems().asArrayItems();
for (JsonSchema item : items.getJsonSchemas()) {
findRefs(item, refs, referenced);
}
} else {
throw new UnsupportedOperationException(as.getItems().toString());
}
}
} else if (schema.isObjectSchema()) {
ObjectSchema os = schema.asObjectSchema();
for (JsonSchema value : os.getProperties().values()) {
findRefs(value, refs, referenced);
}
}
}
private void objectExample(StringBuilder sb, int maxlength, String indent, JsonSchema schema,
Map<String, JsonSchema> refs, Set<String> followed, Set<String> referenced, String id) {
sb.append("{");
if (referenced.contains(id)) {
shortId(sb, schema);
}
ObjectSchema os = schema.asObjectSchema();
if (os.getProperties().isEmpty()) {
AdditionalProperties additionalProperties = os.getAdditionalProperties();
if (additionalProperties instanceof SchemaAdditionalProperties) {
sb.append("\n").append(indent).append(" ").append("abc").append(": ");
example(sb, maxlength, indent + " ", ((SchemaAdditionalProperties) additionalProperties).getJsonSchema(), refs, followed, referenced);
sb.append(", ...");
}
}
Map<String, JsonSchema> props = new TreeMap<>(os.getProperties());
for (Entry<String, JsonSchema> entry : props.entrySet()) {
sb.append("\n").append(indent).append(" ").append(entry.getKey()).append(": ");
example(sb, maxlength, indent + " ", entry.getValue(), refs, followed, referenced);
sb.append(",");
}
sb.append("\n").append(indent).append("}");
}
private void arrayExample(StringBuilder sb, int maxlength, String indent, JsonSchema schema,
Map<String, JsonSchema> refs, Set<String> followed, Set<String> referenced) {
sb.append("[\n").append(indent).append(" ");
ArraySchema as = schema.asArraySchema();
if (as.getItems() == null) {
sb.append(" ... ]");
} else if (as.getItems().isSingleItems()) {
example(sb, maxlength, indent + " ", as.getItems().asSingleItems().getSchema(), refs, followed, referenced);
sb.append(",\n").append(indent).append(" ...\n").append(indent).append("]");
} else if (as.getItems().isArrayItems()) {
ArrayItems items = as.getItems().asArrayItems();
for (JsonSchema item : items.getJsonSchemas()) {
sb.append("\n").append(indent);
example(sb, maxlength, indent + " ", item, refs, followed, referenced);
sb.append(",");
}
sb.append("]");
} else {
throw new UnsupportedOperationException(as.getItems().toString());
}
}
/**
* Implemented for backwards compatibility reasons
* since the original schema generated by JSONSchema was based off the json schema standard
* since then we have standardized on Avro
*
* @return
*/
public SchemaInfo getBackwardsCompatibleJsonSchemaInfo() {
SchemaInfo backwardsCompatibleSchemaInfo;
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(objectMapper);
JsonSchema jsonBackwardsCompatibleSchema = schemaGen.generateSchema(pojo);
backwardsCompatibleSchemaInfo = new SchemaInfo();
backwardsCompatibleSchemaInfo.setName("");
backwardsCompatibleSchemaInfo.setProperties(schemaInfo.getProperties());
backwardsCompatibleSchemaInfo.setType(SchemaType.JSON);
backwardsCompatibleSchemaInfo.setSchema(objectMapper.writeValueAsBytes(jsonBackwardsCompatibleSchema));
} catch (JsonProcessingException ex) {
throw new RuntimeException(ex);
}
return backwardsCompatibleSchemaInfo;
}
@Test
public void testGetIdentitySchema() {
get(METADATA_IDENTITY_TYPE_SCHEMA_ENDPOINT, "foobar")
.assertStatus(Status.NOT_FOUND);
final JsonSchema schema =
get(METADATA_IDENTITY_TYPE_SCHEMA_ENDPOINT, "user")
.assertStatus(Status.OK)
.result(JsonSchema.class);
assertNotNull(schema);
assertTrue(
schema
.asObjectSchema()
.getProperties()
.get("name")
.isStringSchema()
);
}
@Override
public String generateSearchQueryInstructionJsonSchema() {
String jsonSchemaAsString = null;
try {
ObjectMapper mapper = getObjectMapper();
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(
mapper.constructType(SearchQueryInstruction.class), visitor);
JsonSchema schema = visitor.finalSchema();
jsonSchemaAsString = mapper.writeValueAsString(schema);
} catch (JsonProcessingException e) {
throw new RuntimeException("Error occured generating json schema!",
e);
}
return jsonSchemaAsString;
}
/** 数据字典转换成JsonSchema */
public static JsonSchema byEntity(String entityName) {
MetaEntity meta = Meta.getEntity(entityName);
if (meta == null) {
return null;
}
ObjectSchema root = new ObjectSchema();
root.setDescription(meta.getLabel());
for (MetaProperty property : meta.getProperties().values()) {
appendJsonSchema(root, property);
}
return root;
}
/** 解析字段,并追加到parent */
public static JsonSchema appendJsonSchema(ObjectSchema parent,
MetaProperty property) {
if (property.getShowType() == ShowType.NONE) {
return null;
}
JsonSchema schema = toJsonSchema(property);
if (property.isCollection()) {
ArraySchema array = new ArraySchema();
completeJsonSchema(array, property);
if (schema != null) {
array.setItems(new SingleItems(schema));
}
schema = array;
} else {
if (schema == null) {
return null;
}
completeJsonSchema(schema, property);
}
if (schema.getRequired() == null) {
parent.putOptionalProperty(property.getName(), schema);
} else {
parent.putProperty(property.getName(), schema);
}
return schema;
}
/** 数据字典转换成JsonSchema */
public static JsonSchema byEntity(String entityName) {
MetaEntity meta = Meta.getEntity(entityName);
if (meta == null) {
return null;
}
ObjectSchema root = new ObjectSchema();
root.setDescription(meta.getLabel());
for (MetaProperty property : meta.getProperties().values()) {
appendJsonSchema(root, property);
}
return root;
}
/** 解析字段,并追加到parent */
public static JsonSchema appendJsonSchema(ObjectSchema parent,
MetaProperty property) {
if (property.getShowType() == ShowType.NONE) {
return null;
}
JsonSchema schema = toJsonSchema(property);
if (property.isCollection()) {
ArraySchema array = new ArraySchema();
completeJsonSchema(array, property);
if (schema != null) {
array.setItems(new SingleItems(schema));
}
schema = array;
} else {
if (schema == null) {
return null;
}
completeJsonSchema(schema, property);
}
if (schema.getRequired() == null) {
parent.putOptionalProperty(property.getName(), schema);
} else {
parent.putProperty(property.getName(), schema);
}
return schema;
}
private String commandJsonSchema(String commandClassName) {
try {
JsonSchema commandSchema = jsonSchemaGenerator.generateSchema(classLoader.loadClass(commandClassName));
commandSchema.setId(null);
return objectMapper.writeValueAsString(commandSchema);
} catch (ClassNotFoundException | JsonProcessingException e) {
logger.error("Failed to instantiate command api for [{}]", commandClassName, e);
return String.format("{\n\tmessage: Failed to instantiate command api for [%s]\n}", commandClassName);
}
}