
io.vertx.rxjava3.impl.ObservableUnmarshaller Maven / Gradle / Ivy
package io.vertx.rxjava3.impl;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.core.Single;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.Json;
import io.vertx.core.json.jackson.JacksonFactory;
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;
private ObjectCodec mapper;
public ObservableUnmarshaller(java.util.function.Function unwrap, Class mappedType) {
this(unwrap, mappedType, null, null);
}
public ObservableUnmarshaller(java.util.function.Function unwrap, TypeReference mappedTypeRef) {
this(unwrap, null, mappedTypeRef, null);
}
public ObservableUnmarshaller(java.util.function.Function unwrap, Class mappedType, ObjectCodec mapper) {
this(unwrap, mappedType, null, mapper);
}
public ObservableUnmarshaller(java.util.function.Function unwrap, TypeReference mappedTypeRef, ObjectCodec mapper) {
this(unwrap, null, mappedTypeRef, mapper);
}
private ObservableUnmarshaller(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 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;
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 Maybe.just(obj);
} catch (Exception e) {
return Maybe.error(e);
}
} else {
return Maybe.empty();
}
});
return unmarshalled.toObservable();
}
static T getT(Buffer buffer, Class mappedType, TypeReference mappedTypeRef) {
T obj;
obj = nonNull(mappedType) ? Json.CODEC.fromBuffer(buffer, mappedType) :
JacksonFactory.CODEC.fromBuffer(buffer, mappedTypeRef);
return obj;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy