List of usage examples for com.fasterxml.jackson.databind.introspect BeanPropertyDefinition getName
public abstract String getName();
From source file:org.jongo.marshall.jackson.JacksonObjectIdUpdater.java
private static boolean hasIdName(BeanPropertyDefinition property) { return "_id".equals(property.getName()); }
From source file:springfox.documentation.schema.property.BeanPropertyDefinitions.java
private static String getName(PropertyNamingStrategy naming, BeanPropertyDefinition beanProperty, MapperConfig<?> config) {/*from w ww . j av a2 s.c o m*/ PojoPropertyBuilderFactory factory = new PojoPropertyBuilderFactory(); POJOPropertyBuilder prop = factory.create(config, beanProperty); return naming.nameForField(config, prop.getField(), beanProperty.getName()); }
From source file:org.lightadmin.core.web.json.DynamicFilePropertyOmittingSerializerModifier.java
private PersistentProperty<?> findProperty(String finalName, PersistentEntity<?, ?> entity, BeanDescription description) {/*w ww .j a v a 2 s. c om*/ for (BeanPropertyDefinition definition : description.findProperties()) { if (definition.getName().equals(finalName)) { return entity.getPersistentProperty(definition.getInternalName()); } } return null; }
From source file:com.addthis.codec.jackson.WriteonlyPropertyIgnorer.java
@Override public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException { ObjectCodec objectCodec = jp.getCodec(); if (objectCodec instanceof ObjectMapper) { ObjectMapper objectMapper = (ObjectMapper) objectCodec; BeanDescription beanDescription = objectMapper.getSerializationConfig() .introspect(ctxt.constructType(beanOrClass.getClass())); for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) { if (propertyName.equals(propertyDefinition.getName())) { jp.skipChildren();//from ww w . j a v a 2 s.c o m return true; } } } return false; }
From source file:de.fraunhofer.iosb.ilt.sta.deserialize.custom.CustomEntityDeserializer.java
@Override public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Entity result;// ww w. j ava 2s. c o m try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IOException("Error deserializing JSON!"); } // need to make subclass of this class for every Entity subclass with custom field to get expected class!!! BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz)); ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode obj = (JsonNode) mapper.readTree(parser); List<BeanPropertyDefinition> properties = beanDescription.findProperties(); Iterator<Map.Entry<String, JsonNode>> i = obj.fields(); // First check if we know all properties that are present. if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) { for (; i.hasNext();) { Map.Entry<String, JsonNode> next = i.next(); String fieldName = next.getKey(); JsonNode field = next.getValue(); Optional<BeanPropertyDefinition> findFirst = properties.stream() .filter(p -> p.getName().equals(fieldName)).findFirst(); if (!findFirst.isPresent()) { throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null); } } } for (BeanPropertyDefinition classProperty : properties) { if (obj.has(classProperty.getName())) { // property is present in class and json Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class); if (annotation != null) { // property has custom annotation // check if encoding property is also present in json (and also in class itself for sanity reasons) CustomSerialization customAnnotation = (CustomSerialization) annotation; Optional<BeanPropertyDefinition> encodingClassProperty = properties.stream() .filter(p -> p.getName().equals(customAnnotation.encoding())).findFirst(); if (!encodingClassProperty.isPresent()) { throw new IOException("Error deserializing JSON as class '" + clazz.toString() + "' \n" + "Reason: field '" + customAnnotation.encoding() + "' specified by annotation as encoding field is not defined in class!"); } String customEncoding = null; if (obj.has(customAnnotation.encoding())) { customEncoding = obj.get(customAnnotation.encoding()).asText(); } Object customDeserializedValue = CustomDeserializationManager.getInstance() .getDeserializer(customEncoding) .deserialize(mapper.writeValueAsString(obj.get(classProperty.getName()))); classProperty.getMutator().setValue(result, customDeserializedValue); } else { // TODO type identificatin is not safe beacuase may ne be backed by field. Rather do multiple checks Object value = mapper.readValue(mapper.writeValueAsString(obj.get(classProperty.getName())), classProperty.getField().getType()); classProperty.getMutator().setValue(result, value); } } } return (T) result; }
From source file:dk.nykredit.jackson.dataformat.hal.deser.HALBeanDeserializerModifier.java
@Override public List<BeanPropertyDefinition> updateProperties(DeserializationConfig config, BeanDescription beanDesc, List<BeanPropertyDefinition> propDefs) { Resource ann = beanDesc.getClassAnnotations().get(Resource.class); if (ann != null) { List<BeanPropertyDefinition> modified = new ArrayList<>(); Iterator<BeanPropertyDefinition> defIt = propDefs.iterator(); while (defIt.hasNext()) { BeanPropertyDefinition pbd = defIt.next(); for (ReservedProperty rp : ReservedProperty.values()) { String alternateName = rp.alternateName(pbd, pbd.getName()); if (!pbd.getName().equals(alternateName)) { modified.add(pbd.withName(new PropertyName(alternateName))); defIt.remove();/*from ww w.j av a2 s . c om*/ } } } propDefs.addAll(modified); } return propDefs; }
From source file:gaffer.rest.service.SimpleGraphConfigurationService.java
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user") @Override/* w w w.ja va 2s .c o m*/ public Set<String> getSerialisedFields(final String className) { final Class<?> clazz; try { clazz = Class.forName(className); } catch (Exception e) { throw new IllegalArgumentException("Class name was not recognised: " + className, e); } final ObjectMapper mapper = new ObjectMapper(); final JavaType type = mapper.getTypeFactory().constructType(clazz); final BeanDescription introspection = mapper.getSerializationConfig().introspect(type); final List<BeanPropertyDefinition> properties = introspection.findProperties(); final Set<String> fields = new HashSet<>(); for (final BeanPropertyDefinition property : properties) { fields.add(property.getName()); } return fields; }
From source file:fr.norad.jaxrs.doc.parser.ModelJacksonParser.java
@Override public List<PropertyAccessor> findProperties(Class<?> modelClass) { List<PropertyAccessor> properties = new ArrayList<>(); BasicBeanDescription beanDesc = fakeSerializer.getDescription(modelClass); List<BeanPropertyDefinition> findProperties = beanDesc.findProperties(); for (BeanPropertyDefinition beanPropertyDefinition : findProperties) { if (modelClass.isEnum() && "declaringClass".equals(beanPropertyDefinition.getName())) { continue; }/*from w w w . j av a2 s. c o m*/ AnnotatedMethod getterJackson = beanPropertyDefinition.getGetter(); AnnotatedMethod setterJackson = beanPropertyDefinition.getSetter(); AnnotatedField fieldJackson = null; try { fieldJackson = beanPropertyDefinition.getField(); } catch (Exception e) { log.warning("Name conflict on fields in bean : " + beanPropertyDefinition + " during doc generation" + e.getMessage()); } Method getter = getterJackson == null ? null : getterJackson.getAnnotated(); Method setter = setterJackson == null ? null : setterJackson.getAnnotated(); Field field = fieldJackson == null ? null : fieldJackson.getAnnotated(); if (getter == null && setter == null && field == null) { log.warning( "Cannot find valid property element for : " + beanPropertyDefinition + " on " + modelClass); continue; } PropertyAccessor property = new PropertyAccessor(); property.setField(field); property.setGetter(getter); property.setSetter(setter); property.setName(beanPropertyDefinition.getName()); properties.add(property); } return properties; }
From source file:org.gvnix.web.json.ConversionServiceBeanSerializerModifier.java
@Override public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) { // We need the BeanPropertyDefinition to get the related Field List<BeanPropertyDefinition> properties = beanDesc.findProperties(); Map<String, BeanPropertyDefinition> propertyDefMap = new HashMap<String, BeanPropertyDefinition>(); for (BeanPropertyDefinition property : properties) { propertyDefMap.put(property.getName(), property); }// w w w.j a v a2 s . c o m // iterate over bean's properties to configure serializers for (int i = 0; i < beanProperties.size(); i++) { BeanPropertyWriter beanPropertyWriter = beanProperties.get(i); Class<?> propertyType = beanPropertyWriter.getPropertyType(); if (beanPropertyWriter.hasSerializer()) { continue; } // For conversion between collection, array, and map types, // ConversionService.canConvert() method will return 'true' // but better to delegate in default Jackson property writer for // right start and ends markers serialization and iteration if (propertyType.isArray() || Collection.class.isAssignableFrom(propertyType) || Map.class.isAssignableFrom(propertyType)) { // Don't set ConversionService serializer, let Jackson // use default Collection serializer continue; } else if (BindingResult.class.isAssignableFrom(propertyType)) { // Use BindingResultSerializer beanPropertyWriter.assignSerializer(bindingResultSerializer); } else { // ConversionService uses value Class plus related Field // annotations to be able to select the right converter, // so we must get/ the Field annotations for success // formatting BeanPropertyDefinition propertyDef = propertyDefMap.get(beanPropertyWriter.getName()); AnnotatedField annotatedField = propertyDef.getField(); if (annotatedField == null) { continue; } AnnotatedElement annotatedEl = annotatedField.getAnnotated(); // Field contains info about Annotations, info that // ConversionService uses for success formatting, use it if // available. Otherwise use the class of given value. TypeDescriptor sourceType = annotatedEl != null ? new TypeDescriptor((Field) annotatedEl) : TypeDescriptor.valueOf(propertyType); TypeDescriptor targetType = TypeDescriptor.valueOf(String.class); if (beanPropertyWriter.getSerializationType() != null) { targetType = TypeDescriptor.valueOf(beanPropertyWriter.getSerializationType().getRawClass()); } if (ObjectUtils.equals(sourceType, targetType)) { // No conversion needed continue; } else if (sourceType.getObjectType() == Object.class && targetType.getObjectType() == String.class && beanPropertyWriter.getSerializationType() == null) { // Can't determine source type and no target type has been // configure. Delegate on jackson. continue; } // All other converters must be set in ConversionService if (this.conversionService.canConvert(sourceType, targetType)) { // We must create BeanPropertyWriter own Serializer that // has knowledge about the Field related to that // BeanPropertyWriter in order to have access to // Field Annotations for success serialization JsonSerializer<Object> jsonSerializer = new ConversionServicePropertySerializer( this.conversionService, sourceType, targetType); beanPropertyWriter.assignSerializer(jsonSerializer); } // If no converter set, use default Jackson property writer else { continue; } } } return beanProperties; }
From source file:org.springframework.rest.documentation.boot.SwaggerDocumentationEndpoint.java
private void addModelForType(String type, Map<String, ClassDescriptor> responseClasses, Documentation documentation) {//from w w w .ja v a 2 s . c o m String name = getSwaggerDataType(type); if (documentation.getModels() == null || !documentation.getModels().containsKey(name)) { DocumentationSchema schema = new DocumentationSchema(); ClassDescriptor classDescriptor = responseClasses.get(type); if (classDescriptor != null) { schema.setDescription(classDescriptor.getName()); } try { Class<?> clazz = Class.forName(type); if (clazz.isEnum()) { Object[] enumConstants = clazz.getEnumConstants(); List<String> values = new ArrayList<String>(); for (Object enumConstant : enumConstants) { values.add(enumConstant.toString()); } schema.setAllowableValues(new DocumentationAllowableListValues(values)); } else { BasicClassIntrospector introspector = new BasicClassIntrospector(); Map<String, DocumentationSchema> properties = new HashMap<String, DocumentationSchema>(); BasicBeanDescription descriptor = introspector.forSerialization( this.objectMapper.getSerializationConfig(), TypeFactory.defaultInstance().constructType(clazz), this.objectMapper.getSerializationConfig()); for (BeanPropertyDefinition property : descriptor.findProperties()) { String propertyName = property.getName(); DocumentationSchema propertySchema = new DocumentationSchema(); MethodDescriptor methodDescriptor = classDescriptor .getMethodDescriptor((Method) property.getAccessor().getAnnotated()); if (methodDescriptor != null) { Class<?> propertyClass = Class.forName(methodDescriptor.getReturnType()); propertySchema.setDescription(methodDescriptor.getSummary()); if (propertyClass.isEnum()) { Object[] enumConstants = propertyClass.getEnumConstants(); List<String> values = new ArrayList<String>(); for (Object enumConstant : enumConstants) { values.add(enumConstant.toString()); } propertySchema.setType("string"); propertySchema.setAllowableValues(new DocumentationAllowableListValues(values)); } else { propertySchema.setType(getSwaggerDataType(methodDescriptor.getReturnType())); addModelForType(methodDescriptor.getReturnType(), responseClasses, documentation); } } properties.put(propertyName, propertySchema); } schema.setProperties(properties); } } catch (ClassNotFoundException e) { e.printStackTrace(); } documentation.addModel(name, schema); } }