org.springframework.http.converter.json.MappingJacksonValue Java Examples

The following examples show how to use org.springframework.http.converter.json.MappingJacksonValue. 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: SecurityJsonViewControllerAdvice.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
                                       MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
    if (SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<Class> jsonViews = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .map(AppConfig.Role::valueOf)
                .map(View.MAPPING::get)
                .collect(Collectors.toList());
        if (jsonViews.size() == 1) {
            bodyContainer.setSerializationView(jsonViews.get(0));
            return;
        }
        throw new IllegalArgumentException("Ambiguous @JsonView declaration for roles "+ authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")));
    }
}
 
Example #2
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 #3
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 #4
Source File: MappingJackson2XmlHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jsonView() throws Exception {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");

	MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
	jacksonValue.setSerializationView(MyJacksonView1.class);
	this.converter.write(jacksonValue, null, outputMessage);

	String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
	assertThat(result, containsString("<withView1>with</withView1>"));
	assertThat(result, not(containsString("<withView2>with</withView2>")));
	assertThat(result, not(containsString("<withoutView>without</withoutView>")));
}
 
Example #5
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 #6
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 #7
Source File: MappingJackson2XmlHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jsonView() throws Exception {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");

	MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
	jacksonValue.setSerializationView(MyJacksonView1.class);
	this.converter.write(jacksonValue, null, outputMessage);

	String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
	assertThat(result, containsString("<withView1>with</withView1>"));
	assertThat(result, not(containsString("<withView2>with</withView2>")));
	assertThat(result, not(containsString("<withoutView>without</withoutView>")));
}
 
Example #8
Source File: UserController.java    From learning-taotaoMall with MIT License 6 votes vote down vote up
@RequestMapping("/token/{token}")
public Object getUserByToken(@PathVariable String token, String callback) {
	TaotaoResult result = null;
	try {
		result = userService.getUserByToken(token);
	} catch (Exception e) {
		e.printStackTrace();
		result = TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
	}

	//判断是否为jsonp调用
	if (StringUtils.isBlank(callback)) {
		return result;
	} else {
		MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
		mappingJacksonValue.setJsonpFunction(callback);
		return mappingJacksonValue;
	}

}
 
Example #9
Source File: MappingJackson2JsonView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = super.filterAndWrapModel(model, request);
	String jsonpParameterValue = getJsonpParameterValue(request);
	if (jsonpParameterValue != null) {
		if (value instanceof MappingJacksonValue) {
			((MappingJacksonValue) value).setJsonpFunction(jsonpParameterValue);
		}
		else {
			MappingJacksonValue container = new MappingJacksonValue(value);
			container.setJsonpFunction(jsonpParameterValue);
			value = container;
		}
	}
	return value;
}
 
Example #10
Source File: AbstractJsonpResponseBodyAdvice.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	for (String name : this.jsonpQueryParamNames) {
		String value = servletRequest.getParameter(name);
		if (value != null) {
			if (!isValidJsonpQueryParam(value)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Ignoring invalid jsonp parameter value: " + value);
				}
				continue;
			}
			MediaType contentTypeToUse = getContentType(contentType, request, response);
			response.getHeaders().setContentType(contentTypeToUse);
			bodyContainer.setJsonpFunction(value);
			break;
		}
	}
}
 
Example #11
Source File: MappingJackson2JsonView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = super.filterAndWrapModel(model, request);
	String jsonpParameterValue = getJsonpParameterValue(request);
	if (jsonpParameterValue != null) {
		if (value instanceof MappingJacksonValue) {
			((MappingJacksonValue) value).setJsonpFunction(jsonpParameterValue);
		}
		else {
			MappingJacksonValue container = new MappingJacksonValue(value);
			container.setJsonpFunction(jsonpParameterValue);
			value = container;
		}
	}
	return value;
}
 
Example #12
Source File: AbstractJsonpResponseBodyAdvice.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	for (String name : this.jsonpQueryParamNames) {
		String value = servletRequest.getParameter(name);
		if (value != null) {
			if (!isValidJsonpQueryParam(value)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Ignoring invalid jsonp parameter value: " + value);
				}
				continue;
			}
			MediaType contentTypeToUse = getContentType(contentType, request, response);
			response.getHeaders().setContentType(contentTypeToUse);
			bodyContainer.setJsonpFunction(value);
			break;
		}
	}
}
 
Example #13
Source File: MappingJackson2XmlHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jsonView() throws Exception {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");

	MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
	jacksonValue.setSerializationView(MyJacksonView1.class);
	this.writeInternal(jacksonValue, outputMessage);

	String result = outputMessage.getBodyAsString(Charset.forName("UTF-8"));
	assertThat(result, containsString("<withView1>with</withView1>"));
	assertThat(result, not(containsString("<withView2>with</withView2>")));
	assertThat(result, not(containsString("<withoutView>without</withoutView>")));
}
 
Example #14
Source File: PageResponseBodyAdvisor.java    From spring-boot-jpa with Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer,
		MediaType contentType, MethodParameter returnType,
		ServerHttpRequest request, ServerHttpResponse response) {

	Page<?> page = ((Page<?>) bodyContainer.getValue());

	response.getHeaders().add(CUSTOM_HEADER_META_PAGINATION,
			String.format(PAGE_METADATA_FMT, page.getNumber(), page.getSize(),
					page.getTotalElements(), page.getTotalPages(), page.isFirst(),
					page.isLast()));

	getHttpHeaderLinksString(request, page)
			.filter(StringUtils::isNotEmpty)
			.ifPresent(s -> response.getHeaders().add(HttpHeaders.LINK, s));

	// finally, strip out the actual content and replace it as the body value
	bodyContainer.setValue(page.getContent());
}
 
Example #15
Source File: ExtJackson2HttpMessageConverter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected Object filterAndWrapModel(Object value, HttpOutputMessage outputMessage, HttpServletRequest request) {
	String jsonpParameterValue = getJsonpParameterValue(request);
	if (jsonpParameterValue != null) {
		if (value instanceof MappingJacksonValue) {
			((MappingJacksonValue) value).setJsonpFunction(jsonpParameterValue);
		}
		else {
			MappingJacksonValue container = new MappingJacksonValue(value);
			container.setJsonpFunction(jsonpParameterValue);
			value = container;
		}
		outputMessage.getHeaders().setContentType(MediaType.parseMediaType("application/javascript"));
	}
	if (value instanceof Optional) {
		Optional<?> opt = (Optional<?>) value;
		value = opt.orElse(null);
	}
	return value;
}
 
Example #16
Source File: GroupController.java    From osiam with MIT License 5 votes vote down vote up
@RequestMapping(value = "/.search", method = RequestMethod.POST)
public MappingJacksonValue searchWithPost(@RequestParam Map<String, String> requestParameters) {
    SCIMSearchResult<Group> scimSearchResult = scimGroupProvisioning.search(requestParameters.get("filter"),
            requestParameters.get("sortBy"),
            requestParameters.getOrDefault("sortOrder", "ascending"),
            Integer.parseInt(requestParameters.getOrDefault("count", "" + SCIMSearchResult.MAX_RESULTS)),
            Integer.parseInt(requestParameters.getOrDefault("startIndex", "1")));

    String attributes = (requestParameters.containsKey("attributes") ? requestParameters.get("attributes") : "");
    return buildResponse(scimSearchResult, attributes);
}
 
Example #17
Source File: GroupController.java    From osiam with MIT License 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<MappingJacksonValue> replace(@PathVariable final String id,
                                                   @RequestBody @Valid Group group,
                                                   @RequestParam(required = false) String attributes,
                                                   UriComponentsBuilder builder)
        throws IOException {
    Group updatedGroup = scimGroupProvisioning.replace(id, group);
    return buildResponseWithLocation(updatedGroup, builder, HttpStatus.OK, attributes);
}
 
Example #18
Source File: OrganizationController.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<MappingJacksonValue> create(@RequestBody  Organization user,
                                                  @RequestParam(required = false) String attributes,
                                                  UriComponentsBuilder builder) throws IOException {
    Organization createdUser = null;
    return null;
}
 
Example #19
Source File: UserController.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/.search", method = RequestMethod.POST)
    public MappingJacksonValue searchWithPost(@RequestParam Map<String, String> requestParameters) {
        ScimSearchResult<User> scimSearchResult = null;
        /*
                requestParameters.get("filter"),
                requestParameters.get("sortBy"),
                requestParameters.getOrDefault("sortOrder", "ascending"),             // scim default
                Integer.parseInt(requestParameters.getOrDefault("count", "" + ServiceProviderConfigController.MAX_RESULTS)),
                Integer.parseInt(requestParameters.getOrDefault("startIndex", "1")); // scim default
*/
        String attributes = (requestParameters.containsKey("attributes") ? requestParameters.get("attributes") : "");
        return null;
    }
 
Example #20
Source File: UserController.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<MappingJacksonValue> replace(@PathVariable String id,
                                                   @RequestBody User user,
                                                   @RequestParam(required = false) String attributes)
        throws IOException {
    User createdUser = null;
    return null;
}
 
Example #21
Source File: UserController.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<MappingJacksonValue> create(@RequestBody  User user,
                                                  @RequestParam(required = false) String attributes,
                                                  UriComponentsBuilder builder) throws IOException {
    User createdUser = null;
    return null;
}
 
Example #22
Source File: AliyunOssController.java    From zheng with MIT License 5 votes vote down vote up
/**
 * 签名生成
 * @param callback 跨域请求
 * @return
 */
@GetMapping("/policy")
@ResponseBody
//@CrossOrigin(origins = "*", methods = RequestMethod.GET) // 该注解不支持JDK1.7
public Object policy(@RequestParam(required = false) String callback) {
	JSONObject result = aliyunOssService.policy();
	if (StringUtils.isBlank(callback)) {
		return result;
	}
	MappingJacksonValue jsonp = new MappingJacksonValue(result);
	jsonp.setJsonpFunction(callback);
	return jsonp;
}
 
Example #23
Source File: AbstractMappingJacksonResponseBodyAdvice.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public final Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	if (body == null) {
		return null;
	}
	MappingJacksonValue container = getOrCreateContainer(body);
	beforeBodyWriteInternal(container, contentType, returnType, request, response);
	return container;
}
 
Example #24
Source File: RestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void jsonPostForObjectWithJacksonView() throws URISyntaxException {
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
	MySampleBean bean = new MySampleBean("with", "with", "without");
	MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
	jacksonValue.setSerializationView(MyJacksonView1.class);
	HttpEntity<MappingJacksonValue> entity = new HttpEntity<MappingJacksonValue>(jacksonValue, entityHeaders);
	String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class, "post");
	assertTrue(s.contains("\"with1\":\"with\""));
	assertFalse(s.contains("\"with2\":\"with\""));
	assertFalse(s.contains("\"without\":\"without\""));
}
 
Example #25
Source File: RequestMappingHandlerAdapterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	int status = ((ServletServerHttpResponse) response).getServletResponse().getStatus();
	response.setStatusCode(HttpStatus.OK);

	Map<String, Object> map = new LinkedHashMap<>();
	map.put("status", status);
	map.put("message", bodyContainer.getValue());
	bodyContainer.setValue(map);
}
 
Example #26
Source File: AbstractMappingJacksonResponseBodyAdvice.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public final Object beforeBodyWrite(Object body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	MappingJacksonValue container = getOrCreateContainer(body);
	beforeBodyWriteInternal(container, contentType, returnType, request, response);
	return container;
}
 
Example #27
Source File: JsonViewResponseBodyAdvice.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	JsonView annotation = returnType.getMethodAnnotation(JsonView.class);
	Class<?>[] classes = annotation.value();
	if (classes.length != 1) {
		throw new IllegalArgumentException(
				"@JsonView only supported for response body advice with exactly 1 class argument: " + returnType);
	}
	bodyContainer.setSerializationView(classes[0]);
}
 
Example #28
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 #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: OrganizationController.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<MappingJacksonValue> replace(@PathVariable String id,
                                                   @RequestBody Organization user,
                                                   @RequestParam(required = false) String attributes)
        throws IOException {
    Organization createdUser = null;
    return null;
}