com.apollographql.apollo.api.Operation Java Examples

The following examples show how to use com.apollographql.apollo.api.Operation. 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: ApolloClient.java    From apollo-android with MIT License 6 votes vote down vote up
private <D extends Operation.Data, T, V extends Operation.Variables> RealApolloCall<T> newCall(
    @NotNull Operation<D, T, V> operation) {
  return RealApolloCall.<T>builder()
      .operation(operation)
      .serverUrl(serverUrl)
      .httpCallFactory(httpCallFactory)
      .httpCache(httpCache)
      .httpCachePolicy(defaultHttpCachePolicy)
      .responseFieldMapperFactory(responseFieldMapperFactory)
      .scalarTypeAdapters(scalarTypeAdapters)
      .apolloStore(apolloStore)
      .responseFetcher(defaultResponseFetcher)
      .cacheHeaders(defaultCacheHeaders)
      .dispatcher(dispatcher)
      .logger(logger)
      .applicationInterceptors(applicationInterceptors)
      .applicationInterceptorFactories(applicationInterceptorFactories)
      .tracker(tracker)
      .refetchQueries(Collections.<Query>emptyList())
      .refetchQueryNames(Collections.<OperationName>emptyList())
      .enableAutoPersistedQueries(enableAutoPersistedQueries)
      .useHttpGetMethodForQueries(useHttpGetMethodForQueries)
      .useHttpGetMethodForPersistedQueries(useHttpGetMethodForPersistedQueries)
      .build();
}
 
Example #2
Source File: RealApolloStore.java    From apollo-android with MIT License 6 votes vote down vote up
<D extends Operation.Data, T, V extends Operation.Variables> Set<String> doWrite(
    final Operation<D, T, V> operation, final D operationData, final boolean optimistic,
    final UUID mutationId) {
  return writeTransaction(new Transaction<WriteableStore, Set<String>>() {
    @Override public Set<String> execute(WriteableStore cache) {
      RealResponseWriter responseWriter = new RealResponseWriter(operation.variables(), scalarTypeAdapters);
      operationData.marshaller().marshal(responseWriter);

      ResponseNormalizer<Map<String, Object>> responseNormalizer = networkResponseNormalizer();
      responseNormalizer.willResolveRootQuery(operation);
      responseWriter.resolveFields(responseNormalizer);
      if (optimistic) {
        List<Record> updatedRecords = new ArrayList<>();
        for (Record record : responseNormalizer.records()) {
          updatedRecords.add(record.toBuilder().mutationId(mutationId).build());
        }
        return optimisticCache.mergeOptimisticUpdates(updatedRecords);
      } else {
        return optimisticCache.merge(responseNormalizer.records(), CacheHeaders.NONE);
      }
    }
  });
}
 
Example #3
Source File: RealApolloStore.java    From apollo-android with MIT License 6 votes vote down vote up
<F extends GraphqlFragment> F doRead(final ResponseFieldMapper<F> responseFieldMapper,
    final CacheKey cacheKey, final Operation.Variables variables) {
  return readTransaction(new Transaction<ReadableStore, F>() {
    @Nullable @Override public F execute(ReadableStore cache) {
      Record rootRecord = cache.read(cacheKey.key(), CacheHeaders.NONE);
      if (rootRecord == null) {
        return null;
      }

      CacheFieldValueResolver fieldValueResolver = new CacheFieldValueResolver(cache, variables,
          cacheKeyResolver(), CacheHeaders.NONE, cacheKeyBuilder);
      //noinspection unchecked
      RealResponseReader<Record> responseReader = new RealResponseReader<>(variables, rootRecord,
          fieldValueResolver, scalarTypeAdapters, ResponseNormalizer.NO_OP_NORMALIZER);
      return responseFieldMapper.map(responseReader);
    }
  });
}
 
Example #4
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void connecting() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());

  assertThat(subscriptionTransportFactory.subscriptionTransport).isNotNull();
  assertThat(subscriptionTransportFactory.subscriptionTransport.connected).isTrue();
  assertThat(subscriptionTransportFactory.subscriptionTransport.lastSentMessage).isNull();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.CONNECTING);

  subscriptionManager.subscribe(subscription2, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  assertThat(subscriptionTransportFactory.subscriptionTransport.connected).isTrue();
  assertThat(subscriptionTransportFactory.subscriptionTransport.lastSentMessage).isNull();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.CONNECTING);

  assertThat(subscriptionManager.subscriptions).hasSize(2);

  assertThat(subscriptionManager.timer.tasks).isEmpty();
}
 
Example #5
Source File: ApolloServerInterceptor.java    From apollo-android with MIT License 6 votes vote down vote up
static HttpUrl httpGetUrl(HttpUrl serverUrl, Operation operation,
    ScalarTypeAdapters scalarTypeAdapters, boolean writeQueryDocument,
    boolean autoPersistQueries) throws IOException {
  HttpUrl.Builder urlBuilder = serverUrl.newBuilder();
  if (!autoPersistQueries || writeQueryDocument) {
    urlBuilder.addQueryParameter("query", operation.queryDocument());
  }
  if (operation.variables() != Operation.EMPTY_VARIABLES) {
    addVariablesUrlQueryParameter(urlBuilder, operation, scalarTypeAdapters);
  }
  urlBuilder.addQueryParameter("operationName", operation.name().name());
  if (autoPersistQueries) {
    addExtensionsUrlQueryParameter(urlBuilder, operation);
  }
  return urlBuilder.build();
}
 
Example #6
Source File: ApolloCacheInterceptorTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test
public void testDoesNotCacheErrorResponse() {
  Operation<?, ?, ?> operation = mock(Operation.class);
  Error error = new Error("Error", Collections.emptyList(), Collections.emptyMap());
  ApolloInterceptor.InterceptorResponse networkResponse = new ApolloInterceptor.InterceptorResponse(
      okHttpResponse,
      com.apollographql.apollo.api.Response.builder(operation).errors(Collections.singletonList(error)).build(),
      new ArrayList<Record>()
  );
  ApolloInterceptor.InterceptorRequest request = ApolloInterceptor.InterceptorRequest.builder(operation).build();

  Set<String> cachedKeys = interceptor.cacheResponse(networkResponse, request);

  assertThat(cachedKeys).isEmpty();
  verifyZeroInteractions(apolloStore, logger);
}
 
Example #7
Source File: RealApolloStore.java    From apollo-android with MIT License 6 votes vote down vote up
<D extends Operation.Data, T, V extends Operation.Variables> T doRead(final Operation<D, T, V> operation) {
  return readTransaction(new Transaction<ReadableStore, T>() {
    @Nullable @Override public T execute(ReadableStore cache) {
      Record rootRecord = cache.read(CacheKeyResolver.rootKeyForOperation(operation).key(), CacheHeaders.NONE);
      if (rootRecord == null) {
        return null;
      }

      ResponseFieldMapper<D> responseFieldMapper = operation.responseFieldMapper();
      CacheFieldValueResolver fieldValueResolver = new CacheFieldValueResolver(cache, operation.variables(),
          cacheKeyResolver(), CacheHeaders.NONE, cacheKeyBuilder);
      //noinspection unchecked
      RealResponseReader<Record> responseReader = new RealResponseReader<>(operation.variables(), rootRecord,
          fieldValueResolver, scalarTypeAdapters, ResponseNormalizer.NO_OP_NORMALIZER);
      return operation.wrapData(responseFieldMapper.map(responseReader));
    }
  });
}
 
Example #8
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 6 votes vote down vote up
@Test public void unsubscribeOnComplete() {
  SubscriptionManagerCallbackAdapter<Operation.Data> subscriptionManagerCallback1 = new SubscriptionManagerCallbackAdapter<>();
  subscriptionManager.subscribe(subscription1, subscriptionManagerCallback1);
  SubscriptionManagerCallbackAdapter<Operation.Data> subscriptionManagerCallback2 = new SubscriptionManagerCallbackAdapter<>();
  subscriptionManager.subscribe(subscription2, subscriptionManagerCallback2);

  final List<UUID> subscriptionIds = new ArrayList<>(subscriptionManager.subscriptions.keySet());

  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.Complete(subscriptionIds.get(0).toString()));
  assertThat(subscriptionManagerCallback1.completed).isTrue();

  assertThat(subscriptionManager.subscriptions).hasSize(1);
  assertThat(subscriptionManagerCallback2.completed).isFalse();
}
 
Example #9
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void active() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.ACTIVE);
  assertThat(subscriptionTransportFactory.subscriptionTransport.lastSentMessage).isInstanceOf(OperationClientMessage.Start.class);
  assertThat(subscriptionManager.timer.tasks).isEmpty();
}
 
Example #10
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void stopWhenConnected() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionManager.subscribe(subscription2, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.CONNECTED);

  subscriptionManager.stop();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.STOPPED);
}
 
Example #11
Source File: ApolloInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
InterceptorRequest(Operation operation, CacheHeaders cacheHeaders, RequestHeaders requestHeaders,
    Optional<Operation.Data> optimisticUpdates, boolean fetchFromCache,
    boolean sendQueryDocument, boolean useHttpGetMethodForQueries, boolean autoPersistQueries) {
  this.operation = operation;
  this.cacheHeaders = cacheHeaders;
  this.requestHeaders = requestHeaders;
  this.optimisticUpdates = optimisticUpdates;
  this.fetchFromCache = fetchFromCache;
  this.sendQueryDocument = sendQueryDocument;
  this.useHttpGetMethodForQueries = useHttpGetMethodForQueries;
  this.autoPersistQueries = autoPersistQueries;
}
 
Example #12
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Override public ResponseFieldMapper<Data> responseFieldMapper() {
  return new ResponseFieldMapper<Data>() {
    @Override public Data map(ResponseReader responseReader) {
      return new Operation.Data() {
        @Override public ResponseFieldMarshaller marshaller() {
          throw new UnsupportedOperationException();
        }
      };
    }
  };
}
 
Example #13
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void startWhenStopped() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  subscriptionManager.stop();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.STOPPED);

  subscriptionManager.start();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.DISCONNECTED);
}
 
Example #14
Source File: ApolloCallTracker.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * <p>Removes provided {@link ApolloCall} that finished his execution, if it is found, else throws an
 * {@link AssertionError}.</p>
 * <p>
 * If the removal operation is successful and no active running calls are found, then the registered
 * {@link ApolloCallTracker#idleResourceCallback} is invoked.
 *
 * <p><b>Note</b>: This method needs to be called right after an apolloCall is completed (whether successful or
 * failed).</p>
 */
void unregisterCall(@NotNull ApolloCall call) {
  checkNotNull(call, "call == null");
  Operation operation = call.operation();
  if (operation instanceof Query) {
    unregisterQueryCall((ApolloQueryCall) call);
  } else if (operation instanceof Mutation) {
    unregisterMutationCall((ApolloMutationCall) call);
  } else {
    throw new IllegalArgumentException("Unknown call type");
  }
}
 
Example #15
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void connected() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.CONNECTED);
  assertThat(subscriptionTransportFactory.subscriptionTransport.lastSentMessage).isInstanceOf(OperationClientMessage.Init.class);
  assertThat(subscriptionManager.timer.tasks).containsKey(RealSubscriptionManager.CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID);
}
 
Example #16
Source File: ResponseNormalizer.java    From apollo-android with MIT License 5 votes vote down vote up
@NotNull @Override public CacheKeyBuilder cacheKeyBuilder() {
  return new CacheKeyBuilder() {
    @NotNull @Override public String build(@NotNull ResponseField field, @NotNull Operation.Variables variables) {
      return CacheKey.NO_KEY.key();
    }
  };
}
 
Example #17
Source File: ApolloCallTracker.java    From apollo-android with MIT License 5 votes vote down vote up
/**
 * <p>Adds provided {@link ApolloCall} that is currently in progress.</p>
 *
 * <p><b>Note</b>: This method needs to be called right before an apolloCall is executed.</p>
 */
void registerCall(@NotNull ApolloCall call) {
  checkNotNull(call, "call == null");
  Operation operation = call.operation();
  if (operation instanceof Query) {
    registerQueryCall((ApolloQueryCall) call);
  } else if (operation instanceof Mutation) {
    registerMutationCall((ApolloMutationCall) call);
  } else {
    throw new IllegalArgumentException("Unknown call type");
  }
}
 
Example #18
Source File: RealApolloStore.java    From apollo-android with MIT License 5 votes vote down vote up
Set<String> doWrite(final GraphqlFragment fragment, final CacheKey cacheKey, final Operation.Variables variables) {
  return writeTransaction(new Transaction<WriteableStore, Set<String>>() {
    @Override public Set<String> execute(WriteableStore cache) {
      RealResponseWriter responseWriter = new RealResponseWriter(variables, scalarTypeAdapters);
      fragment.marshaller().marshal(responseWriter);

      ResponseNormalizer<Map<String, Object>> responseNormalizer = networkResponseNormalizer();
      responseNormalizer.willResolveRecord(cacheKey);
      responseWriter.resolveFields(responseNormalizer);

      return merge(responseNormalizer.records(), CacheHeaders.NONE);
    }
  });
}
 
Example #19
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void duplicateSubscriptions() {
  SubscriptionManagerCallbackAdapter<Operation.Data> subscriptionManagerCallback1 = new SubscriptionManagerCallbackAdapter<>();
  subscriptionManager.subscribe(subscription1, subscriptionManagerCallback1);
  SubscriptionManagerCallbackAdapter<Operation.Data> subscriptionManagerCallback2 = new SubscriptionManagerCallbackAdapter<>();
  subscriptionManager.subscribe(subscription1, subscriptionManagerCallback2);

  assertThat(subscriptionManagerCallback2.error).isNull();
}
 
Example #20
Source File: ApolloServerInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
Call httpGetCall(Operation operation, CacheHeaders cacheHeaders, RequestHeaders requestHeaders,
    boolean writeQueryDocument, boolean autoPersistQueries) throws IOException {
  Request.Builder requestBuilder = new Request.Builder()
      .url(httpGetUrl(serverUrl, operation, scalarTypeAdapters, writeQueryDocument, autoPersistQueries))
      .get();
  decorateRequest(requestBuilder, operation, cacheHeaders, requestHeaders);
  return httpCallFactory.newCall(requestBuilder.build());
}
 
Example #21
Source File: ApolloServerInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
Call httpPostCall(Operation operation, CacheHeaders cacheHeaders, RequestHeaders requestHeaders,
    boolean writeQueryDocument, boolean autoPersistQueries) throws IOException {
  RequestBody requestBody = RequestBody.create(MEDIA_TYPE, httpPostRequestBody(operation, scalarTypeAdapters,
      writeQueryDocument, autoPersistQueries));

  requestBody = transformToMultiPartIfUploadExists(requestBody, operation);

  Request.Builder requestBuilder = new Request.Builder()
      .url(serverUrl)
      .header(HEADER_CONTENT_TYPE, CONTENT_TYPE)
      .post(requestBody);
  decorateRequest(requestBuilder, operation, cacheHeaders, requestHeaders);
  return httpCallFactory.newCall(requestBuilder.build());
}
 
Example #22
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void stopWhenActive() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.ACTIVE);

  subscriptionManager.stop();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.STOPPED);
}
 
Example #23
Source File: ApolloServerInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
static void addVariablesUrlQueryParameter(HttpUrl.Builder urlBuilder, Operation operation,
    ScalarTypeAdapters scalarTypeAdapters) throws IOException {
  Buffer buffer = new Buffer();
  JsonWriter jsonWriter = JsonWriter.of(buffer);
  jsonWriter.setSerializeNulls(true);
  jsonWriter.beginObject();
  operation.variables().marshaller().marshal(new InputFieldJsonWriter(jsonWriter, scalarTypeAdapters));
  jsonWriter.endObject();
  jsonWriter.close();
  urlBuilder.addQueryParameter("variables", buffer.readUtf8());
}
 
Example #24
Source File: ApolloServerInterceptor.java    From apollo-android with MIT License 5 votes vote down vote up
static void addExtensionsUrlQueryParameter(HttpUrl.Builder urlBuilder, Operation operation) throws IOException {
  Buffer buffer = new Buffer();
  JsonWriter jsonWriter = JsonWriter.of(buffer);
  jsonWriter.setSerializeNulls(true);
  jsonWriter.beginObject();
  jsonWriter.name("persistedQuery")
      .beginObject()
      .name("version").value(1)
      .name("sha256Hash").value(operation.operationId())
      .endObject();
  jsonWriter.endObject();
  jsonWriter.close();
  urlBuilder.addQueryParameter("extensions", buffer.readUtf8());
}
 
Example #25
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void startWhenActive() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.ACTIVE);

  subscriptionManager.start();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.ACTIVE);
}
 
Example #26
Source File: ResponseFieldMapperFactory.java    From apollo-android with MIT License 5 votes vote down vote up
@NotNull public ResponseFieldMapper create(@NotNull Operation operation) {
  checkNotNull(operation, "operation == null");
  Class operationClass = operation.getClass();
  ResponseFieldMapper mapper = pool.get(operationClass);
  if (mapper != null) {
    return mapper;
  }
  pool.putIfAbsent(operationClass, operation.responseFieldMapper());
  return pool.get(operationClass);
}
 
Example #27
Source File: SubscriptionManagerTest.java    From apollo-android with MIT License 5 votes vote down vote up
@Test public void stopWhenStopped() {
  subscriptionManager.subscribe(subscription1, new SubscriptionManagerCallbackAdapter<Operation.Data>());
  subscriptionTransportFactory.callback.onConnected();
  subscriptionTransportFactory.callback.onMessage(new OperationServerMessage.ConnectionAcknowledge());
  subscriptionManager.stop();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.STOPPED);

  subscriptionManager.stop();
  assertThat(subscriptionManager.state).isEqualTo(SubscriptionManagerState.STOPPED);
}
 
Example #28
Source File: RealApolloStore.java    From apollo-android with MIT License 5 votes vote down vote up
@Override @NotNull public <D extends Operation.Data, T, V extends Operation.Variables>
ApolloStoreOperation<Response<T>> read(@NotNull final Operation<D, T, V> operation,
    @NotNull final ResponseFieldMapper<D> responseFieldMapper,
    @NotNull final ResponseNormalizer<Record> responseNormalizer, @NotNull final CacheHeaders cacheHeaders) {
  checkNotNull(operation, "operation == null");
  checkNotNull(responseNormalizer, "responseNormalizer == null");
  return new ApolloStoreOperation<Response<T>>(dispatcher) {
    @Override protected Response<T> perform() {
      return doRead(operation, responseFieldMapper, responseNormalizer, cacheHeaders);
    }
  };
}
 
Example #29
Source File: RealApolloStore.java    From apollo-android with MIT License 5 votes vote down vote up
@Override @NotNull public <F extends GraphqlFragment> ApolloStoreOperation<F> read(
    @NotNull final ResponseFieldMapper<F> responseFieldMapper, @NotNull final CacheKey cacheKey,
    @NotNull final Operation.Variables variables) {
  checkNotNull(responseFieldMapper, "responseFieldMapper == null");
  checkNotNull(cacheKey, "cacheKey == null");
  checkNotNull(variables, "variables == null");
  return new ApolloStoreOperation<F>(dispatcher) {
    @Override protected F perform() {
      return doRead(responseFieldMapper, cacheKey, variables);
    }
  };
}
 
Example #30
Source File: RealApolloStore.java    From apollo-android with MIT License 5 votes vote down vote up
@Override @NotNull public <D extends Operation.Data, T, V extends Operation.Variables>
ApolloStoreOperation<Set<String>> write(@NotNull final Operation<D, T, V> operation, @NotNull final D operationData) {
  checkNotNull(operation, "operation == null");
  checkNotNull(operationData, "operationData == null");
  return new ApolloStoreOperation<Set<String>>(dispatcher) {
    @Override protected Set<String> perform() {
      return doWrite(operation, operationData, false, null);
    }
  };
}