All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.vertx.reactivex.core.json.ObservableUnmarshaller Maven / Gradle / Ivy

There is a newer version: 4.5.10
Show newest version
package io.vertx.reactivex.core.json;

import com.fasterxml.jackson.core.type.TypeReference;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.annotations.NonNull;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

import static io.vertx.core.json.Json.mapper;
import static java.util.Objects.nonNull;

/**
 * An operator to unmarshall json to pojos.
 *
 * @author Julien Viet
 */
public class ObservableUnmarshaller implements ObservableTransformer {

  private final java.util.function.Function unwrap;
  private final Class mappedType;
  private final TypeReference mappedTypeRef;

  public ObservableUnmarshaller(java.util.function.Function unwrap, Class mappedType) {
    this.unwrap = unwrap;
    this.mappedType = mappedType;
    this.mappedTypeRef = null;
  }

  public ObservableUnmarshaller(java.util.function.Function unwrap, TypeReference mappedTypeRef) {
    this.unwrap = unwrap;
    this.mappedType = null;
    this.mappedTypeRef = mappedTypeRef;
  }

  @Override
  public ObservableSource apply(@NonNull Observable upstream) {
    Observable unwrapped = upstream.map(unwrap::apply);
    Single aggregated = unwrapped.collect(Buffer::buffer, Buffer::appendBuffer);
    Maybe unmarshalled = aggregated.toMaybe().concatMap(buffer -> {
      if (buffer.length() > 0) {
        try {
          T obj = nonNull(mappedType) ? mapper.readValue(buffer.getBytes(), mappedType) :
            mapper.readValue(buffer.getBytes(), mappedTypeRef);
          return Maybe.just(obj);
        } catch (IOException e) {
          return Maybe.error(e);
        }
      } else {
        return Maybe.empty();
      }
    });
    return unmarshalled.toObservable();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy