Java Code Examples for com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider#addFilter()

The following examples show how to use com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider#addFilter() . 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: 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 3
Source File: StringCatalogReader.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
public StringCatalogReader() throws Exception {
    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    ObjectMapper mapper = new ObjectMapper(factory);
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("catalogEvent", new CatalogEventFilter());
    mapper.setFilterProvider(filterProvider);
    catalogData = createCatalogData();
    json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(catalogData);
    assertNotNull("No json catalog created", json);
    File file = new File("target/testCatalog.json");
    PrintStream ps = new PrintStream(new FileOutputStream(file));
    ps.print(json);
    ps.close();
    lastUpdated = LocalDateTime.now();
}
 
Example 4
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 5
Source File: WebMvcAppContext.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
public ObjectMapper objectMapper() {
    LOGGER.debug("Creating custom ObjectMapper");
    ObjectMapper mapper = JsonObjectMapperFactory.createMapper();
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("catalogEvent", new CatalogEventFilter());
    mapper.setFilterProvider(filterProvider);
    return mapper;
}
 
Example 6
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 7
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 8
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 9
Source File: TaggedLogAPIEntity.java    From eagle with Apache License 2.0 5 votes vote down vote up
public static FilterProvider getFilterProvider() {
    if (_filterProvider == null) {
        SimpleFilterProvider _provider = new SimpleFilterProvider();
        _provider.addFilter(PropertyBeanFilterName, new BeanPropertyFilter());
        _filterProvider = _provider;
    }
    return _filterProvider;
}
 
Example 10
Source File: MetricsHttpSink.java    From beam with Apache License 2.0 5 votes vote down vote up
private String serializeMetrics(MetricQueryResults metricQueryResults) throws Exception {
  SimpleModule module = new JodaModule();
  module.addSerializer(new MetricNameSerializer(MetricName.class));
  module.addSerializer(new MetricKeySerializer(MetricKey.class));
  module.addSerializer(new MetricResultSerializer(MetricResult.class));
  objectMapper.registerModule(module);
  objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
  // need to register a filter as soon as @JsonFilter annotation is specified.
  // So specify an pass through filter
  SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAll();
  SimpleFilterProvider filterProvider = new SimpleFilterProvider();
  filterProvider.addFilter("committedMetrics", filter);
  objectMapper.setFilterProvider(filterProvider);
  String result;
  try {
    result = objectMapper.writeValueAsString(metricQueryResults);
  } catch (JsonMappingException exception) {
    if ((exception.getCause() instanceof UnsupportedOperationException)
        && exception.getCause().getMessage().contains("committed metrics")) {
      filterProvider.removeFilter("committedMetrics");
      filter = SimpleBeanPropertyFilter.serializeAllExcept("committed");
      filterProvider.addFilter("committedMetrics", filter);
      result = objectMapper.writeValueAsString(metricQueryResults);
    } else {
      throw exception;
    }
  }
  return result;
}
 
Example 11
Source File: SerializeService.java    From Web-API with MIT License 5 votes vote down vote up
public ObjectMapper getDefaultObjectMapper(boolean xml, boolean details, TreeNode perms) {
    if (perms == null) {
        throw new NullPointerException("Permissions may not be null");
    }

    ObjectMapper om = xml ? new XmlMapper() : new ObjectMapper();
    if (xml) {
        ((XmlMapper)om).configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    }
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    SimpleModule mod = new SimpleModule();
    for (Map.Entry<Class, BaseSerializer> entry : serializers.entrySet()) {
        mod.addSerializer(entry.getKey(), entry.getValue());
    }
    mod.addDeserializer(ItemStack.class, new ItemStackDeserializer());
    mod.addDeserializer(BlockState.class, new BlockStateDeserializer());
    mod.addDeserializer(ItemStackSnapshot.class, new ItemStackSnapshotDeserializer());
    mod.addDeserializer(CachedLocation.class, new CachedLocationDeserializer());
    mod.addDeserializer(CachedPlayer.class, new CachedPlayerDeserializer());
    mod.addDeserializer(CachedWorld.class, new CachedWorldDeserializer());
    mod.addDeserializer(CachedCatalogType.class, new CachedCatalogTypeDeserializer<>(CatalogType.class));
    om.registerModule(mod);

    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter(BaseFilter.ID, new BaseFilter(details, perms));
    om.setFilterProvider(filterProvider);

    om.setAnnotationIntrospector(new AnnotationIntrospector());

    return om;
}
 
Example 12
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 13
Source File: GitCatalogDao.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
public GitCatalogDao() {
    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    mapper = new ObjectMapper(factory).enable(SerializationFeature.INDENT_OUTPUT);
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("catalogEvent", new CatalogEventFilter());
    mapper.setFilterProvider(filterProvider);
}
 
Example 14
Source File: WebMvcAppContext.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = JsonObjectMapperFactory.createMapper();
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("catalogEvent", new CatalogEventFilter());
    mapper.setFilterProvider(filterProvider);
    return mapper;
}
 
Example 15
Source File: ConsoleApplier.java    From replicator with Apache License 2.0 5 votes vote down vote up
private void setupColumnsFilter(Map<String, Object> configuration) {
    this.includeInColumns.add("name");
    this.includeInColumns.add("columnType");

    this.includeInColumns.addAll(this.getAsSet(configuration.get(KafkaApplier.Configuration.INCLUDE_IN_COLUMNS)));

    LOG.info("Adding " + this.includeInColumns.toString() + " fields in metadata.columns.");

    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("column", SimpleBeanPropertyFilter.filterOutAllExcept(this.includeInColumns));
    MAPPER.setFilterProvider(filterProvider);
}
 
Example 16
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 17
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 18
Source File: JsonMapper.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public static SimpleFilterProvider exceptFilter(String id, String...properties){
	SimpleFilterProvider filterProvider = new SimpleFilterProvider();
	filterProvider.addFilter(id, SimpleBeanPropertyFilter.serializeAllExcept(properties));
	return filterProvider;
}
 
Example 19
Source File: CatalogTest.java    From logging-log4j-audit with Apache License 2.0 4 votes vote down vote up
@Test
public void testCatalogAPI() throws Exception {

    String result = mockMvc.perform(
            get("/catalog/TEST/attributes")
                    .accept(Versions.V1_0))
            .andExpect(status().is(HttpStatus.OK.value()))
            .andReturn().getResponse().getContentAsString();
    assertNotNull("No result returned for TEST catalog", result);
    ObjectMapper objectMapper = new ObjectMapper();
    CollectionType typeReference =
            TypeFactory.defaultInstance().constructCollectionType(List.class, Attribute.class);
    List<Attribute> attributes = objectMapper.readValue(result, typeReference);
    assertNotNull("Result is not a list", attributes);
    assertEquals("Incorrect number of attributes in list", 0, attributes.size());
    result = mockMvc.perform(
            get("/catalog/DEFAULT/attributes")
            .accept(Versions.V1_0))
            .andExpect(status().is(HttpStatus.OK.value()))
            .andReturn().getResponse().getContentAsString();
    assertNotNull("No result returned for DEFAULT catalog", result);

    attributes = objectMapper.readValue(result, typeReference);
    assertNotNull("Result is not a list", attributes);
    assertEquals("Incorrect number of attributes in list", 10, attributes.size());
    result = mockMvc.perform( get("/catalog/DEFAULT/events").accept(Versions.V1_0))
            .andExpect(status().is(HttpStatus.OK.value()))
            .andReturn().getResponse().getContentAsString();
    assertNotNull("No result returned for DEFAULT catalog", result);
    typeReference = TypeFactory.defaultInstance().constructCollectionType(List.class, Event.class);
    List<Event> events = objectMapper.readValue(result, typeReference);
    assertNotNull("Result is not a list", events);
    assertEquals("Incorrect number of events in list", 4, events.size());
    Event event = new Event();
    event.setName("createUser");
    event.setDescription("Create a User");
    event.setCatalogId("TEST");
    event.setDisplayName("Create User");
    List<EventAttribute> eventAttributes = new ArrayList<>();
    EventAttribute eventAttribute = new EventAttribute();
    eventAttribute.setName("loginId");
    eventAttribute.setRequired(true);
    eventAttributes.add(eventAttribute);
    eventAttribute = new EventAttribute();
    eventAttribute.setName("userId");
    eventAttribute.setRequired(true);
    eventAttributes.add(eventAttribute);
    event.setAttributes(eventAttributes);
    ObjectMapper mapper = new ObjectMapper();
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("catalogEvent", new CatalogEventFilter());
    mapper.setFilterProvider(filterProvider);
    String json = mapper.writeValueAsString(event);
    result = mockMvc.perform(post("/catalog/event").content(json).accept(Versions.V1_0).contentType(Versions.V1_0))
            .andExpect(status().is(HttpStatus.CREATED.value()))
            .andReturn().getResponse().getContentAsString();
    assertNotNull("No content returned from create user", result);
    assertTrue("Missing catalog id", result.contains("\"catalogId\":\"TEST\""));
}
 
Example 20
Source File: KafkaApplier.java    From replicator with Apache License 2.0 3 votes vote down vote up
private void setupColumnsFilter(Map<String, Object> configuration) {

        this.includeInColumns.add("name");
        this.includeInColumns.add("columnType");

        this.includeInColumns.addAll(this.getAsSet(configuration.get(Configuration.INCLUDE_IN_COLUMNS)));

        LOG.info("Adding " + this.includeInColumns.toString() + " fields in metadata.columns.");

        SimpleFilterProvider filterProvider = new SimpleFilterProvider();

        filterProvider.addFilter("column", SimpleBeanPropertyFilter.filterOutAllExcept(this.includeInColumns));

        MAPPER.setFilterProvider(filterProvider);
    }