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

io.vertx.reactivex.impl.SingleUnmarshaller Maven / Gradle / Ivy

There is a newer version: 5.0.0.CR3
Show newest version
package io.vertx.reactivex.impl;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.SingleTransformer;
import io.reactivex.annotations.NonNull;
import io.vertx.core.buffer.Buffer;

import static io.vertx.reactivex.impl.ObservableUnmarshaller.getT;
import static java.util.Objects.nonNull;

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

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


  public SingleUnmarshaller(java.util.function.Function unwrap, Class mappedType) {
    this(unwrap, mappedType,null,  null);

  }

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

  public SingleUnmarshaller(java.util.function.Function unwrap, Class mappedType, ObjectCodec mapper) {
    this(unwrap, mappedType,null,  mapper);
  }

  public SingleUnmarshaller(java.util.function.Function unwrap, TypeReference mappedTypeRef, ObjectCodec mapper) {
    this(unwrap, null, mappedTypeRef, mapper);
  }

  private SingleUnmarshaller(java.util.function.Function unwrap, Class mappedType, TypeReference mappedTypeRef, ObjectCodec mapper) {
    this.unwrap = unwrap;
    this.mappedType = mappedType;
    this.mappedTypeRef = mappedTypeRef;
    this.mapper = mapper;
  }

  @Override
  public SingleSource apply(@NonNull Single upstream) {
    Single unwrapped = upstream.map(unwrap::apply);
    Single unmarshalled = unwrapped.flatMap(buffer -> {
      try {
        T obj;
        if (mapper != null) {
          JsonParser parser = mapper.getFactory().createParser(buffer.getBytes());
          obj = nonNull(mappedType) ? mapper.readValue(parser, mappedType) :
            mapper.readValue(parser, mappedTypeRef);
        } else {
          obj = getT(buffer, mappedType, mappedTypeRef);
        }
        return Single.just(obj);
      } catch (Exception e) {
        return Single.error(e);
      }
    });
    return unmarshalled;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy