I currently have the following controller method (it's a bit simplified to only show the relevant part):
#PostMapping(...)
...
public ResponseEntity<List<PresignedUrlsResponse>> getPresignedUrlBatch(#Valid #RequestBody PresignedUrlsRequest urlsRequest) {
List<PresignedUrlsResponse> presignedUrlResponses = urlsRequest.getRequests().stream().map(request -> {
// TODO: put this in it's own mapping
String url = this.mediaService.getPresignedUrl(request.getObjectId(), request.getBucket());
PresignedUrlsResponse response = new PresignedUrlsResponse();
response.setId(request.getId());
response.setUrl(url);
return response;
}).collect(Collectors.toList());
return ResponseEntity.ok().body(presignedUrlResponses);
}
As mentioned in the TODO, I want to simplify this controller method and add a mapper. I'm only used to mapping requests from a db call for example (in which I will get a List of entities) but not when the service method has to be called for a list of items.
Is there a best practice for this?
MapStruct supports mapping Stream to Collection and Stream to Stream.
However, in your use case you start with List and not with Stream.
You can move your entire logic in a mapper.
e.g.
#Mapper(componentModel = "spring", uses = {
PresignedUrlMappingService.class
})
public interface PresignedUrlsMapper {
List<PresignedUrlsResponse> map(List<PresignedUrlsRequest> requests);
#Mapping(target = "url", source = "request", qualifiedByName = "presignedUrl")
PresignedUrlsResponse map(PresignedUrlsRequest request);
}
Your PresignedUrlMappingService can look like:
#Service
public class PresignedUrlMappingService {
protected final MediaService mediaService;
public PresignedUrlMappingService(MediaService mediaService) {
this.mediaService = mediaService;
}
#Named("presignedUrl")
public String presignedUrl(PresignedUrlsRequest request) {
return this.mediaService.getPresignedUrl(request.getObjectId(), request.getBucket())
}
}
and finally your controller method will look like:
#PostMapping(...)
...
public ResponseEntity<List<PresignedUrlsResponse>> getPresignedUrlBatch(#Valid #RequestBody PresignedUrlsRequest urlsRequest) {
return ResponseEntity.ok().body(presignedUrlsMapper.map(urlsRequest.getRequests());
}
Related
I was trying to get the body of "users" in HttpRequest body from ServerRequest. I am using RouterFunction for this. This "users" key contains a list of users.
After that, I need to extract this list of users to get the Flux from a repository and return back to frontend. How can I achieve that?
#Repository
public interface UserRepository extends ReactiveCrudRepository<User, Integer> {
Flux<Account> findByUserIn(List userList);
}
How to modify the below code for it to work?
public Mono<ServerResponse> getUserList(ServerRequest request) {
Flux<User> users = request.bodyToMono(String.class).doOnSuccess(x -> {
JSONObject jObject = new JSONObject(x);
List userList= jObject.getJSONArray("users").toList();
userRepository.findByUserIn(userList);
})
return ServerResponse.ok().body(users, Repo.class);
}
I found the answer, stuck because of a few typos, and thanks to Toerktumlare pointing it out. I need to use flatMapMany.
public Mono<ServerResponse> getUserList(ServerRequest request) {
Flux<User> results = request.bodyToMono(String.class)
.flatMapMany(x -> {
JSONObject req = new JSONObject(x);
List userList = req.getJSONArray("users").toList();
return userRepository.findByUserIn(userList);
});
return ServerResponse.ok().body(results, User.class);
}
I am trying to write a feign client to make calls to retrieve data from a server where the api accepts a list of identical named query parameters to determine how much data is being asked. Here is an example url I am trying to hit:
http://some-server/some-endpoint/{id}?include=profile&include=account&include=address&include=email
So far for my feign client I'm attempting to set it up this way:
#FeignClient("some-server")
public interface SomeServerClient {
#RequestMapping(method = RequestMethod.GET,
value = "/customers/api/customers/{id}",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
Map<Object, Object> queryById(
#PathVariable long id,
#RequestParam("include[]") String ... include);
default Map<Object, Object> queryById(long id) {
return queryById(id,"profile", "account", "address", "email");
}
However this doesn't appear t format the request in the way desired, so my question is how can I set up my feign client to submit its request to the url as shown in the example above?
use #RequestParam("include") List<String> includes, example:
client:
#FeignClient(value = "foo-client")
public interface FooClient {
#GetMapping("/foo")
Foo getFoo(#RequestParam("include") List<String> includes);
}
controller:
#RestController
public class FooController {
#GetMapping("/foo")
public Foo getFoo(#RequestParam("include") List<String> includes) {
return new Foo(includes);
}
}
usage:
List<String> includes = new ArrayList<>();
includes.add("foo");
includes.add("bar");
Foo foo = fooClient.getFoo(includes);
url:
http://some-server/foo?include=foo&include=bar
I have a request like:
example.com/search?sort=myfield1,-myfield2,myfield3
I would like to split those params to bind a List<String> sort in my controller or List<SortParam> where SortParam is the class with fields like: name (String) and ask (boolean).
So the final controller would look like this:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(#RequestParam List<String> sort) {
//...
}
or
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(#RequestParam List<SortParam> sort) {
//...
}
Is there a way to make it?
UPDATE:
The standard way of passing parameters does not satisfy my requirements. I.e. I cannot use sort=myfield1&sort=-myfield2&sort=myfield3. I have to use comma separated names.
Also, I do understand that I can accept #RequestParam String sort in my controller and then split the string inside the controller like sort.split(",") but it also doesn't solve the above problem.
Its just a simple Type Covertion task. Spring defines an SPI (Service Provider Interface) to implement type conversion logic. For your specific problem you can define your Type Conversion logic by implementing Converter interface.
#Component
public class StringToListConverter implements Converter<String, List<String>> {
#Override
public List<String> convert(String source) {
return Arrays.asList(source.split(","));
}
}
You can also convert your request parameter to List<SortPram> according your logic (but I am not sure about your that logic from your question). This is it! Now Spring get known that how to bind your request paramter to a list.
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> participants(#RequestParam("sort") List<String> sort) {
// .. do your logic
}
There are many more ways to define you custom data binder. Check this
A Custom Data Binder in Spring MVC article.
Spring documentation about Validation, Data Binding, and Type Conversion
Yes, you can certainly do that, you're almost there.
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> participants(#RequestParam("sort") List<String> sort) {
//...
}
You should now be able to call your service like this (if search is located at your root, otherwise adapt according to your situation):
curl "localhost:8080/search?sort=sortField1&sort=sortField2&sort=sortField3"
Hope this helps!
EDIT
Sorry, I have read your comments and what you need is clear to me now. I have created a workaround for you that is almost what you want I think.
So first a SortParams class:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SortParams {
private List<SortParam> sortParamList;
public SortParams(String commaSeparatedString) {
sortParamList = Arrays.stream(commaSeparatedString.split(","))
.map(p -> SortParam.valueOf(p))
.collect(Collectors.toList());
}
public List<SortParam> getSortParamList() {
return this.sortParamList;
}
public enum SortParam {
FOO, BAR, FOOBAR;
}
}
Then your controller could look like this:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<List<SortParams.SortParam>> search(#RequestParam("sort") SortParams sort) {
return ResponseEntity.ok(sort.getSortParamList());
}
Now your SortParams object has a list of SortParam:
curl "localhost:8080/search?sort=FOO,BAR"
["FOO","BAR"]
Would something like this fit what you're looking for?
It could be helpfull if Kotlin
private const val DELIMITER: Char = ':'
private val DEFAULT_DIRECTION: Sort.Direction = Sort.Direction.ASC
private fun parseFrom(source: String): Sort.Order = if (source.contains(DELIMITER)) {
Sort.Order(Sort.Direction.fromString(source.substringAfter(DELIMITER)), source.substringBefore(DELIMITER))
} else Sort.Order(DEFAULT_DIRECTION, source)
// if few sort paremeters
#Component
class RequestSortConverterArray : Converter<Array<String>, Sort> {
override fun convert(source: Array<String>): Sort? = if (source.isEmpty()) Sort.unsorted()
else source.map { parseFrom(it) }.let { Sort.by(it) }
}
// if single sort paremeter
#Component
class RequestSortConverterString : Converter<String, Sort> {
override fun convert(source: String): Sort? = if (source.isEmpty()) Sort.unsorted()
else Sort.by(parseFrom(source))
}
...
#GetMapping
fun search(
#RequestParam(required = false, defaultValue = "0") page: Int,
#RequestParam(required = false, defaultValue = "20") size: Int,
#RequestParam(required = false, defaultValue = "myfield1:asc") sort: Sort
) {
val pageable = PageRequest.of(page, size, sort)
// make a search by repository
}
Our company is planning to switch our microservice technology to Spring Boot. As an initiative I did some advanced reading and noting down its potential impact and syntax equivalents. I also started porting the smallest service we had as a side project.
One issue that blocked my progress was trying to convert our Json request/response exchange to Spring Boot.
Here's an example of the code: (This is Nutz framework for those who don't recognize this)
#POST
#At // These two lines are equivalent to #PostMapping("/create")
#AdaptBy(type=JsonAdapter.class)
public Object create(#Param("param_1") String param1, #Param("param_2) int param2) {
MyModel1 myModel1 = new MyModel1(param1);
MyModel2 myModel2 = new MyModel2(param2);
myRepository1.create(myMode12);
myRepository2.create(myModel2);
return new MyJsonResponse();
}
On PostMan or any other REST client I simply pass POST:
{
"param_1" : "test",
"param_2" : 1
}
I got as far as doing this in Spring Boot:
#PostMapping("/create")
public Object create(#RequestParam("param_1") String param1, #RequestParam("param_2) int param2) {
MyModel1 myModel1 = new MyModel1(param1);
MyModel2 myModel2 = new MyModel2(param2);
myRepository1.create(myMode12);
myRepository2.create(myModel2);
return new MyJsonResponse();
}
I am not sure how to do something similar as JsonAdapter here. Spring doesn't recognize the data I passed.
I tried this but based on the examples it expects the Json paramters to be of an Entity's form.
#RequestMapping(path="/wallet", consumes="application/json", produces="application/json")
But I only got it to work if I do something like this:
public Object (#RequestBody MyModel1 model1) {}
My issue with this is that MyModel1 may not necessarily contain the fields/parameters that my json data has.
The very useful thing about Nutz is that if I removed JsonAdapter it behaves like a regular form request endpoint in spring.
I couldn't find an answer here in Stack or if possible I'm calling it differently than what existing spring devs call it.
Our bosses expect us (unrealistically) to implement these changes without forcing front-end developers to adjust to these changes. (Autonomy and all that jazz). If this is unavoidable what would be the sensible explanation for this?
In that case you can use Map class to read input json, like
#PostMapping("/create")
public Object create(#RequestBody Map<String, ?> input) {
sout(input.get("param1")) // cast to String, int, ..
}
I actually figured out a more straightforward solution.
Apparently this works:
#PostMapping("/endpoint")
public Object endpoint(#RequestBody MyWebRequestObject request) {
String value1 = request.getValue_1();
String value2 = request.getValue_2();
}
The json payload is this:
{
"value_1" : "hello",
"value_2" : "world"
}
This works if MyRequestObject is mapped like the json request object like so. Example:
public class MyWebRequestObject {
String value_1;
String value_2
}
Unmapped values are ignored. Spring is smart like that.
I know this is right back where I started but since we introduced a service layer for the rest control to interact with, it made sense to create our own request model object (DTOs) that is separate from the persistence model.
You can use #RequestBody Map as a parameter for #PostMapping, #PutMapping and #PatchMapping. For #GetMapping and #DeleteMapping, you can write a class which implements Converter to convert from json-formed request parameters to Map. And you would register that class as a bean with #Component annotation. Then you can bind your parameters to #RequestParameter Map.
Here is an example of Converter below.
#Component
public class StringToMapConverter implements Converter<String, Map<String, Object>> {
private final ObjectMapper objectMapper;
#Autowired
public StringToMapConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
#Override
public Map<String, Object> convert(String source) {
try {
return objectMapper.readValue(source, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
return new HashMap<>();
}
}
}
If you want to exclude specific field of your MyModel1 class, use #JsonIgnore annotation onto the field like below.
class MyModel1 {
private field1;
#JsonIgnore field2;
}
Then, I guess you can just use what you have done.(I'm not sure.)
public Object (#RequestBody MyModel1 model1) {}
i think that you can use a strategy that involve dto
https://auth0.com/blog/automatically-mapping-dto-to-entity-on-spring-boot-apis/
you send a json to your rest api that is map like a dto object, after you can map like an entity or use it for your needs
try this:
Add new annotation JsonParam and implement HandlerMethodArgumentResolver of this, Parse json to map and get data in HandlerMethodArgumentResolver
{
"aaabbcc": "aaa"
}
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
public #interface JsonParam {
String value();
}
#Component
public class JsonParamMethodResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(JsonParam.class);
}
#Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
RepeatedlyRequestWrapper nativeRequest = webRequest.getNativeRequest(RepeatedlyRequestWrapper.class);
if (nativeRequest == null) {
return null;
}
Gson gson = new Gson();
Map<String, Object> response = gson.fromJson(nativeRequest.getReader(), new TypeToken<Map<String, Object>>() {
}.getType());
if (response == null) {
return null;
}
JsonParam parameterAnnotation = parameter.getParameterAnnotation(JsonParam.class);
String value = parameterAnnotation.value();
Class<?> parameterType = parameter.getParameterType();
return response.get(value);
}
}
#Configuration
public class JsonParamConfig extends WebMvcConfigurerAdapter {
#Autowired
JsonParamMethodResolver jsonParamMethodResolver;
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(jsonParamMethodResolver);
}
}
#PostMapping("/methodName")
public void methodName(#JsonParam("aaabbcc") String ddeeff) {
System.out.println(username);
}
I have
#RequestMapping(method = RequestMethod.GET)
#ResponseBody
SessionInfo register(UserProfile profileJson){
...
}
I pass profileJson this way:
http://server/url?profileJson={"email": "mymail#gmail.com"}
but my profileJson object has all null fields. What should I do to make spring parse my json?
The solution to this is so easy and simple it will practically make you laugh, but before I even get to it, let me first emphasize that no self-respecting Java developer would ever, and I mean EVER work with JSON without utilizing the Jackson high-performance JSON library.
Jackson is not only a work horse and a defacto JSON library for Java developers, but it also provides a whole suite of API calls that makes JSON integration with Java a piece of cake (you can download Jackson at http://jackson.codehaus.org/).
Now for the answer. Assuming that you have a UserProfile pojo that looks something like this:
public class UserProfile {
private String email;
// etc...
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// more getters and setters...
}
...then your Spring MVC method to convert a GET parameter name "profileJson" with JSON value of {"email": "mymail#gmail.com"} would look like this in your controller:
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper; // this is your lifesaver right here
//.. your controller class, blah blah blah
#RequestMapping(value="/register", method = RequestMethod.GET)
public SessionInfo register(#RequestParam("profileJson") String profileJson)
throws JsonMappingException, JsonParseException, IOException {
// now simply convert your JSON string into your UserProfile POJO
// using Jackson's ObjectMapper.readValue() method, whose first
// parameter your JSON parameter as String, and the second
// parameter is the POJO class.
UserProfile profile =
new ObjectMapper().readValue(profileJson, UserProfile.class);
System.out.println(profile.getEmail());
// rest of your code goes here.
}
Bam! You're done. I would encourage you to look through the bulk of Jackson API because, as I said, it is a lifesaver. For example, are you returning JSON from your controller at all? If so, all you need to do is include JSON in your lib, and return your POJO and Jackson will AUTOMATICALLY convert it into JSON. You can't get much easier than that. Cheers! :-)
This could be done with a custom editor, that converts the JSON into a UserProfile object:
public class UserProfileEditor extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
ObjectMapper mapper = new ObjectMapper();
UserProfile value = null;
try {
value = new UserProfile();
JsonNode root = mapper.readTree(text);
value.setEmail(root.path("email").asText());
} catch (IOException e) {
// handle error
}
setValue(value);
}
}
This is for registering the editor in the controller class:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserProfile.class, new UserProfileEditor());
}
And this is how to use the editor, to unmarshall the JSONP parameter:
#RequestMapping(value = "/jsonp", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
#ResponseBody
SessionInfo register(#RequestParam("profileJson") UserProfile profileJson){
...
}
You can create your own Converter and let Spring use it automatically where appropriate:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
#Component
class JsonToUserProfileConverter implements Converter<String, UserProfile> {
private final ObjectMapper jsonMapper = new ObjectMapper();
public UserProfile convert(String source) {
return jsonMapper.readValue(source, UserProfile.class);
}
}
As you can see in the following controller method nothing special is needed:
#GetMapping
#ResponseBody
public SessionInfo register(#RequestParam UserProfile userProfile) {
...
}
Spring picks up the converter automatically if you're using component scanning and annotate the converter class with #Component.
Learn more about Spring Converter and type conversions in Spring MVC.
This does solve my immediate issue, but I'm still curious as to how you might pass in multiple JSON objects via an AJAX call.
The best way to do this is to have a wrapper object that contains the two (or multiple) objects you want to pass. You then construct your JSON object as an array of the two objects i.e.
[
{
"name" : "object1",
"prop1" : "foo",
"prop2" : "bar"
},
{
"name" : "object2",
"prop1" : "hello",
"prop2" : "world"
}
]
Then in your controller method you recieve the request body as a single object and extract the two contained objects. i.e:
#RequestMapping(value="/handlePost", method = RequestMethod.POST, consumes = { "application/json" })
public void doPost(#RequestBody WrapperObject wrapperObj) {
Object obj1 = wrapperObj.getObj1;
Object obj2 = wrapperObj.getObj2;
//Do what you want with the objects...
}
The wrapper object would look something like...
public class WrapperObject {
private Object obj1;
private Object obj2;
public Object getObj1() {
return obj1;
}
public void setObj1(Object obj1) {
this.obj1 = obj1;
}
public Object getObj2() {
return obj2;
}
public void setObj2(Object obj2) {
this.obj2 = obj2;
}
}
Just add #RequestBody annotation before this param