Search in sources :

Example 81 with Maybe

use of io.reactivex.rxjava3.core.Maybe in project julian-http-client by ljtfreitas.

the class VertxHTTPClientResponse method valueOf.

static Single<VertxHTTPClientResponse> valueOf(HttpClientResponse response) {
    HTTPStatus status = HTTPStatusCode.select(response.statusCode()).map(HTTPStatus::new).orElseGet(() -> new HTTPStatus(response.statusCode(), response.statusMessage()));
    HTTPHeaders headers = response.headers().names().stream().map(name -> HTTPHeader.create(name, response.headers().getAll(name))).reduce(HTTPHeaders.empty(), HTTPHeaders::join, (a, b) -> b);
    Maybe<byte[]> bodyAsBytes = response.body().map(Buffer::getBytes).toMaybe();
    return bodyAsBytes.map(body -> HTTPResponseBody.optional(status, headers, () -> HTTPResponseBody.some(body))).map(body -> new VertxHTTPClientResponse(HTTPClientResponse.create(status, headers, body))).switchIfEmpty(Single.fromCallable(() -> new VertxHTTPClientResponse(HTTPClientResponse.empty(status, headers))));
}
Also used : Single(io.reactivex.rxjava3.core.Single) Function(java.util.function.Function) HTTPResponseBody(com.github.ljtfreitas.julian.http.HTTPResponseBody) HTTPStatusCode(com.github.ljtfreitas.julian.http.HTTPStatusCode) Maybe(io.reactivex.rxjava3.core.Maybe) Response(com.github.ljtfreitas.julian.Response) HTTPHeader(com.github.ljtfreitas.julian.http.HTTPHeader) HTTPHeaders(com.github.ljtfreitas.julian.http.HTTPHeaders) HTTPStatus(com.github.ljtfreitas.julian.http.HTTPStatus) Optional(java.util.Optional) Buffer(io.vertx.rxjava3.core.buffer.Buffer) HTTPClientResponse(com.github.ljtfreitas.julian.http.client.HTTPClientResponse) HttpClientResponse(io.vertx.rxjava3.core.http.HttpClientResponse) HTTPHeaders(com.github.ljtfreitas.julian.http.HTTPHeaders) HTTPStatus(com.github.ljtfreitas.julian.http.HTTPStatus)

Example 82 with Maybe

use of io.reactivex.rxjava3.core.Maybe in project amplify-android by aws-amplify.

the class Merger method merge.

/**
 * Merge an item back into the local store, using a default strategy.
 * TODO: Change this method to return a Maybe, and remove the Consumer argument.
 * @param modelWithMetadata A model, combined with metadata about it
 * @param changeTypeConsumer A callback invoked when the merge method saves or deletes the model.
 * @param <T> Type of model
 * @return A completable operation to merge the model
 */
<T extends Model> Completable merge(ModelWithMetadata<T> modelWithMetadata, Consumer<StorageItemChange.Type> changeTypeConsumer) {
    AtomicReference<Long> startTime = new AtomicReference<>();
    return Completable.defer(() -> {
        ModelMetadata metadata = modelWithMetadata.getSyncMetadata();
        boolean isDelete = Boolean.TRUE.equals(metadata.isDeleted());
        int incomingVersion = metadata.getVersion() == null ? -1 : metadata.getVersion();
        T model = modelWithMetadata.getModel();
        return versionRepository.findModelVersion(model).onErrorReturnItem(-1).filter(currentVersion -> currentVersion == -1 || incomingVersion > currentVersion).flatMapCompletable(shouldMerge -> {
            Completable firstStep;
            if (mutationOutbox.hasPendingMutation(model.getId())) {
                LOG.info("Mutation outbox has pending mutation for " + model.getId() + ". Saving the metadata, but not model itself.");
                firstStep = Completable.complete();
            } else {
                firstStep = (isDelete ? delete(model, changeTypeConsumer) : save(model, changeTypeConsumer));
            }
            return firstStep.andThen(save(metadata, NoOpConsumer.create()));
        }).doOnComplete(() -> {
            announceSuccessfulMerge(modelWithMetadata);
            LOG.debug("Remote model update was sync'd down into local storage: " + modelWithMetadata);
        }).onErrorComplete(failure -> {
            if (!ErrorInspector.contains(failure, SQLiteConstraintException.class)) {
                return false;
            }
            LOG.warn("Sync failed: foreign key constraint violation: " + modelWithMetadata, failure);
            return true;
        }).doOnError(failure -> LOG.warn("Failed to sync remote model into local storage: " + modelWithMetadata, failure));
    }).doOnSubscribe(disposable -> startTime.set(System.currentTimeMillis())).doOnTerminate(() -> {
        long duration = System.currentTimeMillis() - startTime.get();
        LOG.verbose("Merged a single item in " + duration + " ms.");
    });
}
Also used : Amplify(com.amplifyframework.core.Amplify) HubChannel(com.amplifyframework.hub.HubChannel) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) AtomicReference(java.util.concurrent.atomic.AtomicReference) ErrorInspector(com.amplifyframework.datastore.utils.ErrorInspector) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) Consumer(com.amplifyframework.core.Consumer) LocalStorageAdapter(com.amplifyframework.datastore.storage.LocalStorageAdapter) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) SQLiteConstraintException(android.database.sqlite.SQLiteConstraintException) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) HubEvent(com.amplifyframework.hub.HubEvent) Completable(io.reactivex.rxjava3.core.Completable) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata)

Example 83 with Maybe

use of io.reactivex.rxjava3.core.Maybe in project caravan-rhyme by wcm-io-caravan.

the class RenderRelatedResourceTest method should_throw_exception_if_server_impls_are_neither_linkable_or_embeddable.

@Test
public void should_throw_exception_if_server_impls_are_neither_linkable_or_embeddable() {
    TestResourceWithObservableLinks resourceImpl = new TestResourceWithObservableLinks() {

        @Override
        public Observable<TestResource> getLinked() {
            return Observable.just(new TestResource() {

                @Override
                public Maybe<TestState> getState() {
                    return Maybe.just(new TestState("foo"));
                }
            });
        }
    };
    Throwable ex = catchThrowable(() -> render(resourceImpl));
    assertThat(ex).isInstanceOf(HalApiDeveloperException.class).hasMessageStartingWith("Your server side resource implementation classes must implement either EmbeddableResource or LinkableResource.");
}
Also used : Maybe(io.reactivex.rxjava3.core.Maybe) HalApiDeveloperException(io.wcm.caravan.rhyme.api.exceptions.HalApiDeveloperException) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) TestResource(io.wcm.caravan.rhyme.testing.TestResource) LinkableTestResource(io.wcm.caravan.rhyme.testing.LinkableTestResource) TestResourceWithObservableLinks(io.wcm.caravan.rhyme.impl.renderer.RenderLinkedResourceTest.TestResourceWithObservableLinks) TestState(io.wcm.caravan.rhyme.testing.TestState) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.Test)55 TestException (io.reactivex.rxjava3.exceptions.TestException)38 TestSubscriber (io.reactivex.rxjava3.subscribers.TestSubscriber)13 Maybe (io.reactivex.rxjava3.core.Maybe)12 InOrder (org.mockito.InOrder)12 Flowable (io.reactivex.rxjava3.core.Flowable)10 Observable (io.reactivex.rxjava3.core.Observable)10 Disposable (io.reactivex.rxjava3.disposables.Disposable)10 Single (io.reactivex.rxjava3.core.Single)8 IOException (java.io.IOException)8 Predicate (io.reactivex.rxjava3.functions.Predicate)6 RxMethod (io.reactivex.rxjava3.validators.BaseTypeParser.RxMethod)6 Type (java.lang.reflect.Type)6 Test (org.junit.jupiter.api.Test)6 TestObserver (io.reactivex.rxjava3.observers.TestObserver)5 Completable (io.reactivex.rxjava3.core.Completable)4 Action (io.reactivex.rxjava3.functions.Action)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 FlowableRxInvoker (org.apache.cxf.jaxrs.rx3.client.FlowableRxInvoker)4 FlowableRxInvokerProvider (org.apache.cxf.jaxrs.rx3.client.FlowableRxInvokerProvider)4