JaxRs + RxJava = Awesome query interface

Philipp Eichhorn • • coding

As part of MyAdvent we wanted a simple REST interface for quickly pulling some statistics about the service, like how many calendars have been created and how many photos they contain. Simply displaying those stats is simple (and boring!), but what about some simply queries like “give me all calendars with more than 10 photos”?

Databases support that by default, but what if you don’t have a database and just want to do some quick filtering of POJOs you have lying around? Tough luck? RxJava to the rescue! Here is what we ended up using:

public class Stats {
  int count;
  boolean readonly;

public class RestInterface {

  public List<Stats> getStats(
      @QueryParam("minCount") final Optional<Integer> minCount,
      @QueryParam("maxCount") final Optional<Integer> maxCount,
      @QueryParam("readonly") final Optional<Boolean> isReadonly) {

    return Observable.from(myAwesomeSource())
        .filter(new Func1<Stats, Boolean>() {
          public Boolean call(Stats stats) {
            return (!minCount.isPresent() || stats.count >= minCount.get()) &&
                  (!maxCount.isPresent() || stats.count <= maxCount.get()) &&
                  (!readonly.isPresent() || stats.readonly == readonly.get());


Note that the Optional<Integer> is a Dropwizard goodie.

So, that’s it! Just a nice little way to use RxJava to simply query interfaces if you happen to use JaxRs / Dropwizard :)

comments powered by Disqus