@Test public void findAllTest2() throws Exception { Auction auction = new Auction(); auction.setRealmId(1); auction.setItemId(124105); List<Auction> auctions = auctionService.findAll(auction); ObjectMapper mapper = new ObjectMapper(); FilterProvider filters = new SimpleFilterProvider().addFilter("auctionFilter", SimpleBeanPropertyFilter.filterOutAllExcept("owner")); MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(auctions); mappingJacksonValue.setFilters(filters); System.out.println(mappingJacksonValue.getValue()); }
@Override protected void beforeBodyWriteInternal(final MappingJacksonValue bodyContainer, final MediaType contentType, final MethodParameter returnType, final ServerHttpRequest request, final ServerHttpResponse response) { final Mutable<Class<?>> viewClass = Mutable.of(View.Anonymous.class); if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) { final Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities(); viewClass.mutateIf(View.User.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_USER"))); viewClass.mutateIf(View.Moderator.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_MODERATOR"))); viewClass.mutateIf(View.Admin.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_ADMIN"))); } bodyContainer.setSerializationView(viewClass.get()); }
@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; }
@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; } } }
@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>"))); }
@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()); }
private WarehouseTask createWarehouseTask(final String targetUri, final HttpMethod httpMethod, final WarehouseS3Credentials s3Credentials, final HttpEntity<MappingJacksonValue> requestEntity, final Object... args) { try { final HttpEntity<WarehouseTask> taskHttpEntity = restTemplate.exchange(targetUri, httpMethod, requestEntity, WarehouseTask.class, args); if (taskHttpEntity == null || taskHttpEntity.getBody() == null) { throw new WarehouseS3CredentialsException(targetUri, format("Empty response when trying to %s S3 credentials via API", httpMethod.name())); } return taskHttpEntity.getBody(); } catch (GoodDataException | RestClientException e) { final String expandedTargetUri = new UriTemplate(targetUri).expand(args).toString(); throw new WarehouseS3CredentialsException(targetUri, format("Unable to %s S3 credentials %s with region: %s, access key: %s", httpMethod.name(), expandedTargetUri, s3Credentials.getRegion(), s3Credentials.getAccessKey()), e); } }
@Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { ((ResponseBodyMessage) bodyContainer.getValue()).businessMsg = "xxxxxxxxxxxxxx"; }
/** * 签名生成 * @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; }
/** * 重写callback方法,使即支持jsonp格式也支持json格式 */ @Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); //如果不存在callback这个请求参数,直接返回,不需要处理为jsonp if (ObjectUtils.isEmpty(servletRequest.getParameter("callback"))) { return; } //按设定的请求参数(JsonAdvice构造方法中的this.jsonpQueryParamNames = new String[]{"callback"};),处理返回结果为jsonp格式 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); return; } } }
@Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { response.getHeaders().set("Access-Control-Allow-Headers", "Origin,No-Cache,X-Requested-with,If-Modified-Since,Last-Modified,Cache-Control,Expires,Content-Type"); response.getHeaders().set("Access-Control-Allow-Origin", "*"); response.getHeaders().set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE"); response.getHeaders().set("Access-Control-Max-Age", "1512000"); }
@Override protected void beforeBodyWriteInternal(final MappingJacksonValue bodyContainer, final MediaType contentType, final MethodParameter returnType, final ServerHttpRequest request, final ServerHttpResponse response) { final HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); if (isGET(servletRequest) && isJsonpURI(servletRequest)) { super.beforeBodyWriteInternal(bodyContainer, contentType, returnType, request, response); } }
@Override protected void writePrefix(JsonGenerator generator, Object object) throws IOException { if (this.jsonPrefix != null) { generator.writeRaw(this.jsonPrefix); } String jsonpFunction = null; if (object instanceof MappingJacksonValue) { jsonpFunction = ((MappingJacksonValue) object).getJsonpFunction(); } if (jsonpFunction != null) { generator.writeRaw("/**/"); generator.writeRaw(jsonpFunction + "(" ); } }
@Override protected void writeSuffix(JsonGenerator generator, Object object) throws IOException { String jsonpFunction = null; if (object instanceof MappingJacksonValue) { jsonpFunction = ((MappingJacksonValue) object).getJsonpFunction(); } if (jsonpFunction != null) { generator.writeRaw(");"); } }
/** * 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; }
/** * 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(); }
@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]); }
@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; }
@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); }
@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\"")); }
@RequestMapping(value = "/leaguemanager/teams") public MappingJacksonValue getSomething2(@RequestParam(value = "fields", required = false) String fields) { Page<Team> r = teamRepository.findAll(new PageRequest(0, 20), 1); MappingJacksonValue response = new MappingJacksonValue(r); if (fields != null) { response.setFilters(processFilterFields(fields, Team.class)); } return response; }
/** * Constructor. Creates a order 'database' (list with a single Order) and configures the view and adapter maps. */ public Controller() { orderDb.add(new Order(1, "John", "Williams", currentTimeMillis(), new Order.Item("Milk", 4, "2.99"), new Order.Item("Bread", 2, "3.45"))); viewMap.put(1, View.Version1.class); adapterMap.put(1, o -> new MappingJacksonValue(new OrderV1(o))); }
/** * GET request that sets a View based on the protocol version and then serializes the Order to JSON. * @param id the ID of the Order * @return a serializable representation of the view. */ @RequestMapping(value = "/method1/{id}", method = RequestMethod.GET) public MappingJacksonValue getMethod1(@PathVariable int id) { MappingJacksonValue result = new MappingJacksonValue(find(id)); result.setSerializationView(getOrderView()); return result; }
@RequestMapping(method = RequestMethod.GET) public MappingJacksonValue getCurrentUser(@RequestHeader("Authorization") String tokenHeader, @RequestParam(required = false) String attributes, HttpServletResponse response, UriComponentsBuilder builder) { if (Strings.isNullOrEmpty(tokenHeader)) { throw new IllegalArgumentException("No access token provided!"); // This should never happen! } String accessToken = tokenHeader.substring("Bearer ".length()); OAuth2Authentication oAuth = resourceServerTokenServices.loadAuthentication(accessToken); if (oAuth.isClientOnly()) { throw new InvalidTokenException("Can't return an user. This access token belongs to a client."); } Authentication userAuthentication = oAuth.getUserAuthentication(); Object principal = userAuthentication.getPrincipal(); User user; if (principal instanceof User) { user = userProvisioning.getById(((User) principal).getId()); } else { throw new IllegalArgumentException("User not authenticated."); } response.setHeader("Location", buildLocation(user, builder).toString()); return buildResponse(user, attributes); }
@RequestMapping(method = RequestMethod.POST) public ResponseEntity<MappingJacksonValue> create(@RequestBody @Valid Group group, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { Group createdGroup = scimGroupProvisioning.create(group); return buildResponseWithLocation(createdGroup, builder, HttpStatus.CREATED, attributes); }
@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); }
@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); }
@RequestMapping(method = RequestMethod.POST) public ResponseEntity<MappingJacksonValue> create(@RequestBody @Valid User user, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { User createdUser = scimUserProvisioning.create(user); return buildResponseWithLocation(createdUser, builder, HttpStatus.CREATED, attributes); }
@RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity<MappingJacksonValue> replace(@PathVariable String id, @RequestBody @Valid User user, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { User createdUser = scimUserProvisioning.replace(id, user); checkAndHandleDeactivation(id, user); return buildResponseWithLocation(createdUser, builder, HttpStatus.OK, attributes); }
@RequestMapping(value = "/.search", method = RequestMethod.POST) public MappingJacksonValue searchWithPost(@RequestParam Map<String, String> requestParameters) { SCIMSearchResult<User> scimSearchResult = scimUserProvisioning.search( requestParameters.get("filter"), requestParameters.get("sortBy"), requestParameters.getOrDefault("sortOrder", "ascending"), // scim default Integer.parseInt(requestParameters.getOrDefault("count", "" + SCIMSearchResult.MAX_RESULTS)), Integer.parseInt(requestParameters.getOrDefault("startIndex", "1"))); // scim default String attributes = (requestParameters.containsKey("attributes") ? requestParameters.get("attributes") : ""); return buildResponse(scimSearchResult, attributes); }
protected ResponseEntity<MappingJacksonValue> buildResponseWithLocation(T resource, UriComponentsBuilder builder, HttpStatus status, String attributes) { HttpHeaders headers = new HttpHeaders(); URI location = buildLocation(resource, builder); headers.setLocation(location); MappingJacksonValue response = buildResponse(resource, attributes); return new ResponseEntity<>(response, headers, status); }
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; }
/** * Get all Seats in the Seatmap. * * @param admin Boolean for admins to view full data. * * @return A list of all Seats in the seatmap. */ @PreAuthorize("isAuthenticated()") @GetMapping MappingJacksonValue getAllSeats(@RequestParam(value = "admin", required = false) boolean admin, @AuthenticationPrincipal User user) { MappingJacksonValue result = new MappingJacksonValue(seatService.getAllSeats()); if (!admin || !user.getAuthorities().contains(Role.ROLE_ADMIN)) { result.setSerializationView(View.Public.class); } return result; }
/** * Get all Seats in a group. * * @param group The name of the Seat group. * @param admin Boolean for admins to view full data. * @return A List of Seats in a group. */ @PreAuthorize("isAuthenticated()") @GetMapping("/{group}") MappingJacksonValue getSeatGroupByName(@PathVariable String group, @RequestParam(value = "admin", required = false) boolean admin, @AuthenticationPrincipal User user) { MappingJacksonValue result = new MappingJacksonValue(seatService.getSeatGroupByName(group)); if (!admin || !user.getAuthorities().contains(Role.ROLE_ADMIN)) { result.setSerializationView(View.Public.class); } return result; }
/** * Get a Seat based on seatGroup and seatNumber * * @param group Group of the Seat * @param number Number in the group of the Seat * @param admin Boolean for admins to view full data. * * @return The seat at the given location */ @PreAuthorize("isAuthenticated()") @GetMapping("/{group}/{number}") MappingJacksonValue getSeatByGroupAndNumber(@PathVariable String group, @PathVariable int number, @RequestParam(value = "admin", required = false) boolean admin, @AuthenticationPrincipal User user) { MappingJacksonValue result = new MappingJacksonValue(seatService.getSeatBySeatGroupAndSeatNumber(group, number)); if (!admin || !user.getAuthorities().contains(Role.ROLE_ADMIN)) { result.setSerializationView(View.Public.class); } return result; }
/** * delete S3 credentials in the Warehouse * * @param s3Credentials the credentials to delete * @return nothing (Void) * @throws WarehouseS3CredentialsException in case of failure during the REST operation */ public FutureResult<Void> removeS3Credentials(final WarehouseS3Credentials s3Credentials) { notNull(s3Credentials, "s3Credentials"); notNull(s3Credentials.getUri(), "s3Credentials.links.self"); final HttpEntity<MappingJacksonValue> emptyRequestEntity = new HttpEntity<>(new HttpHeaders()); final WarehouseTask task = createWarehouseTask(s3Credentials.getUri(), HttpMethod.DELETE, s3Credentials, emptyRequestEntity); return new PollResult<>(this, createS3PollHandler(s3Credentials.getUri(), task, Void.class, "delete")); }
@Override protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { resolveFilter(returnType).map(DynamicFilterProvider::new).ifPresent(bodyContainer::setFilters); }
private MappingJacksonValue adapt(Order order) { return adapterMap .getOrDefault(getProtocolVersion(), MappingJacksonValue::new) .apply(order); }