Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#setFilterProvider()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#setFilterProvider() . 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: 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 2
Source File: JsonUtils.java    From knox with Apache License 2.0 6 votes vote down vote up
public static String renderAsJsonString(Object obj, FilterProvider filterProvider, DateFormat dateFormat) {
  String json = null;
  ObjectMapper mapper = new ObjectMapper();
  if (filterProvider != null) {
    mapper.setFilterProvider(filterProvider);
  }

  if (dateFormat != null) {
    mapper.setDateFormat(dateFormat);
  }

  try {
    // write JSON to a file
    json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
  } catch ( JsonProcessingException e ) {
    LOG.failedToSerializeObjectToJSON( obj, e );
  }
  return json;
}
 
Example 3
Source File: JsonMapper.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public JsonMapper(ObjectMapper objectMapper, Include include, boolean fieldVisibility){
		objectMapper.setSerializationInclusion(include);
//		objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
//		setDateFormat(DateUtils.DATE_TIME);
		objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		objectMapper.configure(Feature.ALLOW_COMMENTS, true);
//		objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		if(fieldVisibility)
			objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		objectMapper.setFilterProvider(filterProvider);
//		objectMapper.addMixIn(target, mixinSource);
		this.objectMapper = objectMapper;
		this.typeFactory = this.objectMapper.getTypeFactory();
	}
 
Example 4
Source File: LogicalPlanPersistence.java    From Bats with Apache License 2.0 6 votes vote down vote up
public LogicalPlanPersistence(DrillConfig conf, ScanResult scanResult, ObjectMapper mapper) {
  this.mapper = mapper;

  SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

  mapper.registerModule(deserModule);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
  mapper.configure(Feature.ALLOW_COMMENTS, true);
  mapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));
  registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult));
  registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult));
  registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult));
}
 
Example 5
Source File: BaseTestServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper() {
  ObjectMapper objectMapper = JSONUtil.prettyMapper();
  JSONUtil.registerStorageTypes(objectMapper, DremioTest.CLASSPATH_SCAN_RESULT,
    ConnectionReader.of(DremioTest.CLASSPATH_SCAN_RESULT, DremioTest.DEFAULT_SABOT_CONFIG));
  objectMapper.registerModule(
      new SimpleModule()
          .addDeserializer(JobDataFragment.class,
              new JsonDeserializer<JobDataFragment>() {
                @Override
                public JobDataFragment deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                  return jsonParser.readValueAs(DataPOJO.class);
                }
              }
          )
  );
  objectMapper.setFilterProvider(new SimpleFilterProvider().addFilter(SentinelSecure.FILTER_NAME, SentinelSecureFilter.TEST_ONLY));
  return objectMapper;
}
 
Example 6
Source File: TestSentinelSecureFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureTestOnlyWithNull() throws IOException {
  ObjectMapper mapper = JSONUtil.mapper();
  mapper.setFilterProvider(new SimpleFilterProvider().addFilter(SentinelSecure.FILTER_NAME, SentinelSecureFilter.TEST_ONLY));
  Example e1 = new Example(null, "bar");
  Example e2 = mapper.readValue(mapper.writeValueAsString(e1), Example.class);
  assertEquals(e1.getSecured(), e2.getSecured());
}
 
Example 7
Source File: TestSentinelSecureFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureTestOnlyWithValue() throws IOException {
  ObjectMapper mapper = JSONUtil.mapper();
  mapper.setFilterProvider(new SimpleFilterProvider().addFilter(SentinelSecure.FILTER_NAME, SentinelSecureFilter.TEST_ONLY));
  Example e1 = new Example("secret", "bar");
  Example e2 = mapper.readValue(mapper.writeValueAsString(e1), Example.class);
  assertEquals(e1.getSecured(), e2.getSecured());
}
 
Example 8
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 9
Source File: CerebroController.java    From cerebro with GNU Affero General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(CerebroException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public String getErrorCode(final CerebroException exception) throws IOException {
    LOGGER.error("Service error", exception);
    ObjectMapper objectMapper = new ObjectMapper();
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("responseFilter",
        SimpleBeanPropertyFilter.filterOutAllExcept("errorCode", "errorMessage"));
    objectMapper.setFilterProvider(filterProvider);
    return objectMapper.writeValueAsString(exception);
}
 
Example 10
Source File: JsonOutputFilter.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the Jackson json object mapper
 */
protected void initJsonMapper() {
    jsonMapper = new ObjectMapper();
    jsonMapper.registerModule(new IbdoModule());
    jsonMapper.addMixIn(IBaseDataObject.class, IbdoMixin.class);
    // the id in addFilter must match the annotation for JsonFilter
    jsonMapper.setFilterProvider(new SimpleFilterProvider().addFilter("param_filter", new IbdoParameterFilter()));
}
 
Example 11
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 12
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 13
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 14
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 15
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 16
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 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: 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 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\""));
}