com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter. 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: AbstractJacksonFactory.java    From curiostack with MIT License 7 votes vote down vote up
public ObjectWriter newWriter(
    final boolean locationInfo, final boolean properties, final boolean compact) {
  final SimpleFilterProvider filters = new SimpleFilterProvider();
  final Set<String> except = new HashSet<>(4);
  if (!locationInfo) {
    except.add(this.getPropertyNameForSource());
  }
  if (!properties) {
    except.add(this.getPropertyNameForContextMap());
  }
  if (!includeStacktrace) {
    except.add(this.getPropertyNameForStackTrace());
  }
  except.add(this.getPropertyNameForNanoTime());
  filters.addFilter(
      Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
  final ObjectWriter writer =
      this.newObjectMapper().writer(compact ? this.newCompactPrinter() : this.newPrettyPrinter());
  return writer.with(filters);
}
 
Example #2
Source File: MappingJackson2JsonViewTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
Example #3
Source File: AbstractJacksonFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public ObjectWriter newWriter(final boolean locationInfo, final boolean properties, final boolean compact,
        final boolean includeMillis) {
    final SimpleFilterProvider filters = new SimpleFilterProvider();
    final Set<String> except = new HashSet<>(5);
    if (!locationInfo) {
        except.add(this.getPropertyNameForSource());
    }
    if (!properties) {
        except.add(this.getPropertyNameForContextMap());
    }
    if (!includeStacktrace) {
        except.add(this.getPropertyNameForStackTrace());
    }
    if (includeMillis) {
        except.add(getPropertyNameForInstant());
    } else {
        except.add(getPropertyNameForTimeMillis());
    }
    except.add(this.getPropertyNameForNanoTime());
    filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
    final ObjectWriter writer = this.newObjectMapper()
            .writer(compact ? this.newCompactPrinter() : this.newPrettyPrinter());
    return writer.with(filters);
}
 
Example #4
Source File: JsonFilterUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException {

    // arrange
    Author author = new Author("Alex", "Theedom");
    FilterProvider filters = new SimpleFilterProvider()
      .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));

    // act
    String result = new ObjectMapper().writer(filters).writeValueAsString(author);

    // assert
    assertThat(from(result).getList("items")).isNull();

    /*
        {
          "lastName": "Theedom"
        }
    */

}
 
Example #5
Source File: IgnoreFieldsWithFilterUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
    final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);

    final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    dtoObject.setIntValue(12);

    final String dtoAsString = mapper.writer(filters)
        .writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}
 
Example #6
Source File: IgnoreFieldsWithFilterUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
    final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);

    final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    dtoObject.setIntValue(12);

    final String dtoAsString = mapper.writer(filters)
        .writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}
 
Example #7
Source File: PathController.java    From odo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
@ResponseBody
public String testPath(@RequestParam String url, @RequestParam String profileIdentifier,
                       @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST,
                                                                                                        ClientService.getInstance().findClient("-1", profileId),
                                                                                                        ProfileService.getInstance().findProfile(profileId), url, requestType, true);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = {"possibleEndpoints", "enabledEndpoints"};
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET",
                                                                  SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}
 
Example #8
Source File: PathController.java    From odo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
@ResponseBody
public String getPathsForProfile(Model model, String profileIdentifier,
                                 @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter,
                                 @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = {"possibleEndpoints", "enabledEndpoints"};
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET",
                                                                  SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}
 
Example #9
Source File: KnoxShellTableJSONSerializer.java    From knox with Apache License 2.0 6 votes vote down vote up
private static String saveTableInFile(KnoxShellTable table, boolean data, String filePath) {
  try {
    final String jsonResult;
    if (data) {
      final SimpleFilterProvider filterProvider = new SimpleFilterProvider();
      filterProvider.addFilter("knoxShellTableFilter", SimpleBeanPropertyFilter.filterOutAllExcept("headers", "rows", "title", "id"));
      jsonResult = JsonUtils.renderAsJsonString(table, filterProvider, JSON_DATE_FORMAT.get());
    } else {
      jsonResult = JsonUtils.renderAsJsonString(KnoxShellTableCallHistory.getInstance().getCallHistory(table.id), null, JSON_DATE_FORMAT.get());
    }
    KnoxShellTableFileUtils.persistToFile(filePath, jsonResult);
    return "Successfully saved into " + filePath;
  } catch (IOException e) {
    throw new KnoxShellException("Error while saving KnoxShellTable JSON into " + filePath, e);
  }
}
 
Example #10
Source File: Jackson2ObjectMapperBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void filters() throws JsonProcessingException {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.filters(new SimpleFilterProvider().setFailOnUnknownId(false)).build();
	JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2");
	String output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, containsString("value2"));

	SimpleFilterProvider provider = new SimpleFilterProvider()
			.setFailOnUnknownId(false)
			.setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	objectMapper = Jackson2ObjectMapperBuilder.json().filters(provider).build();
	output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, not(containsString("value2")));
}
 
Example #11
Source File: MappingJackson2JsonViewTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
Example #12
Source File: Jackson2ObjectMapperBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filters() throws JsonProcessingException {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.filters(new SimpleFilterProvider().setFailOnUnknownId(false)).build();
	JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2");
	String output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, containsString("value2"));

	SimpleFilterProvider provider = new SimpleFilterProvider()
			.setFailOnUnknownId(false)
			.setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	objectMapper = Jackson2ObjectMapperBuilder.json().filters(provider).build();
	output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, not(containsString("value2")));
}
 
Example #13
Source File: JmapResponseWriterImpl.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ObjectMapper newConfiguredObjectMapper(JmapResponse jmapResponse) {
    ObjectMapper objectMapper = objectMapperFactory.forWriting();
    
    FilterProvider filterProvider = jmapResponse
            .getFilterProvider()
            .orElseGet(SimpleFilterProvider::new)
            .setDefaultFilter(SimpleBeanPropertyFilter.serializeAll())
            .addFilter(PROPERTIES_FILTER, getPropertiesFilter(jmapResponse.getProperties()));
    
    objectMapper.setFilterProvider(filterProvider);

    return objectMapper;
}
 
Example #14
Source File: ResourceController.java    From osiam with MIT License 5 votes vote down vote up
protected MappingJacksonValue buildResponse(Object resource, String attributes) {

        MappingJacksonValue wrapper = new MappingJacksonValue(resource);
        if (!Strings.isNullOrEmpty(attributes)) {
            Set<String> attributesSet = extractAttributes(attributes);
            FilterProvider filterProvider = new SimpleFilterProvider().addFilter(
                    "attributeFilter", SimpleBeanPropertyFilter.filterOutAllExcept(attributesSet)
            );
            wrapper.setFilters(filterProvider);
        }
        return wrapper;
    }
 
Example #15
Source File: GetMessagesMethodTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void processShouldReturnPropertyFilterWhenFilteringHeadersRequested() throws Exception {
    MessageManager inbox = mailboxManager.getMailbox(inboxPath, session);

    ComposedMessageId message1 = inbox.appendMessage(
        AppendCommand.from(
            org.apache.james.mime4j.dom.Message.Builder.of()
                .setFrom("[email protected]")
                .setField(new RawField("header1", "Header1Content"))
                .setField(new RawField("HEADer2", "Header2Content"))
                .setSubject("message 1 subject")
                .setBody("my message", StandardCharsets.UTF_8)),
        session).getId();

    GetMessagesRequest request = GetMessagesRequest.builder()
        .ids(ImmutableList.of(message1.getMessageId()))
        .properties(ImmutableList.of("headers.from", "headers.heADER2"))
        .build();

    List<JmapResponse> result = testee.processToStream(request, methodCallId, session).collect(Collectors.toList());

    assertThat(result)
        .hasSize(1)
        .extracting(JmapResponse::getFilterProvider)
        .are(new Condition<>(Optional::isPresent, "present"));
    SimpleFilterProvider actualFilterProvider = result.get(0).getFilterProvider().get();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setFilterProvider(actualFilterProvider.setDefaultFilter(SimpleBeanPropertyFilter.serializeAll()));
    String response = objectMapper.writer().writeValueAsString(result.get(0));
    assertThat(JsonPath.parse(response).<Map<String, String>>read("$.response.list[0].headers")).containsOnly(MapEntry.entry("From", "[email protected]"), MapEntry.entry("HEADer2", "Header2Content"));
}
 
Example #16
Source File: ParsingWritingObjectsTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void writingJsonShouldWorkOnMessage() throws Exception {
    String expected = IOUtils.toString(ClassLoader.getSystemResource("json/message.json"), StandardCharsets.UTF_8);

    SimpleFilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter(JmapResponseWriterImpl.PROPERTIES_FILTER, SimpleBeanPropertyFilter.serializeAll())
            .addFilter(GetMessagesMethod.HEADERS_FILTER, SimpleBeanPropertyFilter.serializeAll());

    String json = testee.forWriting()
            .setFilterProvider(filterProvider)
            .writeValueAsString(MESSAGE);

    assertThatJson(json)
        .when(IGNORING_ARRAY_ORDER)
        .isEqualTo(expected);

}
 
Example #17
Source File: ConfigSupport.java    From redisson with Apache License 2.0 5 votes vote down vote up
private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) {
    ObjectMapper mapper = new ObjectMapper(mapping);
    
    mapper.addMixIn(Config.class, ConfigMixIn.class);
    mapper.addMixIn(ReferenceCodecProvider.class, ClassMixIn.class);
    mapper.addMixIn(AddressResolverGroupFactory.class, ClassMixIn.class);
    mapper.addMixIn(Codec.class, ClassMixIn.class);
    mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class);
    mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
    mapper.addMixIn(NatMapper.class, ClassMixIn.class);
    mapper.addMixIn(NettyHook.class, ClassMixIn.class);
    
    FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
    mapper.setFilterProvider(filterProvider);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    if (classLoader != null) {
        TypeFactory tf = TypeFactory.defaultInstance()
                .withClassLoader(classLoader);
        mapper.setTypeFactory(tf);
    }
    
    return mapper;
}
 
Example #18
Source File: JacksonFactory.java    From summerframework with Apache License 2.0 5 votes vote down vote up
ObjectWriter newWriter(final boolean locationInfo, final boolean properties, final boolean compact) {
    final SimpleFilterProvider filters = new SimpleFilterProvider();
    final Set<String> except = new HashSet<>(2);
    if (!locationInfo) {
        except.add(this.getPropertNameForSource());
    }
    if (!properties) {
        except.add(this.getPropertNameForContextMap());
    }
    except.add(this.getPropertNameForNanoTime());
    filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
    final ObjectWriter writer =
        this.newObjectMapper().writer(compact ? this.newCompactPrinter() : this.newPrettyPrinter());
    return writer.with(filters);
}
 
Example #19
Source File: JsonSerializer.java    From gtfs-validator with MIT License 5 votes vote down vote up
/**
 * Create a JSON serializer for these validation results.
 * @param results
 */
public JsonSerializer (FeedValidationResultSet results) {
	super(results);
	mapper = new ObjectMapper();
	mapper.addMixInAnnotations(Rectangle2D.class, Rectangle2DMixIn.class);
	SimpleModule deser = new SimpleModule();
	deser.addDeserializer(Rectangle2D.class, new Rectangle2DDeserializer());
	mapper.registerModule(deser);
	SimpleFilterProvider filters = new SimpleFilterProvider();
	filters.addFilter("bbox", SimpleBeanPropertyFilter.filterOutAllExcept("west", "east", "south", "north"));
	writer = mapper.writer(filters);
}
 
Example #20
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 #21
Source File: ResponseTransformationFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectWriter modify(EndpointConfigBase<?> endpoint, MultivaluedMap<String, Object> responseHeaders, Object valueToWrite,
		ObjectWriter w, JsonGenerator g) throws IOException {
	SimpleBeanPropertyFilter filter = null;
	if (includes != null && !includes.isEmpty()) {
		filter = new SimpleBeanPropertyFilter.FilterExceptFilter(includes);
	} else if (excludes != null && !excludes.isEmpty()) {
		filter = SimpleBeanPropertyFilter.serializeAllExcept(excludes);
	} else {
		filter = SimpleBeanPropertyFilter.serializeAllExcept(new HashSet<String>());
	}
	FilterProvider provider = new SimpleFilterProvider().addFilter("property_filter", filter);
	return w.with(provider);
}
 
Example #22
Source File: AbstractJacksonSerializer.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected void init() {
	mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);
	mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
	mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PROTECTED_AND_PUBLIC);
	mapper.setVisibility(PropertyAccessor.SETTER, Visibility.PROTECTED_AND_PUBLIC);
	registerModules(mapper);
	mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
	mapper.setPropertyNamingStrategy(getPropertyNamingStrategy());
	SimpleFilterProvider provider = new SimpleFilterProvider();
	provider.addFilter("property_filter", SimpleBeanPropertyFilter.serializeAllExcept(Sets.<String>newHashSet()));
	mapper.setFilters(provider);
}
 
Example #23
Source File: JacksonAnnotationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException {
    final BeanWithFilter bean = new BeanWithFilter(1, "My bean");

    final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));

    final String result = new ObjectMapper().writer(filters)
        .writeValueAsString(bean);

    assertThat(result, containsString("My bean"));
    assertThat(result, not(containsString("id")));
}
 
Example #24
Source File: JacksonConfig.java    From syhthems-platform with MIT License 5 votes vote down vote up
/**
 * 不过滤基础字段的通用 ObjectMapper
 *
 * @return ObjectMapper
 */
@Bean
public ObjectMapper withoutFilterObjectMapper() {
    ObjectMapper objectMapper = jackson2ObjectMapperBuilder.build();
    // 添加字段过滤器,不进行过滤
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider
            .addFilter("cache", SimpleBeanPropertyFilter
                    .serializeAll());
    objectMapper.setFilterProvider(filterProvider);
    return objectMapper;
}
 
Example #25
Source File: JacksonConfig.java    From syhthems-platform with MIT License 5 votes vote down vote up
/**
 * 主要的ObjectMapper,用于Controller数据,过滤掉Model的基础字段。
 *
 * @return ObjectMapper
 */
@Bean
@Primary
public ObjectMapper commonObjectMapper() {
    ObjectMapper objectMapper = jackson2ObjectMapperBuilder.build();
    // 添加字段过滤器
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider
            .addFilter("cache", SimpleBeanPropertyFilter
                    .serializeAllExcept(BaseModel.CREATE_TIME,
                            BaseModel.LAST_UPDATE_TIME,
                            BaseModel.LAST_UPDATE_BY));
    objectMapper.setFilterProvider(filterProvider);
    return objectMapper;
}
 
Example #26
Source File: JacksonMixInFilterModule.java    From camunda-bpm-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static SimpleFilterProvider getCustomFilterProvider() {
  SimpleFilterProvider filterProvider = new SimpleFilterProvider();
  for (Map.Entry<Class<? extends HistoryEvent>, Class> mixInFilter : getDefaultMixInFilters().entrySet()) {
    String jsonFilterId = getJsonFilterAnnotationValue(mixInFilter.getValue());
    if (jsonFilterId != null) {
      SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept("");
      // TODO: add extension mechanism to declare filter values via ElasticSearchHistoryPluginConfiguration
      filterProvider.addFilter(jsonFilterId, filter);
    }
  }

  return filterProvider;
}
 
Example #27
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 #28
Source File: MappingJackson2JsonViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<String, Object>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
Example #29
Source File: APICaCertsPropertyHandler.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
public JsonNode handleProperty(IAPI desired, IAPI actual, JsonNode response) {
	String[] propertiesToExclude = {"certFile", "useForInbound", "useForOutbound"};
	FilterProvider filters = new SimpleFilterProvider()  
		      .addFilter("IgnoreImportFields",   
		          SimpleBeanPropertyFilter.serializeAllExcept(propertiesToExclude) );
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setFilterProvider(filters);
	if(desired.getCaCerts().size()!=0) {
		((ObjectNode)response).replace("caCerts", objectMapper.valueToTree(desired.getCaCerts()));
	}
	return response;
}
 
Example #30
Source File: Trace.java    From heimdall with Apache License 2.0 5 votes vote down vote up
private ObjectMapper mapper() {
    SimpleBeanPropertyFilter customFilter;

    if (!this.printFilters) {
        customFilter = SimpleBeanPropertyFilter.serializeAllExcept("filters");
    } else {
        customFilter = SimpleBeanPropertyFilter.serializeAll();
    }

    FilterProvider filters = new SimpleFilterProvider().addFilter("customFilter", customFilter);

    return new ObjectMapper().setFilterProvider(filters);

}