Binding using Reactive Frameworks

From a developer perspective however, you can generally just work with Plain Old Java Objects (POJOs) and can optionally use a Reactive framework such as RxJava or Reactor. The following is an example of a controller that reads and saves an incoming POJO in a non-blocking way from JSON:

Using RxJava 2 to Read the JSON

  1. @Controller("/people")
  2. public class PersonController {
  3. Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
  4. @Post("/saveReactive")
  5. public Single<HttpResponse<Person>> save(@Body Single<Person> person) { (1)
  6. return person.map(p -> {
  7. inMemoryDatastore.put(p.getFirstName(), p); (2)
  8. return HttpResponse.created(p); (3)
  9. }
  10. );
  11. }
  12. }

Using RxJava 2 to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. ConcurrentHashMap<String, Person> inMemoryDatastore = [:]
  4. @Post("/saveReactive")
  5. Single<HttpResponse<Person>> save(@Body Single<Person> person) { (1)
  6. person.map({ p ->
  7. inMemoryDatastore.put(p.getFirstName(), p) (2)
  8. HttpResponse.created(p) (3)
  9. })
  10. }
  11. }

Using RxJava 2 to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
  4. @Post("/saveReactive")
  5. fun save(@Body person: Single<Person>): Single<HttpResponse<Person>> { (1)
  6. return person.map { p ->
  7. inMemoryDatastore[p.firstName] = p (2)
  8. HttpResponse.created(p) (3)
  9. }
  10. }
  11. }
1The method receives a RxJava Single which emits the POJO once the JSON has been read
2The map method is used to store the instance in Map
3An HttpResponse is returned

Using CURL from the command line you can POST JSON to the /people URI for the server to receive it:

Using CURL to Post JSON

  1. $ curl -X POST localhost:8080/people -d '{"firstName":"Fred","lastName":"Flintstone","age":45}'