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

co.easimart.NetworkQueryController Maven / Gradle / Ivy

package co.easimart;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import bolts.Continuation;
import bolts.Task;

/** package */ class NetworkQueryController extends AbstractQueryController {

  private static final String TAG = "NetworkQueryController";

  private final EasimartHttpClient restClient;

  public NetworkQueryController(EasimartHttpClient restClient) {
    this.restClient = restClient;
  }

  @Override
  public  Task> findAsync(
      EasimartQuery.State state, EasimartUser user, Task cancellationToken) {
    String sessionToken = user != null ? user.getSessionToken() : null;
    return findAsync(state, sessionToken, true, cancellationToken);
  }

  @Override
  public  Task countAsync(
      EasimartQuery.State state, EasimartUser user, Task cancellationToken) {
    String sessionToken = user != null ? user.getSessionToken() : null;
    return countAsync(state, sessionToken, true, cancellationToken);
  }

  /**
   * Retrieves a list of {@link EasimartObject}s that satisfy this query from the source.
   *
   * @return A list of all {@link EasimartObject}s obeying the conditions set in this query.
   */
  /* package */  Task> findAsync(
      final EasimartQuery.State state,
      String sessionToken,
      boolean shouldRetry,
      Task ct) {
    final long queryStart = System.nanoTime();

    final EasimartRESTCommand command = EasimartRESTQueryCommand.findCommand(state, sessionToken);
    if (shouldRetry) {
      command.enableRetrying();
    }

    final long querySent = System.nanoTime();
    return command.executeAsync(restClient, ct).onSuccess(new Continuation>() {
      @Override
      public List then(Task task) throws Exception {
        JSONObject json = task.getResult();
        // Cache the results, unless we are ignoring the cache
        EasimartQuery.CachePolicy policy = state.cachePolicy();
        if (policy != null && (policy != EasimartQuery.CachePolicy.IGNORE_CACHE)) {
          EasimartKeyValueCache.saveToKeyValueCache(command.getCacheKey(), json.toString());
        }

        long queryReceived = System.nanoTime();

        List response = convertFindResponse(state, task.getResult());

        long objectsEasimartd = System.nanoTime();

        if (json.has("trace")) {
          Object serverTrace = json.get("trace");
          EasimartLog.d("EasimartQuery",
                  String.format("Query pre-processing took %f seconds\n" +
                                  "%s\n" +
                                  "Client side parsing took %f seconds\n",
                          (querySent - queryStart) / (1000.0f * 1000.0f),
                          serverTrace,
                          (objectsEasimartd - queryReceived) / (1000.0f * 1000.0f)));
        }
        return response;
      }
    }, Task.BACKGROUND_EXECUTOR);
  }

  /* package */  Task countAsync(
      final EasimartQuery.State state,
      String sessionToken,
      boolean shouldRetry,
      Task ct) {
    final EasimartRESTCommand command = EasimartRESTQueryCommand.countCommand(state, sessionToken);
    if (shouldRetry) {
      command.enableRetrying();
    }

    return command.executeAsync(restClient, ct).onSuccessTask(new Continuation>() {
      @Override
      public Task then(Task task) throws Exception {
        // Cache the results, unless we are ignoring the cache
        EasimartQuery.CachePolicy policy = state.cachePolicy();
        if (policy != null && policy != EasimartQuery.CachePolicy.IGNORE_CACHE) {
          JSONObject result = task.getResult();
          EasimartKeyValueCache.saveToKeyValueCache(command.getCacheKey(), result.toString());
        }
        return task;
      }
    }, Task.BACKGROUND_EXECUTOR).onSuccess(new Continuation() {
      @Override
      public Integer then(Task task) throws Exception {
        // Convert response
        return task.getResult().optInt("count");
      }
    });
  }

  // Converts the JSONArray that represents the results of a find command to an
  // ArrayList.
  /* package */  List convertFindResponse(EasimartQuery.State state,
      JSONObject response) throws JSONException {
    ArrayList answer = new ArrayList<>();
    JSONArray results = response.getJSONArray("results");
    if (results == null) {
      EasimartLog.d(TAG, "null results in find response");
    } else {
      String resultClassName = response.optString("className", null);
      if (resultClassName == null) {
        resultClassName = state.className();
      }
      for (int i = 0; i < results.length(); ++i) {
        JSONObject data = results.getJSONObject(i);
        T object = EasimartObject.fromJSON(data, resultClassName, state.selectedKeys() == null);
        answer.add(object);

        /*
         * If there was a $relatedTo constraint on the query, then add any results to the list of
         * known objects in the relation for offline caching
         */
        EasimartQuery.RelationConstraint relation =
            (EasimartQuery.RelationConstraint) state.constraints().get("$relatedTo");
        if (relation != null) {
          relation.getRelation().addKnownObject(object);
        }
      }
    }

    return answer;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy