示例#1
0
  /**
   * Gets the ID of the last pulled train update.
   *
   * @return the ID or -1 if there aren't any stored IDs.
   */
  public static long getLatestUpdateId() {
    StorageStats stats = getStorageStats();

    if (stats != null) {
      return stats.getLatestUpdateId();
    }

    // TODO: will stats ever be null?

    // TODO:  We should store the latest ID instead of querying for it.
    // That way we don't run into a situation where the data store gets cleared and we end up
    // pulling 200 updates.

    // Attempt to just pull the value out of the cache.
    // We assume that the latest updates will always live here.
    @SuppressWarnings("unchecked")
    List<TrainUpdate> cachedUpdates = (List<TrainUpdate>) cache.get(CACHED_UPDATES_KEY);

    if (cachedUpdates != null && !cachedUpdates.isEmpty()) {
      log.info("Fetched cache with size of : " + cachedUpdates.size());
      return cachedUpdates.get(cachedUpdates.size() - 1).getTwitterId();
    }

    // If no cached updates were found, we must query the datastore.

    long sinceId = -1;
    PersistenceManager pm = PMF.get().getPersistenceManager();

    try {
      Query query = pm.newQuery(TrainUpdate.class);
      query.setOrdering("date DESC");
      query.setRange(0, 1);

      @SuppressWarnings("unchecked")
      List<TrainUpdate> oldUpdates = (List<TrainUpdate>) query.execute();

      if (oldUpdates.size() > 0) {
        sinceId = oldUpdates.get(0).getTwitterId();
      }
    } finally {
      pm.close();
    }

    return sinceId;
  }