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

The following examples show how to use com.fasterxml.jackson.databind.ser.FilterProvider. 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: 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 #2
Source File: AbstractJackson2View.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object) throws IOException {
	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);
	writePrefix(generator, object);

	Object value = object;
	Class<?> serializationView = null;
	FilterProvider filters = null;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}

	ObjectWriter objectWriter = (serializationView != null ?
			this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer());
	if (filters != null) {
		objectWriter = objectWriter.with(filters);
	}
	objectWriter.writeValue(generator, value);

	writeSuffix(generator, object);
	generator.flush();
}
 
Example #3
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 #4
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 #5
Source File: AbstractJackson2View.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object) throws IOException {
	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);
	writePrefix(generator, object);

	Object value = object;
	Class<?> serializationView = null;
	FilterProvider filters = null;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}

	ObjectWriter objectWriter = (serializationView != null ?
			this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer());
	if (filters != null) {
		objectWriter = objectWriter.with(filters);
	}
	objectWriter.writeValue(generator, value);

	writeSuffix(generator, object);
	generator.flush();
}
 
Example #6
Source File: AbstractJackson2View.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		if (serializationView != null) {
			container.setSerializationView(serializationView);
		}
		if (filters != null) {
			container.setFilters(filters);
		}
		value = container;
	}
	return value;
}
 
Example #7
Source File: AbstractJackson2View.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		if (serializationView != null) {
			container.setSerializationView(serializationView);
		}
		if (filters != null) {
			container.setFilters(filters);
		}
		value = container;
	}
	return value;
}
 
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: 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 #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 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 #11
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 #12
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 #13
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 #14
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 #15
Source File: FindConfigFileService.java    From find with MIT License 6 votes vote down vote up
protected FindConfigFileService(final FilterProvider filterProvider,
                                final TextEncryptor textEncryptor,
                                final JsonSerializer<FieldPath> fieldPathSerializer,
                                final JsonDeserializer<FieldPath> fieldPathDeserializer) {

    final ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder()
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .mixIns(customMixins())
        .serializersByType(ImmutableMap.of(FieldPath.class, fieldPathSerializer))
        .deserializersByType(ImmutableMap.of(FieldPath.class, fieldPathDeserializer))
        .createXmlMapper(false)
        .build();

    setConfigFileLocation(CONFIG_FILE_LOCATION);
    setDeprecatedConfigFileLocations(Collections.singletonList(CONFIG_FILE_LOCATION_HP));
    setConfigFileName(CONFIG_FILE_NAME);
    setDefaultConfigFile(getDefaultConfigFile());
    setMapper(objectMapper);
    setTextEncryptor(textEncryptor);
    setFilterProvider(filterProvider);
}
 
Example #16
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 #17
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 #18
Source File: OracleStorageService.java    From front50 with Apache License 2.0 5 votes vote down vote up
public OracleStorageService(OracleProperties oracleProperties) throws IOException {
  this.region = oracleProperties.getRegion();
  this.bucketName = oracleProperties.getBucketName();
  this.namespace = oracleProperties.getNamespace();
  this.compartmentId = oracleProperties.getCompartmentId();

  Supplier<InputStream> privateKeySupplier =
      new SimplePrivateKeySupplier(oracleProperties.getSshPrivateKeyFilePath());
  AuthenticationDetailsProvider provider =
      SimpleAuthenticationDetailsProvider.builder()
          .userId(oracleProperties.getUserId())
          .fingerprint(oracleProperties.getFingerprint())
          .privateKeySupplier(privateKeySupplier)
          .passPhrase(oracleProperties.getPrivateKeyPassphrase())
          .tenantId(oracleProperties.getTenancyId())
          .build();

  RequestSigner requestSigner = DefaultRequestSigner.createRequestSigner(provider);

  ClientConfig clientConfig = new DefaultClientConfig();
  client = new Client(new URLConnectionClientHandler(), clientConfig);
  client.addFilter(new OracleStorageService.RequestSigningFilter(requestSigner));

  FilterProvider filters =
      new SimpleFilterProvider()
          .addFilter(ExplicitlySetFilter.NAME, ExplicitlySetFilter.INSTANCE);
  objectMapper.setFilterProvider(filters);
}
 
Example #19
Source File: JacksonUtils.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>setObjectWriterInjector.</p>
 *
 * @param provider    a {@link javax.inject.Provider} object.
 * @param genericType a {@link java.lang.reflect.Type} object.
 * @param annotations an array of {@link java.lang.annotation.Annotation} objects.
 * @throws java.io.IOException if any.
 */
public static void setObjectWriterInjector(Provider<ObjectProvider<FilterProvider>> provider,
                                           final Type genericType,
                                           final Annotation[] annotations) throws IOException {
    final FilterProvider filterProvider = provider.get().getFilteringObject(genericType, true, annotations);
    if (filterProvider != null) {
        ObjectWriterInjector.set(new FilteringObjectWriterModifier(filterProvider, ObjectWriterInjector.getAndClear()));
    }
}
 
Example #20
Source File: JacksonFilteringFeature.java    From ameba with MIT License 5 votes vote down vote up
@Override
protected void configure() {
    bindAsContract(JacksonObjectProvider.class)
            // FilteringObjectProvider.
            .to(new GenericType<ObjectProvider<FilterProvider>>() {
            })
                    // FilteringGraphTransformer.
            .to(new GenericType<ObjectGraphTransformer<FilterProvider>>() {
            })
                    // Scope.
            .in(Singleton.class);
}
 
Example #21
Source File: HodFindConfigFileService.java    From find with MIT License 5 votes vote down vote up
@Autowired
public HodFindConfigFileService(
        final FilterProvider filterProvider,
        final TextEncryptor textEncryptor,
        final JsonSerializer<FieldPath> fieldPathSerializer,
        final JsonDeserializer<FieldPath> fieldPathDeserializer) {
    super(filterProvider, textEncryptor, fieldPathSerializer, fieldPathDeserializer);
}
 
Example #22
Source File: TestJsonFilter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testFilterOnProperty() throws Exception
{
    FilterProvider prov = new SimpleFilterProvider()
        .addFilter("RootFilter", SimpleBeanPropertyFilter.filterOutAllExcept("a"))
        .addFilter("b", SimpleBeanPropertyFilter.filterOutAllExcept("b"));

    assertEquals("{\"first\":{\"a\":\"a\"},\"second\":{\"b\":\"b\"}}",
            MAPPER.writer(prov).writeValueAsString(new FilteredProps()));
}
 
Example #23
Source File: TestJsonFilter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testSimpleInclusionFilter() throws Exception
{
    FilterProvider prov = new SimpleFilterProvider().addFilter("RootFilter",
            SimpleBeanPropertyFilter.filterOutAllExcept("a"));
    assertEquals("{\"a\":\"a\"}", MAPPER.writer(prov).writeValueAsString(new Bean()));

    ObjectMapper mapper = afterburnerMapperBuilder()
            .filterProvider(prov)
            .build();
    assertEquals("{\"a\":\"a\"}", mapper.writeValueAsString(new Bean()));
}
 
Example #24
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());
    }
 
Example #25
Source File: AbstractJackson2View.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object)
		throws IOException {

	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);

	writePrefix(generator, object);
	Class<?> serializationView = null;
	FilterProvider filters = null;
	Object value = object;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}
	if (serializationView != null) {
		this.objectMapper.writerWithView(serializationView).writeValue(generator, value);
	}
	else if (filters != null) {
		this.objectMapper.writer(filters).writeValue(generator, value);
	}
	else {
		this.objectMapper.writeValue(generator, value);
	}
	writeSuffix(generator, object);
	generator.flush();
}
 
Example #26
Source File: MappingJackson2JsonView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys modelKeys} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	model.forEach((clazz, value) -> {
		if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
				!clazz.equals(JsonView.class.getName()) &&
				!clazz.equals(FilterProvider.class.getName())) {
			result.put(clazz, value);
		}
	});
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
Example #27
Source File: MappingJackson2JsonView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys renderedAttributes} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<String, Object>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	for (Map.Entry<String, Object> entry : model.entrySet()) {
		if (!(entry.getValue() instanceof BindingResult) && modelKeys.contains(entry.getKey()) &&
				!entry.getKey().equals(JsonView.class.getName()) &&
				!entry.getKey().equals(FilterProvider.class.getName())) {
			result.put(entry.getKey(), entry.getValue());
		}
	}
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
Example #28
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 #29
Source File: AbstractJackson2View.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		container.setSerializationView(serializationView);
		container.setFilters(filters);
		value = container;
	}
	return value;
}
 
Example #30
Source File: JsonJacksonTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSerializeMultipleObjects() throws IOException
{
    final Collection<Comment> allComments = new ArrayList<Comment>();
    Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    allComments.add(aComment);
    aComment = new Comment();
    aComment.setContent("<p>I agree with the author</p>");
    allComments.add(aComment);

    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, allComments);
        }
    });
    assertTrue(out.toString().contains("content\":\"<b>There it is</b>"));
    assertTrue(out.toString().contains("content\":\"<p>I agree with the author</p>"));
}