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

The following examples show how to use com.fasterxml.jackson.databind.ser.PropertyFilter. 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: MapSerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serialize(Map<?,?> value, JsonGenerator gen, SerializerProvider provider)
    throws IOException
{
    gen.writeStartObject(value);
    if (!value.isEmpty()) {
        if (_sortKeys || provider.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)) {
            value = _orderEntries(value, gen, provider);
        }
        PropertyFilter pf;
        if ((_filterId != null) && (pf = findPropertyFilter(provider, _filterId, value)) != null) {
            serializeFilteredFields(value, gen, provider, pf, _suppressableValue);
        } else if ((_suppressableValue != null) || _suppressNulls) {
            serializeOptionalFields(value, gen, provider, _suppressableValue);
        } else if (_valueSerializer != null) {
            serializeFieldsUsing(value, gen, provider, _valueSerializer);
        } else {
            serializeFields(value, gen, provider);
        }
    }
    gen.writeEndObject();
}
 
Example #2
Source File: MapSerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serializeWithType(Map<?,?> value, JsonGenerator gen, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    // [databind#631]: Assign current value, to be accessible by custom serializers
    gen.setCurrentValue(value);
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen,
            typeSer.typeId(value, JsonToken.START_OBJECT));
    if (!value.isEmpty()) {
        if (_sortKeys || provider.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)) {
            value = _orderEntries(value, gen, provider);
        }
        PropertyFilter pf;
        if ((_filterId != null) && (pf = findPropertyFilter(provider, _filterId, value)) != null) {
            serializeFilteredFields(value, gen, provider, pf, _suppressableValue);
        } else if ((_suppressableValue != null) || _suppressNulls) {
            serializeOptionalFields(value, gen, provider, _suppressableValue);
        } else if (_valueSerializer != null) {
            serializeFieldsUsing(value, gen, provider, _valueSerializer);
        } else {
            serializeFields(value, gen, provider);
        }
    }
    typeSer.writeTypeSuffix(gen, typeIdDef);
}
 
Example #3
Source File: RntbdObjectMapper.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
static void registerPropertyFilter(final Class<?> type, final Class<? extends PropertyFilter> filter) {

    checkNotNull(type, "type");
    checkNotNull(filter, "filter");

    try {
        filterProvider.addFilter(type.getSimpleName(), filter.newInstance());
    } catch (final ReflectiveOperationException error) {
        throw new IllegalStateException(error);
    }
}
 
Example #4
Source File: JacksonObjectProvider.java    From ameba with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public PropertyFilter findPropertyFilter(final Object filterId, final Object valueToFilter) {
    if (filterId instanceof String) {
        final String id = (String) filterId;

        // FilterId should represent a class only in case of root entity is marshalled.
        if (id.equals(root.getEntityClass().getName())) {
            stack.clear();
            return stack.push(root);
        }

        while (!stack.isEmpty()) {
            final FilteringPropertyFilter peek = stack.peek();
            final FilteringPropertyFilter subfilter = peek.findSubfilter(id);

            if (subfilter != null) {
                stack.push(subfilter);

                // Need special handling for maps here - map keys can be filtered as well so we just say that every key is
                // allowed.
                if (valueToFilter instanceof Map) {
                    final Map<String, ?> map = (Map<String, ?>) valueToFilter;
                    return new FilteringPropertyFilter(Map.class, map.keySet(),
                            Collections.emptyMap());
                }
                return subfilter;
            } else {
                stack.pop();
            }
        }
    }
    return SimpleBeanPropertyFilter.filterOutAllExcept();
}
 
Example #5
Source File: ApiService_UpdateTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));

    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(mock(Authentication.class));
    SecurityContextHolder.setContext(securityContext);

    when(api.getId()).thenReturn(API_ID);
    when(api.getDefinition()).thenReturn("{\"id\": \"" + API_ID + "\",\"name\": \"" + API_NAME + "\",\"proxy\": {\"context_path\": \"/old\"}}");
}
 
Example #6
Source File: ApiService_StartTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    UserEntity u = mock(UserEntity.class);
    when(u.getId()).thenReturn("uid");
    when(userService.findById(any())).thenReturn(u);
    MembershipEntity po = mock(MembershipEntity.class);
    when(membershipService.getPrimaryOwner(
            eq(io.gravitee.rest.api.model.MembershipReferenceType.API),
            anyString())).thenReturn(po);
    when(api.getId()).thenReturn(API_ID);
}
 
Example #7
Source File: ApiService_StopTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws TechnicalException {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    UserEntity u = mock(UserEntity.class);
    when(u.getId()).thenReturn("uid");
    when(userService.findById(any())).thenReturn(u);
    MembershipEntity po = mock(MembershipEntity.class);
    when(membershipService.getPrimaryOwner(
            eq(io.gravitee.rest.api.model.MembershipReferenceType.API),
            anyString())).thenReturn(po);
    when(api.getId()).thenReturn(API_ID);
}
 
Example #8
Source File: MultimapSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
private final void serializeFilteredFields(Multimap<?, ?> mmap, JsonGenerator gen, SerializerProvider provider)
        throws IOException
{
    final Set<String> ignored = _ignoredEntries;
    PropertyFilter filter = findPropertyFilter(provider, _filterId, mmap);  
    final MapProperty prop = new MapProperty(_valueTypeSerializer, _property);
    for (Entry<?, ? extends Collection<?>> entry : mmap.asMap().entrySet()) {
        // First, serialize key
        Object key = entry.getKey();
        if ((ignored != null) && ignored.contains(key)) {
            continue;
        }
        Collection<?> value = entry.getValue();
        JsonSerializer<Object> valueSer;
        if (value == null) {
            // !!! TODO: null suppression?
            valueSer = provider.getDefaultNullValueSerializer();
        } else {
            valueSer = _valueSerializer;
        }
        prop.reset(key, value, _keySerializer, valueSer);
        try {
            filter.serializeAsField(mmap, gen, provider, prop);
        } catch (Exception e) {
            String keyDesc = ""+key;
            wrapAndThrow(provider, e, value, keyDesc);
        }
    }
}
 
Example #9
Source File: StdSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper method used to locate filter that is needed, based on filter id
 * this serializer was constructed with.
 * 
 * @since 2.3
 */
protected PropertyFilter findPropertyFilter(SerializerProvider provider,
        Object filterId, Object valueToFilter)
    throws JsonMappingException
{
    FilterProvider filters = provider.getFilterProvider();
    // Not ok to miss the provider, if a filter is declared to be needed.
    if (filters == null) {
        provider.reportBadDefinition(handledType(),
                "Cannot resolve PropertyFilter with id '"+filterId+"'; no FilterProvider configured");
    }
    // But whether unknown ids are ok just depends on filter provider; if we get null that's fine
    return filters.findPropertyFilter(filterId, valueToFilter);
}
 
Example #10
Source File: DefaultSqlHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected void log(final String name, final PhysicalPlan plan, final Logger logger) {
  if (logger.isDebugEnabled()) {
    PropertyFilter filter = new SimpleBeanPropertyFilter.SerializeExceptFilter(Sets.newHashSet("password"));
    String planText = plan.unparse(context.getLpPersistence().getMapper()
            .writer(new SimpleFilterProvider().addFilter("passwordFilter", filter)));
    logger.debug(name + " : \n" + planText);
  }
}
 
Example #11
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
private void registerFilterProvider() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    mapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
}
 
Example #12
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
private void registerFilterProvider() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    mapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
}
 
Example #13
Source File: ApiService_FindByUserTest.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
}
 
Example #14
Source File: MapSerializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper method used when we have a JSON Filter to use AND contents are
 * "any properties" of a POJO.
 *
 * @param bean Enclosing POJO that has any-getter used to obtain "any properties"
 * 
 * @since 2.9
 */
public void serializeFilteredAnyProperties(SerializerProvider provider, JsonGenerator gen,
        Object bean, Map<?,?> value, PropertyFilter filter,
        Object suppressableValue)
    throws IOException
{
    final Set<String> ignored = _ignoredEntries;
    final MapProperty prop = new MapProperty(_valueTypeSerializer, _property);
    final boolean checkEmpty = (MARKER_FOR_EMPTY == suppressableValue);

    for (Map.Entry<?,?> entry : value.entrySet()) {
        // First, serialize key; unless ignorable by key
        final Object keyElem = entry.getKey();
        if (ignored != null && ignored.contains(keyElem)) continue;

        JsonSerializer<Object> keySerializer;
        if (keyElem == null) {
            keySerializer = provider.findNullKeySerializer(_keyType, _property);
        } else {
            keySerializer = _keySerializer;
        }
        // or by value; nulls often suppressed
        final Object valueElem = entry.getValue();

        JsonSerializer<Object> valueSer;
        // And then value
        if (valueElem == null) {
            if (_suppressNulls) {
                continue;
            }
            valueSer = provider.getDefaultNullValueSerializer();
        } else {
            valueSer = _valueSerializer;
            if (valueSer == null) {
                valueSer = _findSerializer(provider, valueElem);
            }
            // also may need to skip non-empty values:
            if (checkEmpty) {
                if (valueSer.isEmpty(provider, valueElem)) {
                    continue;
                }
            } else if (suppressableValue != null) {
                if (suppressableValue.equals(valueElem)) {
                    continue;
                }
            }
        }
        // and with that, ask filter to handle it
        prop.reset(keyElem, valueElem, keySerializer, valueSer);
        try {
            filter.serializeAsField(bean, gen, provider, prop);
        } catch (Exception e) {
            wrapAndThrow(provider, e, value, String.valueOf(keyElem));
        }
    }
}
 
Example #15
Source File: ApiService_Update_DefaultLoggingMaxDurationTest.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp()  throws TechnicalException {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
    when(apiRepository.update(any())).thenReturn(api);
    when(api.getName()).thenReturn(API_NAME);
    when(api.getApiLifecycleState()).thenReturn(ApiLifecycleState.CREATED);

    existingApi = new UpdateApiEntity();
    existingApi.setName(API_NAME);
    existingApi.setVersion("v1");
    existingApi.setDescription("Ma description");
    existingApi.setLifecycleState(io.gravitee.rest.api.model.api.ApiLifecycleState.CREATED);
    final Proxy proxy = new Proxy();
    EndpointGroup endpointGroup = new EndpointGroup();
    Endpoint endpoint = new HttpEndpoint(null, null);
    endpointGroup.setEndpoints(singleton(endpoint));
    proxy.setGroups(singleton(endpointGroup));
    existingApi.setProxy(proxy);
    proxy.setVirtualHosts(Collections.singletonList(new VirtualHost("/context")));
    
    RoleEntity poRoleEntity = new RoleEntity();
    poRoleEntity.setName(SystemRole.PRIMARY_OWNER.name());
    poRoleEntity.setScope(RoleScope.API);
    when(roleService.findByScopeAndName(RoleScope.API, SystemRole.PRIMARY_OWNER.name())).thenReturn(Optional.of(poRoleEntity));
    MemberEntity po = new MemberEntity();
    po.setId(USER_NAME);
    po.setReferenceId(API_ID);
    po.setReferenceType(io.gravitee.rest.api.model.MembershipReferenceType.API);
    po.setRoles(Collections.singletonList(poRoleEntity));
    when(membershipService.getMembersByReferencesAndRole(any(), any(), any())).thenReturn(singleton(po));
    
    
    mockStatic(System.class);
    when(System.currentTimeMillis()).thenReturn(0L);

    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(mock(Authentication.class));
    SecurityContextHolder.setContext(securityContext);
}
 
Example #16
Source File: ApiService_FindByIdTest.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
}
 
Example #17
Source File: MapSerializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper method used when we have a JSON Filter to use for potentially
 * filtering out Map entries.
 * 
 * @since 2.5
 */
public void serializeFilteredFields(Map<?,?> value, JsonGenerator gen, SerializerProvider provider,
        PropertyFilter filter,
        Object suppressableValue) // since 2.5
    throws IOException
{
    final Set<String> ignored = _ignoredEntries;
    final MapProperty prop = new MapProperty(_valueTypeSerializer, _property);
    final boolean checkEmpty = (MARKER_FOR_EMPTY == suppressableValue);

    for (Map.Entry<?,?> entry : value.entrySet()) {
        // First, serialize key; unless ignorable by key
        final Object keyElem = entry.getKey();
        if (ignored != null && ignored.contains(keyElem)) continue;

        JsonSerializer<Object> keySerializer;
        if (keyElem == null) {
            keySerializer = provider.findNullKeySerializer(_keyType, _property);
        } else {
            keySerializer = _keySerializer;
        }
        // or by value; nulls often suppressed
        final Object valueElem = entry.getValue();

        JsonSerializer<Object> valueSer;
        // And then value
        if (valueElem == null) {
            if (_suppressNulls) {
                continue;
            }
            valueSer = provider.getDefaultNullValueSerializer();
        } else {
            valueSer = _valueSerializer;
            if (valueSer == null) {
                valueSer = _findSerializer(provider, valueElem);
            }
            // also may need to skip non-empty values:
            if (checkEmpty) {
                if (valueSer.isEmpty(provider, valueElem)) {
                    continue;
                }
            } else if (suppressableValue != null) {
                if (suppressableValue.equals(valueElem)) {
                    continue;
                }
            }
        }
        // and with that, ask filter to handle it
        prop.reset(keyElem, valueElem, keySerializer, valueSer);
        try {
            filter.serializeAsField(value, gen, provider, prop);
        } catch (Exception e) {
            wrapAndThrow(provider, e, value, String.valueOf(keyElem));
        }
    }
}
 
Example #18
Source File: ApiService_DeleteTest.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
}
 
Example #19
Source File: JsonMapper.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public JsonMapper defaultFiler(PropertyFilter bpf){
//		this.filterProvider.setDefaultFilter(bpf);
		this.filterProvider.setDefaultFilter(bpf);
		return this;
	}
 
Example #20
Source File: GetMessagesMethod.java    From james-project with Apache License 2.0 4 votes vote down vote up
private PropertyFilter buildHeadersPropertyFilter(ImmutableSet<HeaderProperty> headerProperties) {
    return new FieldNamePropertyFilter((fieldName) -> headerProperties.contains(HeaderProperty.fromFieldName(fieldName)));
}
 
Example #21
Source File: JmapResponseWriterImpl.java    From james-project with Apache License 2.0 4 votes vote down vote up
private PropertyFilter getPropertiesFilter(Optional<? extends Set<? extends Property>> properties) {
    return properties
            .map(this::toFieldNames)
            .map(SimpleBeanPropertyFilter::filterOutAllExcept)
            .orElse(SimpleBeanPropertyFilter.serializeAll());
}