com.apollographql.apollo.exception.ApolloException Java Examples

The following examples show how to use com.apollographql.apollo.exception.ApolloException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CacheFirstFetcher.java    From apollo-android with MIT License 6 votes vote down vote up
@Override
public void interceptAsync(@NotNull final InterceptorRequest request, @NotNull final ApolloInterceptorChain chain,
    @NotNull final Executor dispatcher, @NotNull final CallBack callBack) {
  InterceptorRequest cacheRequest = request.toBuilder().fetchFromCache(true).build();
  chain.proceedAsync(cacheRequest, dispatcher, new CallBack() {
    @Override public void onResponse(@NotNull InterceptorResponse response) {
      callBack.onResponse(response);
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      if (!disposed) {
        InterceptorRequest networkRequest = request.toBuilder().fetchFromCache(false).build();
        chain.proceedAsync(networkRequest, dispatcher, callBack);
      }
    }

    @Override public void onCompleted() {
      callBack.onCompleted();
    }

    @Override public void onFetch(FetchSourceType sourceType) {
      callBack.onFetch(sourceType);
    }
  });
}
 
Example #2
Source File: BaseCommand.java    From twitch4j with MIT License 6 votes vote down vote up
/**
 * Run Command
 *
 * @return T
 */
@Override
protected T run() {
    // Run GraphQL Call
    getGraphQLCall().enqueue(new ApolloCall.Callback<T>() {
        @Override
        public void onResponse(@NotNull Response<T> response) {
            if (response.errors().size() > 0) {
                throw new RuntimeException("GraphQL API: " + response.errors().toString());
            }

            resultData = response.data();
        }

        @Override
        public void onFailure(@NotNull ApolloException e) {
            throw new RuntimeException(e);
        }
    });

    // block until we've got a result
    block();
    return resultData;
}
 
Example #3
Source File: CacheOnlyFetcher.java    From apollo-android with MIT License 6 votes vote down vote up
@Override
public void interceptAsync(@NotNull final InterceptorRequest request, @NotNull ApolloInterceptorChain chain,
    @NotNull Executor dispatcher, @NotNull final CallBack callBack) {
  InterceptorRequest cacheRequest = request.toBuilder().fetchFromCache(true).build();
  chain.proceedAsync(cacheRequest, dispatcher, new CallBack() {
    @Override public void onResponse(@NotNull InterceptorResponse response) {
      callBack.onResponse(response);
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      // Cache only returns null instead of throwing when the cache is empty
      callBack.onResponse(cacheMissResponse(request.operation));
      callBack.onCompleted();
    }

    @Override public void onCompleted() {
      callBack.onCompleted();
    }

    @Override public void onFetch(FetchSourceType sourceType) {
      callBack.onFetch(sourceType);
    }
  });
}
 
Example #4
Source File: QueryReFetcher.java    From apollo-android with MIT License 6 votes vote down vote up
private void refetchQueries() {
  final OnCompleteCallback completeCallback = onCompleteCallback;
  final AtomicInteger callsLeft = new AtomicInteger(calls.size());
  for (final RealApolloCall call : calls) {
    //noinspection unchecked
    call.enqueue(new ApolloCall.Callback() {
      @Override public void onResponse(@NotNull Response response) {
        if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
          completeCallback.onFetchComplete();
        }
      }

      @Override public void onFailure(@NotNull ApolloException e) {
        if (logger != null) {
          logger.e(e, "Failed to fetch query: %s", call.operation);
        }

        if (callsLeft.decrementAndGet() == 0 && completeCallback != null) {
          completeCallback.onFetchComplete();
        }
      }
    });
  }
}
 
Example #5
Source File: AsyncNormalizedCacheTestCase.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void testAsync() throws IOException, InterruptedException, ApolloException {
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  for (int i = 0; i < 500; i++) {
    server.enqueue(mockResponse("HeroNameResponse.json"));
  }

  List<Observable<Response<EpisodeHeroNameQuery.Data>>> calls = new ArrayList<>();
  for (int i = 0; i < 1000; i++) {
    ApolloQueryCall<EpisodeHeroNameQuery.Data> queryCall = apolloClient
        .query(query)
        .responseFetcher(i % 2 == 0 ? ApolloResponseFetchers.NETWORK_FIRST : ApolloResponseFetchers.CACHE_ONLY);
    calls.add(Rx2Apollo.from(queryCall));
  }
  TestObserver<Response<EpisodeHeroNameQuery.Data>> observer = new TestObserver<>();
  Observable.merge(calls).subscribe(observer);
  observer.awaitTerminalEvent();
  observer.assertNoErrors();
  observer.assertValueCount(1000);
  observer.assertNever(new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
    @Override public boolean test(Response<EpisodeHeroNameQuery.Data> dataResponse) throws Exception {
      return dataResponse.hasErrors();
    }
  });
}
 
Example #6
Source File: Rx3Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloQueryWatcher} to an asynchronous Observable.
 *
 * @param watcher the ApolloQueryWatcher to convert.
 * @param <T>     the value type
 * @return the converted Observable
 * @throws NullPointerException if watcher == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloQueryWatcher<T> watcher) {
  checkNotNull(watcher, "watcher == null");
  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, watcher);

      watcher.enqueueAndWatch(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #7
Source File: Rx3Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloPrefetch} to a synchronous Completable
 *
 * @param prefetch the ApolloPrefetch to convert
 * @return the converted Completable
 * @throws NullPointerException if prefetch == null
 */
@NotNull
@CheckReturnValue
public static Completable from(@NotNull final ApolloPrefetch prefetch) {
  checkNotNull(prefetch, "prefetch == null");

  return Completable.create(new CompletableOnSubscribe() {
    @Override public void subscribe(final CompletableEmitter emitter) {
      cancelOnCompletableDisposed(emitter, prefetch);
      prefetch.enqueue(new ApolloPrefetch.Callback() {
        @Override public void onSuccess() {
          if (!emitter.isDisposed()) {
            emitter.onComplete();
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #8
Source File: Rx2Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloPrefetch} to a synchronous Completable
 *
 * @param prefetch the ApolloPrefetch to convert
 * @return the converted Completable
 * @throws NullPointerException if prefetch == null
 */
@NotNull
@CheckReturnValue
public static Completable from(@NotNull final ApolloPrefetch prefetch) {
  checkNotNull(prefetch, "prefetch == null");

  return Completable.create(new CompletableOnSubscribe() {
    @Override public void subscribe(final CompletableEmitter emitter) {
      cancelOnCompletableDisposed(emitter, prefetch);
      prefetch.enqueue(new ApolloPrefetch.Callback() {
        @Override public void onSuccess() {
          if (!emitter.isDisposed()) {
            emitter.onComplete();
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #9
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void asyncApplicationInterceptorThrowsApolloException() throws Exception {
  final String message = "ApolloException";
  EpisodeHeroNameQuery query = createHeroNameQuery();
  ApolloInterceptor interceptor = new ApolloInterceptor() {
    @Override
    public void interceptAsync(@NotNull InterceptorRequest request, @NotNull ApolloInterceptorChain chain,
        @NotNull Executor dispatcher, @NotNull CallBack callBack) {
      ApolloException apolloException = new ApolloParseException(message);
      callBack.onFailure(apolloException);
    }

    @Override public void dispose() {

    }
  };

  client = createApolloClient(interceptor);
  Rx2Apollo.from(client.query(query))
      .test()
      .assertError(new Predicate<Throwable>() {
        @Override public boolean test(Throwable throwable) throws Exception {
          return message.equals(throwable.getMessage()) && throwable instanceof ApolloParseException;
        }
      });
}
 
Example #10
Source File: Rx2Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloQueryWatcher} to an asynchronous Observable.
 *
 * @param watcher the ApolloQueryWatcher to convert.
 * @param <T>     the value type
 * @return the converted Observable
 * @throws NullPointerException if watcher == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloQueryWatcher<T> watcher) {
  checkNotNull(watcher, "watcher == null");
  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, watcher);

      watcher.enqueueAndWatch(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #11
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void onShortCircuitingResponseSubsequentInterceptorsAreNotCalled() throws IOException, ApolloException {
  EpisodeHeroNameQuery query = createHeroNameQuery();
  final InterceptorResponse expectedResponse = prepareInterceptorResponse(query);

  ApolloInterceptor firstInterceptor = createShortcutInterceptor(expectedResponse);
  ApolloInterceptor secondInterceptor = createChainInterceptor();

  client = ApolloClient.builder()
      .serverUrl(server.url("/"))
      .okHttpClient(okHttpClient)
      .addApplicationInterceptor(firstInterceptor)
      .addApplicationInterceptor(secondInterceptor)
      .build();

  Utils.INSTANCE.assertResponse(
      client.query(query),
      new Predicate<Response<EpisodeHeroNameQuery.Data>>() {
        @Override public boolean test(Response<EpisodeHeroNameQuery.Data> response) throws Exception {
          assertThat(expectedResponse.parsedResponse.get()).isEqualTo(response);
          return true;
        }
      }
  );
}
 
Example #12
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void testQueryWatcherNotUpdated_SameQuery_SameResults() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.enqueueAndWatch(
      new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
        @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
          heroNameList.add(response.data().hero().name());
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Assert.fail(e.getMessage());
        }
      });

  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  apolloClient.query(query).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.size()).isEqualTo(1);
}
 
Example #13
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void onApolloCallCanceledAsyncApolloInterceptorIsDisposed() throws ApolloException, TimeoutException,
    InterruptedException, IOException {
  server.enqueue(mockResponse(FILE_EPISODE_HERO_NAME_WITH_ID));

  EpisodeHeroNameQuery query = createHeroNameQuery();
  SpyingApolloInterceptor interceptor = new SpyingApolloInterceptor();

  Utils.TestExecutor testExecutor = new Utils.TestExecutor();
  client = createApolloClient(interceptor, testExecutor);

  ApolloCall<EpisodeHeroNameQuery.Data> apolloCall = client.query(query);

  apolloCall.enqueue(new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
    @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
    }

    @Override public void onFailure(@NotNull ApolloException e) {
    }
  });
  apolloCall.cancel();
  testExecutor.triggerActions();
  assertThat(interceptor.isDisposed).isTrue();
}
 
Example #14
Source File: Rx2Apollo.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * Converts an {@link ApolloCall} to an {@link Observable}. The number of emissions this Observable will have is based
 * on the {@link com.apollographql.apollo.fetcher.ResponseFetcher} used with the call.
 *
 * @param call the ApolloCall to convert
 * @param <T>  the value type.
 * @return the converted Observable
 * @throws NullPointerException if originalCall == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
  checkNotNull(call, "call == null");

  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, call);
      call.enqueue(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }

        @Override public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
          if (event == ApolloCall.StatusEvent.COMPLETED && !emitter.isDisposed()) {
            emitter.onComplete();
          }
        }
      });
    }
  });
}
 
Example #15
Source File: QueryRefetchTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test @SuppressWarnings("CheckReturnValue") public void refetchWatchers() throws Exception {
  server.enqueue(Utils.INSTANCE.mockResponse("ReviewsEmpireEpisodeResponse.json"));
  server.enqueue(Utils.INSTANCE.mockResponse("CreateReviewResponse.json"));
  server.enqueue(Utils.INSTANCE.mockResponse("ReviewsEmpireEpisodeResponseUpdated.json"));

  final AtomicReference<Response<ReviewsByEpisodeQuery.Data>> empireReviewsWatchResponse = new AtomicReference<>();
  ApolloQueryWatcher<ReviewsByEpisodeQuery.Data> queryWatcher = apolloClient.query(new ReviewsByEpisodeQuery(Episode.EMPIRE))
      .watcher()
      .refetchResponseFetcher(NETWORK_FIRST)
      .enqueueAndWatch(new ApolloCall.Callback<ReviewsByEpisodeQuery.Data>() {
        @Override public void onResponse(@NotNull Response<ReviewsByEpisodeQuery.Data> response) {
          empireReviewsWatchResponse.set(response);
        }

        @Override public void onFailure(@NotNull ApolloException e) {
        }
      });

  CreateReviewMutation mutation = new CreateReviewMutation(
      Episode.EMPIRE,
      ReviewInput.builder().stars(5).commentary("Awesome").favoriteColor(ColorInput.builder().build()).build()
  );
  Rx2Apollo
      .from(apolloClient.mutate(mutation).refetchQueries(queryWatcher.operation().name()))
      .test();
  assertThat(server.getRequestCount()).isEqualTo(3);

  Response<ReviewsByEpisodeQuery.Data> empireReviewsQueryResponse = empireReviewsWatchResponse.get();
  assertThat(empireReviewsQueryResponse.data().reviews()).hasSize(4);
  assertThat(empireReviewsQueryResponse.data().reviews().get(3).stars()).isEqualTo(5);
  assertThat(empireReviewsQueryResponse.data().reviews().get(3).commentary()).isEqualTo("Awesome");

  queryWatcher.cancel();
}
 
Example #16
Source File: ApolloInterceptorTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void asyncApplicationInterceptorRewritesResponsesFromServer() throws Exception {
  server.enqueue(mockResponse(FILE_EPISODE_HERO_NAME_WITH_ID));
  EpisodeHeroNameQuery query = createHeroNameQuery();
  final InterceptorResponse rewrittenResponse = prepareInterceptorResponse(query);
  ApolloInterceptor interceptor = new ApolloInterceptor() {
    @Override
    public void interceptAsync(@NotNull InterceptorRequest request, @NotNull ApolloInterceptorChain chain,
        @NotNull Executor dispatcher, @NotNull final CallBack callBack) {
      chain.proceedAsync(request, dispatcher, new CallBack() {
        @Override public void onResponse(@NotNull InterceptorResponse response) {
          callBack.onResponse(rewrittenResponse);
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          throw new RuntimeException(e);
        }

        @Override public void onCompleted() {
          callBack.onCompleted();
        }

        @Override public void onFetch(FetchSourceType sourceType) {
          callBack.onFetch(sourceType);
        }
      });
    }

    @Override public void dispose() {

    }
  };

  client = createApolloClient(interceptor);
  Rx2Apollo.from(client.query(query)).test()
      .assertValue(rewrittenResponse.parsedResponse.get());
}
 
Example #17
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void prematureDisconnect() throws Exception {
  MockResponse mockResponse = mockResponse("/HttpCacheTestAllPlanets.json");
  Buffer truncatedBody = new Buffer();
  truncatedBody.write(mockResponse.getBody(), 16);
  mockResponse.setBody(truncatedBody);
  server.enqueue(mockResponse);

  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery())
      .httpCachePolicy(HttpCachePolicy.NETWORK_ONLY))
      .test()
      .assertError(ApolloException.class);

  checkNoCachedResponse();
}
 
Example #18
Source File: HttpCacheTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void fileSystemUnavailable() throws IOException, ApolloException {
  cacheStore.delegate = new DiskLruHttpCacheStore(new NoFileSystem(), new File("/cache/"), Integer.MAX_VALUE);
  enqueueResponse("/HttpCacheTestAllPlanets.json");
  Rx2Apollo.from(apolloClient
      .query(new AllPlanetsQuery()))
      .test()
      .assertValue(new Predicate<Response<AllPlanetsQuery.Data>>() {
        @Override public boolean test(Response<AllPlanetsQuery.Data> response) throws Exception {
          return !response.hasErrors();
        }
      });
  checkNoCachedResponse();
}
 
Example #19
Source File: ApolloPrefetchCallback.java    From apollo-android with MIT License 5 votes vote down vote up
@Override public void onFailure(@NotNull final ApolloException e) {
  handler.post(new Runnable() {
    @Override public void run() {
      delegate.onFailure(e);
    }
  });
}
 
Example #20
Source File: ApolloAutoPersistedQueryInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
@Override
public void interceptAsync(@NotNull final InterceptorRequest request, @NotNull final ApolloInterceptorChain chain,
    @NotNull final Executor dispatcher, @NotNull final CallBack callBack) {

  InterceptorRequest newRequest = request.toBuilder()
          .sendQueryDocument(false)
          .autoPersistQueries(true)
          .useHttpGetMethodForQueries(request.useHttpGetMethodForQueries || useHttpGetMethodForPersistedQueries)
          .build();
  chain.proceedAsync(newRequest, dispatcher, new CallBack() {
    @Override public void onResponse(@NotNull InterceptorResponse response) {
      if (disposed) return;

      Optional<InterceptorRequest> retryRequest = handleProtocolNegotiation(request, response);
      if (retryRequest.isPresent()) {
        chain.proceedAsync(retryRequest.get(), dispatcher, callBack);
      } else {
        callBack.onResponse(response);
        callBack.onCompleted();
      }
    }

    @Override public void onFetch(FetchSourceType sourceType) {
      callBack.onFetch(sourceType);
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      callBack.onFailure(e);
    }

    @Override public void onCompleted() {
      // call onCompleted in onResponse
    }
  });
}
 
Example #21
Source File: ApolloCacheInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
InterceptorResponse resolveFromCache(InterceptorRequest request) throws ApolloException {
  ResponseNormalizer<Record> responseNormalizer = apolloStore.cacheResponseNormalizer();
  //noinspection unchecked
  ApolloStoreOperation<Response> apolloStoreOperation = apolloStore.read(request.operation, responseFieldMapper,
      responseNormalizer, request.cacheHeaders);
  Response cachedResponse = apolloStoreOperation.execute();
  if (cachedResponse.getData() != null) {
    logger.d("Cache HIT for operation %s", request.operation);
    return new InterceptorResponse(null, cachedResponse, responseNormalizer.records());
  }
  logger.d("Cache MISS for operation %s", request.operation);
  throw new ApolloException(String.format("Cache miss for operation %s", request.operation));
}
 
Example #22
Source File: ApolloCallback.java    From apollo-android with MIT License 5 votes vote down vote up
@Override public void onFailure(@NotNull final ApolloException e) {
  handler.post(new Runnable() {
    @Override public void run() {
      delegate.onFailure(e);
    }
  });
}
 
Example #23
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testQueryWatcherUpdated_Store_write() throws IOException, InterruptedException,
    TimeoutException, ApolloException {
  final List<String> heroNameList = new ArrayList<>();
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.enqueueAndWatch(
      new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
        @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
          heroNameList.add(response.data().hero().name());
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Assert.fail(e.getMessage());
        }
      });

  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");

  // Someone writes to the store directly
  Set<String> changedKeys = apolloClient.getApolloStore().writeTransaction(new Transaction<WriteableStore, Set<String>>() {
    @Nullable @Override public Set<String> execute(WriteableStore cache) {
      Record record = Record.builder("2001")
          .addField("name", "Artoo")
          .build();
      return cache.merge(Collections.singletonList(record), CacheHeaders.NONE);
    }
  });
  apolloClient.getApolloStore().publish(changedKeys);

  assertThat(heroNameList.get(1)).isEqualTo("Artoo");

  watcher.cancel();
}
 
Example #24
Source File: ApolloIdlingResourceTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void checkIdlingResourceTransition_whenCallIsQueued() throws ApolloException {
  server.enqueue(mockResponse());

  apolloClient = ApolloClient.builder()
      .okHttpClient(okHttpClient)
      .dispatcher(new Executor() {
        @Override public void execute(@NotNull Runnable command) {
          command.run();
        }
      })
      .serverUrl(server.url("/"))
      .build();

  final AtomicInteger counter = new AtomicInteger(1);
  idlingResource = ApolloIdlingResource.create(IDLING_RESOURCE_NAME, apolloClient);

  idlingResource.registerIdleTransitionCallback(new IdlingResource.ResourceCallback() {
    @Override public void onTransitionToIdle() {
      counter.decrementAndGet();
    }
  });

  assertThat(counter.get()).isEqualTo(1);
  Rx2Apollo.from(apolloClient.query(EMPTY_QUERY)).test().awaitTerminalEvent();
  assertThat(counter.get()).isEqualTo(0);
}
 
Example #25
Source File: Rx3Apollo.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * Converts an {@link ApolloCall} to an {@link Observable}. The number of emissions this Observable will have is based
 * on the {@link com.apollographql.apollo.fetcher.ResponseFetcher} used with the call.
 *
 * @param call the ApolloCall to convert
 * @param <T>  the value type.
 * @return the converted Observable
 * @throws NullPointerException if originalCall == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
  checkNotNull(call, "call == null");

  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, call);
      call.enqueue(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }

        @Override public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
          if (event == ApolloCall.StatusEvent.COMPLETED && !emitter.isDisposed()) {
            emitter.onComplete();
          }
        }
      });
    }
  });
}
 
Example #26
Source File: ApolloIdlingResourceTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void checkIsIdleNow_whenCallIsWatched() throws InterruptedException {
  server.enqueue(mockResponse());

  final CountDownLatch latch = new CountDownLatch(1);

  ExecutorService executorService = Executors.newFixedThreadPool(1);

  apolloClient = ApolloClient.builder()
      .okHttpClient(okHttpClient)
      .dispatcher(executorService)
      .serverUrl(server.url("/"))
      .build();

  idlingResource = ApolloIdlingResource.create(IDLING_RESOURCE_NAME, apolloClient);
  assertThat(idlingResource.isIdleNow()).isTrue();

  apolloClient.query(EMPTY_QUERY).watcher().enqueueAndWatch(new ApolloCall.Callback<Object>() {
    @Override public void onResponse(@NotNull Response<Object> response) {
      latch.countDown();
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      throw new AssertionError("This callback can't be called.");
    }
  });

  assertThat(idlingResource.isIdleNow()).isFalse();

  latch.await(TIME_OUT_SECONDS, TimeUnit.SECONDS);

  executorService.shutdown();
  executorService.awaitTermination(TIME_OUT_SECONDS, TimeUnit.SECONDS);
  Thread.sleep(100);
  assertThat(idlingResource.isIdleNow()).isTrue();
}
 
Example #27
Source File: ApolloIdlingResourceTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void checkIsIdleNow_whenCallIsQueued() throws InterruptedException {
  server.enqueue(mockResponse());

  final CountDownLatch latch = new CountDownLatch(1);

  ExecutorService executorService = Executors.newFixedThreadPool(1);

  apolloClient = ApolloClient.builder()
      .okHttpClient(okHttpClient)
      .dispatcher(executorService)
      .serverUrl(server.url("/"))
      .build();

  idlingResource = ApolloIdlingResource.create(IDLING_RESOURCE_NAME, apolloClient);
  assertThat(idlingResource.isIdleNow()).isTrue();

  apolloClient.query(EMPTY_QUERY).enqueue(new ApolloCall.Callback<Object>() {
    @Override public void onResponse(@NotNull Response<Object> response) {
      latch.countDown();
    }

    @Override public void onFailure(@NotNull ApolloException e) {
      throw new AssertionError("This callback can't be called.");
    }
  });
  assertThat(idlingResource.isIdleNow()).isFalse();

  latch.await(TIME_OUT_SECONDS, TimeUnit.SECONDS);

  executorService.shutdown();
  executorService.awaitTermination(TIME_OUT_SECONDS, TimeUnit.SECONDS);
  Thread.sleep(100);
  assertThat(idlingResource.isIdleNow()).isTrue();
}
 
Example #28
Source File: IntegrationTest.java    From apollo-android with MIT License 5 votes vote down vote up
private <T> List<ApolloCall.StatusEvent> enqueueCall(ApolloQueryCall<T> call) throws Exception {
  final List<ApolloCall.StatusEvent> statusEvents = new ArrayList<>();
  call.enqueue(new ApolloCall.Callback<T>() {
    @Override public void onResponse(@NotNull Response<T> response) {
    }

    @Override public void onFailure(@NotNull ApolloException e) {
    }

    @Override public void onStatusEvent(@NotNull ApolloCall.StatusEvent event) {
      statusEvents.add(event);
    }
  });
  return statusEvents;
}
 
Example #29
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testQueryWatcherNotUpdated_DifferentQueries() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.enqueueAndWatch(
      new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
        @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
          heroNameList.add(response.data().hero().name());
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Assert.fail(e.getMessage());
        }
      });

  HeroAndFriendsNamesWithIDsQuery friendsQuery = HeroAndFriendsNamesWithIDsQuery.builder().episode(Episode.NEWHOPE).build();

  server.enqueue(Utils.INSTANCE.mockResponse("HeroAndFriendsNameWithIdsResponse.json"));
  apolloClient.query(friendsQuery).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.size()).isEqualTo(1);
}
 
Example #30
Source File: ApolloWatcherTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test
public void testRefetchCacheControl() throws Exception {
  final List<String> heroNameList = new ArrayList<>();
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseWithId.json"));
  EpisodeHeroNameQuery query = EpisodeHeroNameQuery.builder().episode(Episode.EMPIRE).build();

  ApolloQueryWatcher<EpisodeHeroNameQuery.Data> watcher = apolloClient.query(query).watcher();
  watcher.refetchResponseFetcher(NETWORK_ONLY) //Force network instead of CACHE_FIRST default
      .enqueueAndWatch(
          new ApolloCall.Callback<EpisodeHeroNameQuery.Data>() {
            @Override public void onResponse(@NotNull Response<EpisodeHeroNameQuery.Data> response) {
              heroNameList.add(response.data().hero().name());
            }

            @Override public void onFailure(@NotNull ApolloException e) {
              Assert.fail(e.getCause().getMessage());
            }
          });

  //A different call gets updated information.
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseNameChange.json"));

  //To verify that the updated response comes from server use a different name change
  // -- this is for the refetch
  server.enqueue(Utils.INSTANCE.mockResponse("EpisodeHeroNameResponseNameChangeTwo.json"));
  apolloClient.query(query).responseFetcher(NETWORK_ONLY).enqueue(null);

  watcher.cancel();
  assertThat(heroNameList.get(0)).isEqualTo("R2-D2");
  assertThat(heroNameList.get(1)).isEqualTo("ArTwo");
  assertThat(heroNameList.size()).isEqualTo(2);
}