Example #1
0
  public static void testOCWillAttendLogs() {
    final String geoCode = "OC6465";

    removeCacheCompletely(geoCode);
    final Geocache cache = OkapiClient.getCache(geoCode);
    assertThat(cache).as("Cache from OKAPI").isNotNull();
    assertThat(cache.getLogCounts().get(LogType.WILL_ATTEND)).isGreaterThan(0);
  }
Example #2
0
 public static void testOCSearchMustWorkWithoutOAuthAccessTokens() {
   final String geoCode = "OC1234";
   final Geocache cache = OkapiClient.getCache(geoCode);
   assertThat(cache)
       .overridingErrorMessage(
           "You must have a valid OKAPI key installed for running this test (but you do not need to set credentials in the app).")
       .isNotNull();
   assertThat(cache.getName()).isEqualTo("Wupper-Schein");
 }
Example #3
0
 /**
  * Get geocodes of all the caches, which can be used with GCVote. Non-GC caches will be filtered
  * out.
  *
  * @param caches
  * @return
  */
 private static @NonNull ArrayList<String> getVotableGeocodes(
     final @NonNull Collection<Geocache> caches) {
   final ArrayList<String> geocodes = new ArrayList<>(caches.size());
   for (final Geocache cache : caches) {
     String geocode = cache.getGeocode();
     if (StringUtils.isNotBlank(geocode) && cache.supportsGCVote()) {
       geocodes.add(geocode);
     }
   }
   return geocodes;
 }
Example #4
0
 private static Geocache parseSmallCache(final ObjectNode response) {
   final Geocache cache = new Geocache();
   cache.setReliableLatLon(true);
   try {
     parseCoreCache(response, cache);
     DataStore.saveCache(cache, EnumSet.of(SaveFlag.CACHE));
   } catch (final NullPointerException e) {
     // FIXME: here we may return a partially filled cache
     Log.e("OkapiClient.parseSmallCache", e);
   }
   return cache;
 }
  public static void testTerrainFilter() {
    final Geocache easy = new Geocache();
    easy.setTerrain(1.5f);

    final Geocache hard = new Geocache();
    hard.setTerrain(5f);

    final AbstractRangeFilter easyFilter = new TerrainFilter(1);

    assertTrue(easyFilter.accepts(easy));
    assertFalse(easyFilter.accepts(hard));
  }
Example #6
0
  private static Geocache parseSmallCache(final JSONObject response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);
    try {

      parseCoreCache(response, cache);

      cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_CACHE));
    } catch (final JSONException e) {
      Log.e("OkapiClient.parseSmallCache", e);
    }
    return cache;
  }
Example #7
0
  public static boolean setWatchState(
      final Geocache cache, final boolean watched, final OCApiConnector connector) {
    final Parameters params = new Parameters("cache_code", cache.getGeocode());
    params.add("watched", watched ? "true" : "false");

    final ObjectNode data = request(connector, OkapiService.SERVICE_MARK_CACHE, params).data;

    if (data == null) {
      return false;
    }

    cache.setOnWatchlist(watched);

    return true;
  }
Example #8
0
  public static void testOCCacheWithWaypoints() {
    final String geoCode = "OCDDD2";
    removeCacheCompletely(geoCode);
    Geocache cache = OkapiClient.getCache(geoCode);
    assertThat(cache).as("Cache from OKAPI").isNotNull();
    // cache should be stored to DB (to listID 0) when loaded above
    cache = DataStore.loadCache(geoCode, LoadFlags.LOAD_ALL_DB_ONLY);
    assert cache != null;
    assertThat(cache).isNotNull();
    assertThat(cache.getWaypoints()).hasSize(3);

    // load again
    cache.refreshSynchronous(null);
    assertThat(cache.getWaypoints()).hasSize(3);
  }
Example #9
0
  /**
   * Transmit user vote to gcvote.com
   *
   * @param cache
   * @param vote
   * @return {@code true} if the rating was submitted successfully
   */
  public static boolean setRating(final Geocache cache, final float vote) {
    if (!isVotingPossible(cache)) {
      return false;
    }
    if (!isValidRating(vote)) {
      return false;
    }

    final ImmutablePair<String, String> login = Settings.getGCvoteLogin();
    if (login == null) {
      return false;
    }

    final Parameters params =
        new Parameters(
            "userName",
            login.left,
            "password",
            login.right,
            "cacheId",
            cache.getGuid(),
            "voteUser",
            String.format("%.1f", vote).replace(',', '.'),
            "version",
            "cgeo");

    final String result =
        Network.getResponseData(Network.getRequest("http://gcvote.com/setVote.php", params));

    return result != null && result.trim().equalsIgnoreCase("ok");
  }
Example #10
0
 public static void testGetOCCache() {
   final String geoCode = "OU0331";
   Geocache cache = OkapiClient.getCache(geoCode);
   assertThat(cache).as("Cache from OKAPI").isNotNull();
   assertEquals("Unexpected geo code", geoCode, cache.getGeocode());
   assertThat(cache.getName()).isEqualTo("Oshkosh Municipal Tank");
   assertThat(cache.isDetailed()).isTrue();
   // cache should be stored to DB (to listID 0) when loaded above
   cache = DataStore.loadCache(geoCode, LoadFlags.LOAD_ALL_DB_ONLY);
   assert cache != null;
   assertThat(cache).isNotNull();
   assertThat(cache.getGeocode()).isEqualTo(geoCode);
   assertThat(cache.getName()).isEqualTo("Oshkosh Municipal Tank");
   assertThat(cache.isDetailed()).isTrue();
   assertThat(cache.getOwnerDisplayName()).isNotEmpty();
   assertThat(cache.getOwnerUserId()).isEqualTo(cache.getOwnerDisplayName());
 }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    nonPremiumFilter = new StateFilterFactory.StateNonPremiumFilter();
    premiumCache = new Geocache();
    premiumCache.setPremiumMembersOnly(true);
  }
Example #12
0
  /**
   * Starts the default navigation tool if correctly set and installed or the compass app as default
   * fallback.
   */
  public static void startDefaultNavigationApplication(
      final int defaultNavigation, final Activity activity, final Geocache cache) {
    if (cache == null || cache.getCoords() == null) {
      ActivityMixin.showToast(
          activity, CgeoApplication.getInstance().getString(R.string.err_location_unknown));
      return;
    }

    navigateCache(activity, cache, getDefaultNavigationApplication(defaultNavigation));
  }
Example #13
0
 static void appendFieldNote(
     final StringBuilder fieldNoteBuffer, final Geocache cache, final LogEntry log) {
   fieldNoteBuffer
       .append(cache.getGeocode())
       .append(',')
       .append(fieldNoteDateFormat.format(new Date(log.date)))
       .append(',')
       .append(StringUtils.capitalize(log.type.type))
       .append(",\"")
       .append(StringUtils.replaceChars(log.log, '"', '\''))
       .append("\"\n");
 }
Example #14
0
  public static void loadRatings(final @NonNull ArrayList<Geocache> caches) {
    if (!Settings.isRatingWanted()) {
      return;
    }

    final ArrayList<String> geocodes = getVotableGeocodes(caches);
    if (geocodes.isEmpty()) {
      return;
    }

    try {
      final Map<String, GCVoteRating> ratings = GCVote.getRating(null, geocodes);

      // save found cache coordinates
      for (Geocache cache : caches) {
        if (ratings.containsKey(cache.getGeocode())) {
          GCVoteRating rating = ratings.get(cache.getGeocode());

          cache.setRating(rating.getRating());
          cache.setVotes(rating.getVotes());
          cache.setMyVote(rating.getMyVote());
        }
      }
    } catch (Exception e) {
      Log.e("GCvote.loadRatings", e);
    }
  }
Example #15
0
  private static void parseCoreCache(final JSONObject response, final Geocache cache)
      throws JSONException {
    cache.setGeocode(response.getString(CACHE_CODE));
    cache.setName(response.getString(CACHE_NAME));
    // not used: names
    setLocation(cache, response.getString(CACHE_LOCATION));
    cache.setType(getCacheType(response.getString(CACHE_TYPE)));

    final String status = response.getString(CACHE_STATUS);
    cache.setDisabled(status.equalsIgnoreCase(CACHE_STATUS_DISABLED));
    cache.setArchived(status.equalsIgnoreCase(CACHE_STATUS_ARCHIVED));

    cache.setSize(getCacheSize(response));
    cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY));
    cache.setTerrain((float) response.getDouble(CACHE_TERRAIN));

    if (!response.isNull(CACHE_IS_FOUND)) {
      cache.setFound(response.getBoolean(CACHE_IS_FOUND));
    }
  }
Example #16
0
  public static LogResult postLog(
      final Geocache cache,
      final LogType logType,
      final Calendar date,
      final String log,
      final String logPassword,
      final OCApiConnector connector) {
    final Parameters params = new Parameters("cache_code", cache.getGeocode());
    params.add("logtype", logType.oc_type);
    params.add("comment", log);
    params.add("comment_format", "plaintext");
    params.add("when", LOG_DATE_FORMAT.format(date.getTime()));
    if (logType.equals(LogType.NEEDS_MAINTENANCE)) {
      params.add("needs_maintenance", "true");
    }
    if (logPassword != null) {
      params.add("password", logPassword);
    }

    final ObjectNode data = request(connector, OkapiService.SERVICE_SUBMIT_LOG, params).data;

    if (data == null) {
      return new LogResult(StatusCode.LOG_POST_ERROR, "");
    }

    try {
      if (data.get("success").asBoolean()) {
        return new LogResult(StatusCode.NO_ERROR, data.get("log_uuid").asText());
      }

      return new LogResult(StatusCode.LOG_POST_ERROR, "");
    } catch (final NullPointerException e) {
      Log.e("OkapiClient.postLog", e);
    }
    return new LogResult(StatusCode.LOG_POST_ERROR, "");
  }
Example #17
0
  private static Geocache parseCache(final JSONObject response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);
    try {

      parseCoreCache(response, cache);

      // not used: url
      final JSONObject owner = response.getJSONObject(CACHE_OWNER);
      cache.setOwnerDisplayName(parseUser(owner));

      cache.getLogCounts().put(LogType.FOUND_IT, response.getInt(CACHE_FOUNDS));
      cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS));

      if (!response.isNull(CACHE_RATING)) {
        cache.setRating((float) response.getDouble(CACHE_RATING));
      }
      cache.setVotes(response.getInt(CACHE_VOTES));

      cache.setFavoritePoints(response.getInt(CACHE_RECOMMENDATIONS));
      // not used: req_password
      // Prepend gc-link to description if available
      final StringBuilder description = new StringBuilder(500);
      if (!response.isNull("gc_code")) {
        final String gccode = response.getString("gc_code");
        description
            .append(
                cgeoapplication
                    .getInstance()
                    .getResources()
                    .getString(R.string.cache_listed_on, GCConnector.getInstance().getName()))
            .append(": <a href=\"http://coord.info/")
            .append(gccode)
            .append("\">")
            .append(gccode)
            .append("</a><br /><br />");
      }
      description.append(response.getString(CACHE_DESCRIPTION));
      cache.setDescription(description.toString());

      // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store
      // it directly
      cache.setHint(response.getString(CACHE_HINT));
      // not used: hints

      final JSONArray images = response.getJSONArray(CACHE_IMAGES);
      if (images != null) {
        for (int i = 0; i < images.length(); i++) {
          final JSONObject imageResponse = images.getJSONObject(i);
          if (imageResponse.getBoolean(CACHE_IMAGE_IS_SPOILER)) {
            final String title = imageResponse.getString(CACHE_IMAGE_CAPTION);
            final String url =
                absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode());
            cache.addSpoiler(new Image(url, title));
          }
        }
      }

      cache.setAttributes(parseAttributes(response.getJSONArray(CACHE_ATTRNAMES)));
      cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)));
      cache.setHidden(parseDate(response.getString(CACHE_HIDDEN)));
      // TODO: Store license per cache
      // cache.setLicense(response.getString("attribution_note"));
      cache.setWaypoints(parseWaypoints(response.getJSONArray(CACHE_WPTS)), false);
      if (!response.isNull(CACHE_IS_WATCHED)) {
        cache.setOnWatchlist(response.getBoolean(CACHE_IS_WATCHED));
      }
      if (!response.isNull(CACHE_MY_NOTES)) {
        cache.setPersonalNote(response.getString(CACHE_MY_NOTES));
      }
      cache.setLogPasswordRequired(response.getBoolean(CACHE_REQ_PASSWORD));

      cache.setDetailedUpdatedNow();
      // save full detailed caches
      cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
    } catch (final JSONException e) {
      Log.e("OkapiClient.parseCache", e);
    }
    return cache;
  }
Example #18
0
  private static Geocache parseCache(final ObjectNode response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);
    try {

      parseCoreCache(response, cache);

      // not used: url
      final String owner = parseUser(response.get(CACHE_OWNER));
      cache.setOwnerDisplayName(owner);
      // OpenCaching has no distinction between user id and user display name. Set the ID anyway to
      // simplify c:geo workflows.
      cache.setOwnerUserId(owner);

      cache.getLogCounts().put(LogType.FOUND_IT, response.get(CACHE_FOUNDS).asInt());
      cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.get(CACHE_NOTFOUNDS).asInt());
      // only current Api
      cache.getLogCounts().put(LogType.WILL_ATTEND, response.path(CACHE_WILLATTENDS).asInt());

      if (response.has(CACHE_RATING)) {
        cache.setRating((float) response.get(CACHE_RATING).asDouble());
      }
      cache.setVotes(response.get(CACHE_VOTES).asInt());

      cache.setFavoritePoints(response.get(CACHE_RECOMMENDATIONS).asInt());
      // not used: req_password
      // Prepend gc-link to description if available
      final StringBuilder description = new StringBuilder(500);
      if (response.hasNonNull("gc_code")) {
        final String gccode = response.get("gc_code").asText();
        description
            .append(
                CgeoApplication.getInstance()
                    .getResources()
                    .getString(R.string.cache_listed_on, GCConnector.getInstance().getName()))
            .append(": <a href=\"http://coord.info/")
            .append(gccode)
            .append("\">")
            .append(gccode)
            .append("</a><br /><br />");
      }
      description.append(response.get(CACHE_DESCRIPTION).asText());
      cache.setDescription(description.toString());

      // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store
      // it directly
      cache.setHint(response.get(CACHE_HINT).asText());
      // not used: hints

      final ArrayNode images = (ArrayNode) response.get(CACHE_IMAGES);
      if (images != null) {
        for (final JsonNode imageResponse : images) {
          final String title = imageResponse.get(CACHE_IMAGE_CAPTION).asText();
          final String url =
              absoluteUrl(imageResponse.get(CACHE_IMAGE_URL).asText(), cache.getGeocode());
          // all images are added as spoiler images, although OKAPI has spoiler and non spoiler
          // images
          cache.addSpoiler(new Image(url, title));
        }
      }

      cache.setAttributes(
          parseAttributes(
              (ArrayNode) response.path(CACHE_ATTRNAMES),
              (ArrayNode) response.get(CACHE_ATTR_ACODES)));
      // TODO: Store license per cache
      // cache.setLicense(response.getString("attribution_note"));
      cache.setWaypoints(parseWaypoints((ArrayNode) response.path(CACHE_WPTS)), false);

      cache.setInventory(parseTrackables((ArrayNode) response.path(CACHE_TRACKABLES)));

      if (response.has(CACHE_IS_WATCHED)) {
        cache.setOnWatchlist(response.get(CACHE_IS_WATCHED).asBoolean());
      }
      if (response.hasNonNull(CACHE_MY_NOTES)) {
        cache.setPersonalNote(response.get(CACHE_MY_NOTES).asText());
        cache.parseWaypointsFromNote();
      }
      cache.setLogPasswordRequired(response.get(CACHE_REQ_PASSWORD).asBoolean());

      cache.setDetailedUpdatedNow();
      // save full detailed caches
      DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
      DataStore.saveLogsWithoutTransaction(
          cache.getGeocode(), parseLogs((ArrayNode) response.path(CACHE_LATEST_LOGS)));
    } catch (ClassCastException | NullPointerException e) {
      Log.e("OkapiClient.parseCache", e);
    }
    return cache;
  }
Example #19
0
 @Override
 protected boolean canCompare(final Geocache cache) {
   return cache.getDifficulty() != 0.0;
 }
Example #20
0
 @Override
 protected int compareCaches(final Geocache cache1, final Geocache cache2) {
   return Float.compare(cache1.getDifficulty(), cache2.getDifficulty());
 }
Example #21
0
 private static void setLocation(final Geocache cache, final String location) {
   final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING);
   final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING);
   cache.setCoords(new Geopoint(latitude, longitude));
 }
Example #22
0
  /**
   * This method constructs a <code>Point</code> for displaying in Locus
   *
   * @param cache
   * @param withWaypoints whether to give waypoints to Locus or not
   * @param withCacheDetails whether to give cache details (description, hint) to Locus or not
   *     should be false for all if more then 200 Caches are transferred
   * @return null, when the <code>Point</code> could not be constructed
   */
  private static Point getCachePoint(
      Geocache cache, boolean withWaypoints, boolean withCacheDetails) {
    if (cache == null || cache.getCoords() == null) {
      return null;
    }

    // create one simple point with location
    final Location loc = new Location("cgeo");
    loc.setLatitude(cache.getCoords().getLatitude());
    loc.setLongitude(cache.getCoords().getLongitude());

    final Point p = new Point(cache.getName(), loc);
    final PointGeocachingData pg = new PointGeocachingData();
    p.setGeocachingData(pg);

    // set data in Locus' cache
    pg.cacheID = cache.getGeocode();
    pg.available = !cache.isDisabled();
    pg.archived = cache.isArchived();
    pg.premiumOnly = cache.isPremiumMembersOnly();
    pg.name = cache.getName();
    pg.placedBy = cache.getOwnerDisplayName();
    final Date hiddenDate = cache.getHiddenDate();
    if (hiddenDate != null) {
      pg.hidden = ISO8601DATE.format(hiddenDate);
    }
    int locusId = toLocusType(cache.getType());
    if (locusId != NO_LOCUS_ID) {
      pg.type = locusId;
    }
    locusId = toLocusSize(cache.getSize());
    if (locusId != NO_LOCUS_ID) {
      pg.container = locusId;
    }
    if (cache.getDifficulty() > 0) {
      pg.difficulty = cache.getDifficulty();
    }
    if (cache.getTerrain() > 0) {
      pg.terrain = cache.getTerrain();
    }
    pg.found = cache.isFound();

    if (withWaypoints && cache.hasWaypoints()) {
      pg.waypoints = new ArrayList<>();
      for (Waypoint waypoint : cache.getWaypoints()) {
        if (waypoint == null || waypoint.getCoords() == null) {
          continue;
        }
        PointGeocachingDataWaypoint wp = new PointGeocachingDataWaypoint();
        wp.code = waypoint.getGeocode();
        wp.name = waypoint.getName();
        String locusWpId = toLocusWaypoint(waypoint.getWaypointType());
        if (locusWpId != null) {
          wp.type = locusWpId;
        }
        wp.lat = waypoint.getCoords().getLatitude();
        wp.lon = waypoint.getCoords().getLongitude();
        pg.waypoints.add(wp);
      }
    }

    // Other properties of caches. When there are many caches to be displayed
    // in Locus, using these properties can lead to Exceptions in Locus.
    // Should not be used if caches count > 200

    if (withCacheDetails) {
      pg.shortDescription = cache.getShortDescription();
      pg.longDescription = cache.getDescription();
      pg.encodedHints = cache.getHint();
    }

    return p;
  }
Example #23
0
 @Override
 protected int compareCaches(final Geocache cache1, final Geocache cache2) {
   return Long.valueOf(cache2.getVisitedDate()).compareTo(cache1.getVisitedDate());
 }
Example #24
0
 @Override
 public boolean isOwner(final Geocache cache) {
   return StringUtils.isNotEmpty(getUserName())
       && StringUtils.equals(cache.getOwnerDisplayName(), getUserName());
 }
Example #25
0
 public static boolean isVotingPossible(final Geocache cache) {
   return Settings.isGCvoteLogin()
       && StringUtils.isNotBlank(cache.getGuid())
       && cache.supportsGCVote();
 }
Example #26
0
  private static void parseCoreCache(final ObjectNode response, final Geocache cache) {
    cache.setGeocode(response.get(CACHE_CODE).asText());
    cache.setName(response.get(CACHE_NAME).asText());
    // not used: names
    setLocation(cache, response.get(CACHE_LOCATION).asText());
    cache.setType(getCacheType(response.get(CACHE_TYPE).asText()));

    final String status = response.get(CACHE_STATUS).asText();
    cache.setDisabled(status.equalsIgnoreCase(CACHE_STATUS_DISABLED));
    cache.setArchived(status.equalsIgnoreCase(CACHE_STATUS_ARCHIVED));

    cache.setSize(getCacheSize(response));
    cache.setDifficulty((float) response.get(CACHE_DIFFICULTY).asDouble());
    cache.setTerrain((float) response.get(CACHE_TERRAIN).asDouble());

    cache.setInventoryItems(response.get(CACHE_TRACKABLES_COUNT).asInt());

    if (response.has(CACHE_IS_FOUND)) {
      cache.setFound(response.get(CACHE_IS_FOUND).asBoolean());
    }
    cache.setHidden(parseDate(response.get(CACHE_HIDDEN).asText()));
  }
Example #27
0
 @Override
 public boolean accepts(final Geocache cache) {
   return (cache.getFavoritePoints() > minFavorites)
       && (cache.getFavoritePoints() <= maxFavorites);
 }
Example #28
0
 public static void testGetAllLogs() {
   final String geoCode = "OC10CB8";
   final Geocache cache = OkapiClient.getCache(geoCode);
   final int defaultLogCount = 10;
   assertThat(cache.getLogs().size()).isGreaterThan(defaultLogCount);
 }
 @Override
 public String getCacheUrl(final @NonNull Geocache cache) {
   return getCacheUrlPrefix() + cache.getGeocode();
 }
Example #30
0
 @NonNull
 public static IConnector getConnector(final Geocache cache) {
   return getConnector(cache.getGeocode());
 }