com.fasterxml.jackson.databind.ser.BeanPropertyWriter Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ser.BeanPropertyWriter. 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: StoredAsJsonBeanSerializerModifier.java    From Rosetta with Apache License 2.0 6 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
  for (BeanPropertyWriter beanProperty : beanProperties) {
    StoredAsJson storedAsJson = beanProperty.getAnnotation(StoredAsJson.class);
    if (storedAsJson != null && !StoredAsJson.NULL.equals(storedAsJson.empty())) {
      final JsonSerializer<Object> nullSerializer;
      if (storedAsJson.binary()) {
        nullSerializer = new ConstantBinarySerializer(storedAsJson.empty());
      } else {
        nullSerializer = new ConstantSerializer(storedAsJson.empty());
      }

      beanProperty.assignNullSerializer(nullSerializer);
    }
  }

  return super.changeProperties(config, beanDesc, beanProperties);
}
 
Example #2
Source File: EntityCustomSerializationFactory.java    From bboss-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void processViews(SerializationConfig config, BeanSerializerBuilder builder) {
	super.processViews(config, builder);
	// ignore fields only for concrete class
	// note, that you can avoid or change this check
	Class<?> beanClass = builder.getBeanDescription().getBeanClass();
	ClassUtil.ClassInfo classInfo = ClassUtil.getClassInfo(beanClass);
	// if (builder.getBeanDescription().getBeanClass().equals(Entity.class))
	// {
	// get original writer
	List<BeanPropertyWriter> originalWriters = builder.getProperties();
	// create actual writers
	List<BeanPropertyWriter> writers = new ArrayList<BeanPropertyWriter>();
	String[] fs = this._getFilterFields(classInfo);
	for (BeanPropertyWriter writer : originalWriters) {
		final String propName = writer.getName();
		// if it isn't ignored field, add to actual writers list
		boolean find = isFilterField(  classInfo,  propName,  fs);

		if(!find){
			writers.add(writer);
		}
	}
	builder.setProperties(writers);
}
 
Example #3
Source File: DecryptingObjectMapper.java    From halyard with Apache License 2.0 6 votes vote down vote up
protected StdScalarSerializer<Object> getSecretFileSerializer(
    BeanPropertyWriter beanPropertyWriter, SecretFile annotation, boolean shouldDecrypt) {
  return new StdScalarSerializer<Object>(String.class, false) {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider)
        throws IOException {
      if (value != null) {
        String sValue = value.toString();
        if (!EncryptedSecret.isEncryptedSecret(sValue) && !isURL(sValue)) {
          // metadataUrl is either a URL or a filepath, so only add prefix if it's a path
          sValue = annotation.prefix() + sValue;
        }
        if (EncryptedSecret.isEncryptedSecret(sValue) && shouldDecrypt) {
          // Decrypt the content of the file and store on the profile under a random
          // generated file name
          String name = newRandomFilePath(beanPropertyWriter.getName());
          byte[] bytes = secretSessionManager.decryptAsBytes(sValue);
          profile.getDecryptedFiles().put(name, bytes);
          sValue = annotation.prefix() + getCompleteFilePath(name);
        }
        gen.writeString(sValue);
      }
    }
  };
}
 
Example #4
Source File: JacksonClientModule.java    From bowman with Apache License 2.0 6 votes vote down vote up
public JacksonClientModule() {
	setSerializerModifier(new BeanSerializerModifier() {

		@Override
		public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
				List<BeanPropertyWriter> beanProperties) {
			
			for (BeanPropertyWriter writer : beanProperties) {
				if (writer.getAnnotation(LinkedResource.class) != null) {
					writer.assignSerializer(new LinkedResourceUriSerializer());
				}
			}
			
			return beanProperties;
		}
	});
	
	setMixInAnnotation(EntityModel.class, ResourceMixin.class);
	setMixInAnnotation(MethodHandler.class, MethodHandlerMixin.class);
}
 
Example #5
Source File: TestAccessorGeneration.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
public void testSingleIntAccessorGeneration() throws Exception
{
    Method method = Bean1.class.getDeclaredMethod("getX");
    AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
    PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean1.class);
    BeanPropertyWriter bpw = new BeanPropertyWriter(SimpleBeanPropertyDefinition
            .construct(MAPPER_CONFIG, annMethod, new PropertyName("x")),
            annMethod, null,
            null,
            null, null, null,
            false, null, null);
    coll.addIntGetter(bpw);
    BeanPropertyAccessor acc = coll.findAccessor(null);
    Bean1 bean = new Bean1();
    int value = acc.intGetter(bean, 0);
    assertEquals(bean.getX(), value);
}
 
Example #6
Source File: JsonUtilWithDefaultErrorContractDTOSupportTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void SmartErrorCodePropertyWriter_serializeAsField_still_works_for_non_Error_objects() throws Exception {
    // given
    final SmartErrorCodePropertyWriter secpw = new SmartErrorCodePropertyWriter(mock(BeanPropertyWriter.class));

    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            secpw.serializeAsField(new Object(), mock(JsonGenerator.class), mock(SerializerProvider.class));
        }
    });

    // then
    // We expect a NPE because mocking a base BeanPropertyWriter is incredibly difficult and not worth the effort.
    assertThat(ex).isInstanceOf(NullPointerException.class);
}
 
Example #7
Source File: BooleanMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public BooleanMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Boolean) {
        _suppressableBoolean = ((Boolean)_suppressableValue).booleanValue();
        _suppressableSet = true;
    } else {
        _suppressableBoolean = false;
        _suppressableSet = false;
    }
}
 
Example #8
Source File: RegistrationBeanSerializerModifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                 BeanDescription beanDesc,
                                                 List<BeanPropertyWriter> beanProperties) {
    if (!Registration.class.isAssignableFrom(beanDesc.getBeanClass())) {
        return beanProperties;
    }

    beanProperties.stream()
                  .filter(beanProperty -> "metadata".equals(beanProperty.getName()))
                  .forEach(beanProperty -> beanProperty.assignSerializer(metadataSerializer));
    return beanProperties;
}
 
Example #9
Source File: ConverterMapperModifier.java    From jfilter with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to remove bean property from bean properties list
 *
 * @param beanDesc       bean description
 * @param beanProperties list of bean properties
 */
private void removeFields(BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
    /*
     * Try to remove fields of specified class
     */
    removeFieldsByClass(beanDesc.getType().getRawClass(), beanProperties);

    /*
     * Try to remove fields with not specified class
     */
    removeFieldsByClass(null, beanProperties);
    removeFieldsByClass(void.class, beanProperties);
}
 
Example #10
Source File: FilteredBeanPropertyWriter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static BeanPropertyWriter constructViewBased(BeanPropertyWriter base, Class<?>[] viewsToIncludeIn)
{
    if (viewsToIncludeIn.length == 1) {
        return new SingleView(base, viewsToIncludeIn[0]);
    }
    return new MultiView(base, viewsToIncludeIn);
}
 
Example #11
Source File: ConverterMapperModifier.java    From jfilter with Apache License 2.0 5 votes vote down vote up
/**
 * Search matches of field name in ignoreList and bean properties list
 * If match is found then bean property will be removed from list
 *
 * @param clazz          class
 * @param beanProperties list of bean properties
 */
private void removeFieldsByClass(Class clazz, List<BeanPropertyWriter> beanProperties) {
    List<String> ignores = filterFields.getFields(clazz);

    if (!ignores.isEmpty())
        if (filterFields.getFilterBehaviour() == HIDE_FIELDS) {
            beanProperties.removeIf(beanProperty -> ignores.contains(beanProperty.getName()));
        } else
            beanProperties.removeIf(beanProperty -> !ignores.contains(beanProperty.getName()));
}
 
Example #12
Source File: BladeBeanSerializerModifier.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
 public List<BeanPropertyWriter> changeProperties(
         SerializationConfig config, BeanDescription beanDesc,
         List<BeanPropertyWriter> beanProperties) {
     // 循环所有的beanPropertyWriter
     beanProperties.forEach(writer -> {
// 如果已经有 null 序列化处理如注解:@JsonSerialize(nullsUsing = xxx) 跳过
if (writer.hasNullSerializer()) {
	return;
}
         JavaType type = writer.getType();
         Class<?> clazz = type.getRawClass();
         if (type.isTypeOrSubTypeOf(Number.class)) {
             writer.assignNullSerializer(NullJsonSerializers.NUMBER_JSON_SERIALIZER);
         }else if (type.isTypeOrSubTypeOf(Boolean.class)) {
             writer.assignNullSerializer(NullJsonSerializers.BOOLEAN_JSON_SERIALIZER);
         } else if (type.isTypeOrSubTypeOf(Character.class)) {
	writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
}  else if (type.isTypeOrSubTypeOf(String.class)) {
             writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
         } else if (type.isArrayType() || clazz.isArray() || type.isTypeOrSubTypeOf(Collection.class)) {
             writer.assignNullSerializer(NullJsonSerializers.ARRAY_JSON_SERIALIZER);
         } else if (type.isTypeOrSubTypeOf(OffsetDateTime.class)) {
             writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
         } else if (type.isTypeOrSubTypeOf(Date.class) || type.isTypeOrSubTypeOf(TemporalAccessor.class)) {
             writer.assignNullSerializer(NullJsonSerializers.STRING_JSON_SERIALIZER);
         } else {
             writer.assignNullSerializer(NullJsonSerializers.OBJECT_JSON_SERIALIZER);
         }
     });
     return super.changeProperties(config, beanDesc, beanProperties);
 }
 
Example #13
Source File: BeanAsArraySerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean hasSingleElement(SerializerProvider provider) {
    final BeanPropertyWriter[] props;
    if (_filteredProps != null && provider.getActiveView() != null) {
        props = _filteredProps;
    } else {
        props = _props;
    }
    return props.length == 1;
}
 
Example #14
Source File: AbstractTypeCustomizationFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
public BuilderAndBeanPropertiyWriters constructBeanSerializerBuilder(JavaType type) {
  BeanDescription beanDesc = serializerProvider.getConfig().introspect(type);
  BeanSerializerBuilder builder = new BeanSerializerBuilder(beanDesc);
  BeanPropertyWriter[] properties;

  try {
    properties = serializerFactory.findBeanProperties(serializerProvider, beanDesc, builder).toArray(new BeanPropertyWriter[0]);
  } catch (JsonMappingException e) {
    throw new RuntimeException("Unexpected exception", e);
  }

  return new BuilderAndBeanPropertiyWriters(builder, properties);
}
 
Example #15
Source File: SentinelSecureFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private PropertyWriter filter(PropertyWriter writer) {
  if (!transform) {
    return writer;
  }

  SentinelSecure secure = writer.getAnnotation(SentinelSecure.class);
  if (secure == null || secure.value() == null || secure.value().isEmpty()) {
    return writer;
  }

  return new SensitivePropertyWriter((BeanPropertyWriter) writer, secure.value());
}
 
Example #16
Source File: CustomBeanPropertyWriterTest.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> props)
{
    for (int i = 0, len = props.size(); i < len; ++i) {
        BeanPropertyWriter w = props.get(i);
        if (Integer.class.isAssignableFrom(w.getType().getRawClass())) {
            props.set(i, new Only2BeanPropertyWriter(w));
        }
    }
    return props;
}
 
Example #17
Source File: GuavaBeanSerializerModifier.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
        BeanDescription beanDesc,
        List<BeanPropertyWriter> beanProperties)
{
    for (int i = 0; i < beanProperties.size(); ++i) {
        final BeanPropertyWriter writer = beanProperties.get(i);
        if (Optional.class.isAssignableFrom(writer.getType().getRawClass())) {
            beanProperties.set(i, new GuavaOptionalBeanPropertyWriter(writer));
        }
    }
    return beanProperties;
}
 
Example #18
Source File: RegistrationBeanSerializerModifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
		List<BeanPropertyWriter> beanProperties) {
	if (!Registration.class.isAssignableFrom(beanDesc.getBeanClass())) {
		return beanProperties;
	}

	beanProperties.stream().filter((beanProperty) -> "metadata".equals(beanProperty.getName()))
			.forEach((beanProperty) -> beanProperty.assignSerializer(metadataSerializer));
	return beanProperties;
}
 
Example #19
Source File: DecryptingObjectMapper.java    From halyard with Apache License 2.0 5 votes vote down vote up
public DecryptingObjectMapper(
    SecretSessionManager secretSessionManager,
    Profile profile,
    Path decryptedOutputDirectory,
    boolean decryptAllSecrets) {
  super();
  this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
  this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

  this.secretSessionManager = secretSessionManager;
  this.profile = profile;
  this.decryptedOutputDirectory = decryptedOutputDirectory;
  this.decryptAllSecrets = decryptAllSecrets;

  SimpleModule module = new SimpleModule();
  module.setSerializerModifier(
      new BeanSerializerModifier() {

        @Override
        public List<BeanPropertyWriter> changeProperties(
            SerializationConfig config,
            BeanDescription beanDesc,
            List<BeanPropertyWriter> beanProperties) {
          for (BeanPropertyWriter bpw : beanProperties) {
            Secret secret = bpw.getAnnotation(Secret.class);
            if (secret != null && (decryptAllSecrets || secret.alwaysDecrypt())) {
              bpw.assignSerializer(getSecretSerializer());
            }
            SecretFile secretFile = bpw.getAnnotation(SecretFile.class);
            if (secretFile != null) {
              boolean shouldDecrypt = (decryptAllSecrets || secretFile.alwaysDecrypt());
              bpw.assignSerializer(getSecretFileSerializer(bpw, secretFile, shouldDecrypt));
            }
          }
          return beanProperties;
        }
      });
  this.registerModule(module);
}
 
Example #20
Source File: BooleanFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public BooleanFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Boolean) {
        _suppressableBoolean = ((Boolean)_suppressableValue).booleanValue();
        _suppressableSet = true;
    } else {
        _suppressableBoolean = false;
        _suppressableSet = false;
    }
}
 
Example #21
Source File: OptimizedBeanPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
protected OptimizedBeanPropertyWriter(BeanPropertyWriter src,
        BeanPropertyAccessor propertyAccessor, int propertyIndex,
        JsonSerializer<Object> ser)
{
    super(src);
    this.fallbackWriter = unwrapFallbackWriter(src);
    // either use the passed on serializer or the original one
    _serializer = (ser != null) ? ser : src.getSerializer();
    _propertyAccessor = propertyAccessor;
    _propertyIndex = propertyIndex;
    _fastName = src.getSerializedName();
}
 
Example #22
Source File: IntMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public IntMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Integer) {
        _suppressableInt = (Integer)_suppressableValue;
        _suppressableIntSet = true;
    } else {
        _suppressableInt = 0;
        _suppressableIntSet = false;
    }
}
 
Example #23
Source File: IntFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public IntFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Integer) {
        _suppressableInt = ((Integer)_suppressableValue).intValue();
        _suppressableSet = true;
    } else {
        _suppressableInt = 0;
        _suppressableSet = false;
    }
}
 
Example #24
Source File: LongMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public LongMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Long) {
        _suppressableLong = (Long)_suppressableValue;
        _suppressableSet = true;
    } else {
        _suppressableLong = 0L;
        _suppressableSet = false;
    }
}
 
Example #25
Source File: LongFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public LongFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Long) {
        _suppressableLong = (Long)_suppressableValue;
        _suppressableSet = true;
    } else {
        _suppressableLong = 0L;
        _suppressableSet = false;
    }
}
 
Example #26
Source File: MyBeanSerializerModifier.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(final SerializationConfig config, final BeanDescription beanDesc, final List<BeanPropertyWriter> beanProperties) {
    for (int i = 0; i < beanProperties.size(); i++) {
        final BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
        if (beanPropertyWriter.getName() == "name") {
            beanProperties.set(i, new UpperCasingWriter(beanPropertyWriter));
        }
    }
    return beanProperties;
}
 
Example #27
Source File: StringFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
public StringFieldPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);
}
 
Example #28
Source File: UnwrappingBeanPropertyWriter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public UnwrappingBeanPropertyWriter(BeanPropertyWriter base, NameTransformer unwrapper) {
    super(base);
    _nameTransformer = unwrapper;
}
 
Example #29
Source File: StringMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
@Override
public BeanPropertyWriter withSerializer(JsonSerializer<Object> ser) {
    return new StringMethodPropertyWriter(this, _propertyAccessor, _propertyIndex, ser);
}
 
Example #30
Source File: StringMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
@Override
protected BeanPropertyWriter _new(PropertyName newName) {
    return new StringMethodPropertyWriter(this, newName);
}