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

The following examples show how to use com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: InternalConfigStateController.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected ObjectMapper initializeObjectMapper() {
    final ObjectMapper mapper = super.initializeObjectMapper();

    final FilterProvider filters = new SimpleFilterProvider()
            .addFilter("beanObjectFilter", new CasSimpleBeanObjectFilter());
    mapper.setFilters(filters);

    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.addMixIn(Object.class, CasSimpleBeanObjectFilter.class);
    mapper.disable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    return mapper;
}
 
Example #9
Source File: JsonJacksonTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSerializeComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\""));
}
 
Example #10
Source File: JsonJacksonTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testNullInComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent(null);
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertEquals("Null values should not be output.", "{\"canEdit\":false,\"canDelete\":false}",
                out.toString());
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: PartialResponse.java    From ReCiter with Apache License 2.0 5 votes vote down vote up
public PartialResponse(final Object value, final String... filters) {
    super(value);
    if (null == filters || filters.length <= 0) {
        setFilters(new SimpleFilterProvider().addFilter("antPathFilter", new AntPathPropertyFilter("**")));
    } else {
        setFilters(new SimpleFilterProvider().addFilter("antPathFilter", new AntPathPropertyFilter(filters)));
    }
}
 
Example #18
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 #19
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setFilters() throws JsonProcessingException {
	this.factory.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	JacksonFilteredBean bean = new JacksonFilteredBean("value1", "value2");
	String output = objectMapper.writeValueAsString(bean);
	assertThat(output, containsString("value1"));
	assertThat(output, containsString("value2"));
}
 
Example #20
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 #21
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 #22
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 #23
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 #24
Source File: ObjectMapperExceptField.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public ObjectMapperExceptField(Class<?> targetClass, String property) {
    super();
    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept(property);
    FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
    addMixInAnnotations(targetClass, PropertyFilterMixIn.class);
    setFilters(filters);
}
 
Example #25
Source File: TemplateEngine.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public TemplateEngine(String template) {
    SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider();
    simpleFilterProvider.setFailOnUnknownId(false);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setFilters(simpleFilterProvider);

    handlebars = new Handlebars(new ClassPathTemplateLoader("/", ""));
    handlebars.registerHelper("json", new Jackson2Helper(objectMapper));
    handlebars.registerHelper("join", StringHelpers.join);
    handlebars.registerHelper("ifequal", IfEqualHelper.INSTANCE);
    handlebars.prettyPrint(true);

    location = "templates/" + template;
}
 
Example #26
Source File: ConfigFileConfiguration.java    From find with MIT License 5 votes vote down vote up
@Bean
public SimpleFilterProvider filterProvider() {
    final Set<String> set = ImmutableSet.of(
            "indexProtocol",
            "indexPort",
            "serviceProtocol",
            "servicePort",
            "productType",
            "productTypeRegex",
            "indexErrorMessage",
            "plaintextPassword",
            "currentPassword"
    );

    final SimpleBeanPropertyFilter.SerializeExceptFilter filter = new SimpleBeanPropertyFilter.SerializeExceptFilter(set);

    return new SimpleFilterProvider(ImmutableMap.of("configurationFilter", filter));
}
 
Example #27
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 #28
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 #29
Source File: PageResource.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping(value = "/{pageId}", method = RequestMethod.GET)
public MappingJacksonValue get(@PathVariable("pageId") String pageId)
        throws NotFoundException, RepositoryException {
    Page page = pageService.get(pageId);
    page.setAssets(assetVisitor.visit(page));

    FilterProvider filters = new SimpleFilterProvider()
            .addFilter("valueAsArray", SimpleBeanPropertyFilter.serializeAllExcept("value"));
    MappingJacksonValue mapping = new MappingJacksonValue(page);
    mapping.setFilters(filters);

    return mapping;
}
 
Example #30
Source File: ObjectMapperFactory.java    From etf-webapp with European Union Public License 1.2 5 votes vote down vote up
public ObjectMapperFactory() {

        mapper.addMixIn(ModelItemDto.class, BaseMixin.class);
        mapper.addMixIn(Dto.class, BaseMixin.class);
        mapper.addMixIn(ExecutableTestSuiteDto.class, ExecutableTestSuiteDtoMixin.class);
        mapper.addMixIn(TranslationTemplateDto.class, TranslationTemplateMixin.class);
        mapper.addMixIn(TestObjectDto.class, TestObjectDtoMixin.class);

        // important!
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        final FilterProvider filters = new SimpleFilterProvider().setDefaultFilter(baseFilter)
                .addFilter("translationTemplateFilter", translationTemplateFilter).addFilter("etsFilter", etsFilter)
                .addFilter("testObjectFilter", testObjectFilter);
        mapper.setFilterProvider(filters);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        final SimpleModule etfModule = new SimpleModule("EtfModule",
                new Version(1, 0, 0, null,
                        "de.interactive_instruments", "etf"));

        etfModule.addSerializer(EID.class, new EidConverter().jsonSerializer());
        etfModule.addDeserializer(EID.class, new EidConverter().jsonDeserializer());

        etfModule.addSerializer(de.interactive_instruments.Version.class, new VersionConverter().jsonSerializer());
        etfModule.addDeserializer(de.interactive_instruments.Version.class, new VersionConverter().jsonDeserializer());
        // Prevent XSS
        etfModule.addDeserializer(String.class, new JsonHtmlXssDeserializer());

        mapper.registerModule(etfModule);

        mapper.getFactory().setCharacterEscapes(new HTMLCharacterEscapes());
    }