/** Test {@link cgBase#searchByOwner(String, String, int, boolean, CancellableHandler)} */
 @MediumTest
 public static void testSearchByOwner() {
   final SearchResult search = cgBase.searchByOwner(null, "blafoo", CacheType.MYSTERY, 0, false);
   assertNotNull(search);
   assertEquals(3, search.getGeocodes().size());
   assertTrue(search.getGeocodes().contains("GC36RT6"));
 }
 /** Test {@link cgBase#searchByCoords(cgSearchThread, Geopoint, String, int, boolean)} */
 @MediumTest
 public static void testSearchByCoords() {
   final SearchResult search =
       cgBase.searchByCoords(
           null, new Geopoint("N 52° 24.972 E 009° 35.647"), CacheType.MYSTERY, 0, false);
   assertNotNull(search);
   assertTrue(18 <= search.getGeocodes().size());
   assertTrue(search.getGeocodes().contains("GC1RMM2"));
 }
 /** Test {@link cgBase#searchByGeocode(String, String, int, boolean, CancellableHandler)} */
 @MediumTest
 public static cgCache testSearchByGeocode(final String geocode) {
   final SearchResult search = cgBase.searchByGeocode(geocode, null, 0, true, null);
   assertNotNull(search);
   if (Settings.isPremiumMember() || search.error == null) {
     assertEquals(1, search.getGeocodes().size());
     assertTrue(search.getGeocodes().contains(geocode));
     return cgeoapplication.getInstance().loadCache(geocode, LoadFlags.LOADCACHEORDB);
   }
   assertEquals(0, search.getGeocodes().size());
   return null;
 }
  /** Test {@link cgBase#searchByViewport(String, Viewport)} */
  @MediumTest
  public static void testSearchByViewport() {

    if (LIVEMAPENABLED) {
      GC2JVEH cache = new GC2JVEH();

      final String token = cgBase.getMapUserToken(new Handler());
      final Viewport viewport = new Viewport(cache.getCoords(), 0.003, 0.003);
      final SearchResult search = cgBase.searchByViewport(token, viewport);

      // GC2JVEH is a premium members only cache. It can't be "found" by non-premium members
      if (Settings.isPremiumMember()) {
        assertNotNull(search);
        // coords are identical... if the user is logged in
        if (search.error != null) {
          if (search.getGeocodes().contains(cache.getGeocode())) {
            assertFalse(
                cache
                    .getCoords()
                    .isEqualTo(
                        cgeoapplication
                            .getInstance()
                            .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                            .getCoords()));
            assertFalse(
                cgeoapplication
                    .getInstance()
                    .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                    .isReliableLatLon());
          }
        } else {
          assertTrue(search.getGeocodes().contains(cache.getGeocode()));
          assertEquals(
              cache.getCoords().toString(),
              cgeoapplication
                  .getInstance()
                  .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                  .getCoords()
                  .toString());
          assertTrue(
              cgeoapplication
                  .getInstance()
                  .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                  .isReliableLatLon());
        }
      }
    }
  }
 /** Test {@link cgBase#searchByUsername(String, String, int, boolean, CancellableHandler)} */
 @MediumTest
 public static void testSearchByUsername() {
   final SearchResult search = cgBase.searchByUsername(null, "blafoo", CacheType.WEBCAM, 0, false);
   assertNotNull(search);
   assertEquals(3, search.totalCnt);
   assertTrue(search.getGeocodes().contains("GCP0A9"));
 }
  public void testImportGpxZipAttachment() {
    Uri uri = Uri.parse("android.resource://cgeo.geocaching.test/raw/pq7545915");

    GPXImporter.ImportGpxZipAttachmentThread importThread =
        new GPXImporter.ImportGpxZipAttachmentThread(
            uri,
            getInstrumentation().getContext().getContentResolver(),
            listId,
            importStepHandler,
            progressHandler);
    runImportThread(importThread);

    assertImportStepMessages(
        GPXImporter.IMPORT_STEP_START,
        GPXImporter.IMPORT_STEP_READ_FILE,
        GPXImporter.IMPORT_STEP_READ_WPT_FILE,
        GPXImporter.IMPORT_STEP_STORE_CACHES,
        GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS,
        GPXImporter.IMPORT_STEP_FINISHED);
    SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj;
    assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);
    assertEquals(
        1,
        cache
            .getWaypoints()
            .size()); // this is the original pocket query result without test waypoint
  }
  public void testImportGpxZip() throws IOException {
    File pq7545915 = new File(tempDir, "7545915.zip");
    copyResourceToFile(R.raw.pq7545915, pq7545915);

    GPXImporter.ImportGpxZipFileThread importThread =
        new GPXImporter.ImportGpxZipFileThread(
            pq7545915, listId, importStepHandler, progressHandler);
    runImportThread(importThread);

    assertImportStepMessages(
        GPXImporter.IMPORT_STEP_START,
        GPXImporter.IMPORT_STEP_READ_FILE,
        GPXImporter.IMPORT_STEP_READ_WPT_FILE,
        GPXImporter.IMPORT_STEP_STORE_CACHES,
        GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS,
        GPXImporter.IMPORT_STEP_FINISHED);
    SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj;
    assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);
    assertEquals(
        1,
        cache
            .getWaypoints()
            .size()); // this is the original pocket query result without test waypoint
  }
  public void testImportGpxAttachment() {
    Uri uri = Uri.parse("android.resource://cgeo.geocaching.test/raw/gc31j2h");

    GPXImporter.ImportGpxAttachmentThread importThread =
        new GPXImporter.ImportGpxAttachmentThread(
            uri,
            getInstrumentation().getContext().getContentResolver(),
            listId,
            importStepHandler,
            progressHandler);
    runImportThread(importThread);

    assertImportStepMessages(
        GPXImporter.IMPORT_STEP_START,
        GPXImporter.IMPORT_STEP_READ_FILE,
        GPXImporter.IMPORT_STEP_STORE_CACHES,
        GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS,
        GPXImporter.IMPORT_STEP_FINISHED);
    SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj;
    assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);

    // can't assert, for whatever reason the waypoints are remembered in DB
    //        assertNull(cache.waypoints);
  }
  /** Test {@link cgBase#searchByGeocode(String, String, int, boolean, CancellableHandler)} */
  @MediumTest
  public static void testSearchByGeocodeNotLoggedIn() {
    ImmutablePair<String, String> login = Settings.getLogin();

    try {
      // non premium cache
      MockedCache cache = new GC1ZXX2();

      deleteCacheFromDBAndLogout(cache.getGeocode());

      SearchResult search =
          cgBase.searchByGeocode(
              cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null);
      assertNotNull(search);
      assertEquals(1, search.getGeocodes().size());
      assertTrue(search.getGeocodes().contains(cache.getGeocode()));
      cgCache searchedCache = search.getFirstCacheFromResult(LoadFlags.LOADCACHEORDB);
      // coords must be null if the user is not logged in
      assertNull(searchedCache.getCoords());

      // premium cache. Not visible to guests
      cache = new GC2JVEH();

      deleteCacheFromDBAndLogout(cache.getGeocode());

      search =
          cgBase.searchByGeocode(
              cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null);
      assertNotNull(search);
      assertEquals(0, search.getGeocodes().size());

    } finally {
      // restore user and password
      Settings.setLogin(login.left, login.right);
      cgBase.login();
    }
  }
  public void testImportLoc() throws IOException {
    File oc5952 = new File(tempDir, "oc5952.loc");
    copyResourceToFile(R.raw.oc5952_loc, oc5952);

    GPXImporter.ImportLocFileThread importThread =
        new GPXImporter.ImportLocFileThread(oc5952, listId, importStepHandler, progressHandler);
    runImportThread(importThread);

    assertImportStepMessages(
        GPXImporter.IMPORT_STEP_START,
        GPXImporter.IMPORT_STEP_READ_FILE,
        GPXImporter.IMPORT_STEP_STORE_CACHES,
        GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS,
        GPXImporter.IMPORT_STEP_FINISHED);
    SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj;
    assertEquals(Collections.singletonList("OC5952"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("OC5952", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);
  }
  public void testImportGpxWithWaypoints() throws IOException {
    File gc31j2h = new File(tempDir, "gc31j2h.gpx");
    copyResourceToFile(R.raw.gc31j2h, gc31j2h);
    copyResourceToFile(R.raw.gc31j2h_wpts, new File(tempDir, "gc31j2h-wpts.gpx"));

    GPXImporter.ImportGpxFileThread importThread =
        new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler);
    runImportThread(importThread);

    assertImportStepMessages(
        GPXImporter.IMPORT_STEP_START,
        GPXImporter.IMPORT_STEP_READ_FILE,
        GPXImporter.IMPORT_STEP_READ_WPT_FILE,
        GPXImporter.IMPORT_STEP_STORE_CACHES,
        GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS,
        GPXImporter.IMPORT_STEP_FINISHED);
    SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj;
    assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);
    assertEquals(2, cache.getWaypoints().size());
  }
  public void testImportGpx() throws IOException {
    File gc31j2h = new File(tempDir, "gc31j2h.gpx");
    copyResourceToFile(R.raw.gc31j2h, gc31j2h);

    GPXImporter.ImportGpxFileThread importThread =
        new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler);
    runImportThread(importThread);

    assertEquals(5, importStepHandler.messages.size());
    Iterator<Message> iMsg = importStepHandler.messages.iterator();
    assertEquals(GPXImporter.IMPORT_STEP_START, iMsg.next().what);
    assertEquals(GPXImporter.IMPORT_STEP_READ_FILE, iMsg.next().what);
    assertEquals(GPXImporter.IMPORT_STEP_STORE_CACHES, iMsg.next().what);
    assertEquals(GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, iMsg.next().what);
    assertEquals(GPXImporter.IMPORT_STEP_FINISHED, iMsg.next().what);
    SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj;
    assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes()));

    cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB);
    assertCacheProperties(cache);

    // can't assert, for whatever reason the waypoints are remembered in DB
    //        assertNull(cache.waypoints);
  }
  /** Test {@link cgBase#searchByViewport(String, Viewport)} */
  @MediumTest
  public static void testSearchByViewportNotLoggedIn() {

    if (LIVEMAPENABLED) {
      ImmutablePair<String, String> login = Settings.getLogin();

      try {

        final String token = null; // without a valid token we are "logged off"

        // non premium cache
        MockedCache cache = new GC2CJPF();
        deleteCacheFromDBAndLogout(cache.getGeocode());

        Viewport viewport = new Viewport(cache.getCoords(), 0.003, 0.003);
        SearchResult search = cgBase.searchByViewport(token, viewport);

        assertNotNull(search);
        assertTrue(search.getGeocodes().contains(cache.getGeocode()));
        // coords differ
        Log.d(
            Settings.tag,
            "cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords expected = "
                + cache.getCoords());
        Log.d(
            Settings.tag,
            "cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords actual = "
                + cgeoapplication
                    .getInstance()
                    .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                    .getCoords());
        assertFalse(
            cache
                .getCoords()
                .isEqualTo(
                    cgeoapplication
                        .getInstance()
                        .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                        .getCoords(),
                    1e-3));
        assertFalse(
            cgeoapplication
                .getInstance()
                .loadCache(cache.getGeocode(), LoadFlags.LOADCACHEORDB)
                .isReliableLatLon());

        // premium cache
        cache = new GC2JVEH();
        deleteCacheFromDBAndLogout(cache.getGeocode());

        viewport = new Viewport(cache.getCoords(), 0.003, 0.003);
        search = cgBase.searchByViewport(token, viewport);

        assertNotNull(search);
        // It's a premium member cache only and thus not visible to guests
        assertFalse(search.getGeocodes().contains(cache.getGeocode()));

      } finally {
        // restore user and password
        Settings.setLogin(login.left, login.right);
        cgBase.login();
      }
    }
  }
Esempio n. 14
0
  /**
   * Searches the view port on the live map for caches. The strategy dictates if only live map
   * information is used or if an additional searchByCoordinates query is issued.
   *
   * @param viewport Area to search
   * @param tokens Live map tokens
   * @param strategy Strategy for data retrieval and parsing, @see Strategy
   */
  @NonNull
  private static SearchResult searchByViewport(
      final Viewport viewport, final MapTokens tokens, final LivemapStrategy strategy) {
    Log.d("GCMap.searchByViewport" + viewport.toString());

    final SearchResult searchResult = new SearchResult();

    if (Settings.isDebug()) {
      searchResult.setUrl(viewport.getCenter().format(Format.LAT_LON_DECMINUTE));
    }

    if (strategy.flags.contains(LivemapStrategy.Flag.LOAD_TILES)) {
      final Set<Tile> tiles = Tile.getTilesForViewport(viewport);

      if (Settings.isDebug()) {
        searchResult.setUrl(
            new StringBuilder()
                .append(tiles.iterator().next().getZoomLevel())
                .append(Formatter.SEPARATOR)
                .append(searchResult.getUrl())
                .toString());
      }

      for (final Tile tile : tiles) {
        if (!Tile.cache.contains(tile)) {
          final Parameters params =
              new Parameters(
                  "x", String.valueOf(tile.getX()),
                  "y", String.valueOf(tile.getY()),
                  "z", String.valueOf(tile.getZoomLevel()),
                  "ep", "1",
                  "app", "cgeo");
          if (tokens != null) {
            params.put("k", tokens.getUserSession(), "st", tokens.getSessionToken());
          }
          if (Settings.isExcludeMyCaches()) { // works only for PM
            params.put("hf", "1", "hh", "1"); // hide found, hide hidden
          }
          // ect: exclude cache type (probably), comma separated list
          if (Settings.getCacheType() != CacheType.ALL) {
            params.put("ect", getCacheTypeFilter(Settings.getCacheType()));
          }
          if (tile.getZoomLevel() != 14) {
            params.put("_", String.valueOf(System.currentTimeMillis()));
          }

          // The PNG must be requested first, otherwise the following request would always return
          // with 204 - No Content
          final Single<Bitmap> bitmapObs =
              Tile.requestMapTile(params).onErrorResumeNext(Single.<Bitmap>just(null));
          final Single<String> dataObs =
              Tile.requestMapInfo(GCConstants.URL_MAP_INFO, params, GCConstants.URL_LIVE_MAP)
                  .onErrorResumeNext(Single.just(""));
          try {
            Single.zip(
                    bitmapObs,
                    dataObs,
                    new Func2<Bitmap, String, Void>() {
                      @Override
                      public Void call(final Bitmap bitmap, final String data) {
                        final boolean validBitmap =
                            bitmap != null
                                && bitmap.getWidth() == Tile.TILE_SIZE
                                && bitmap.getHeight() == Tile.TILE_SIZE;

                        if (StringUtils.isEmpty(data)) {
                          Log.w(
                              "GCMap.searchByViewport: No data from server for tile ("
                                  + tile.getX()
                                  + "/"
                                  + tile.getY()
                                  + ")");
                        } else {
                          final SearchResult search =
                              parseMapJSON(data, tile, validBitmap ? bitmap : null, strategy);
                          if (CollectionUtils.isEmpty(search.getGeocodes())) {
                            Log.e(
                                "GCMap.searchByViewport: No cache parsed for viewport " + viewport);
                          } else {
                            synchronized (searchResult) {
                              searchResult.addSearchResult(search);
                            }
                          }
                          synchronized (Tile.cache) {
                            Tile.cache.add(tile);
                          }
                        }

                        // release native bitmap memory
                        if (bitmap != null) {
                          bitmap.recycle();
                        }

                        return null;
                      }
                    })
                .toBlocking()
                .value();
          } catch (final Exception e) {
            Log.e("GCMap.searchByViewPort: connection error");
          }
        }
      }

      // Check for vanished found caches
      if (tiles.iterator().next().getZoomLevel() >= Tile.ZOOMLEVEL_MIN_PERSONALIZED) {
        searchResult.addFilteredGeocodes(
            DataStore.getCachedMissingFromSearch(
                searchResult,
                tiles,
                GCConnector.getInstance(),
                Tile.ZOOMLEVEL_MIN_PERSONALIZED - 1));
      }
    }

    if (strategy.flags.contains(Flag.SEARCH_NEARBY) && Settings.isGCPremiumMember()) {
      final Geopoint center = viewport.getCenter();
      if ((lastSearchViewport == null) || !lastSearchViewport.contains(center)) {
        // FIXME We don't have a RecaptchaReceiver!?
        final SearchResult search =
            GCParser.searchByCoords(center, Settings.getCacheType(), false, null);
        if (search != null && !search.isEmpty()) {
          final Set<String> geocodes = search.getGeocodes();
          lastSearchViewport = DataStore.getBounds(geocodes);
          searchResult.addGeocodes(geocodes);
        }
      }
    }

    return searchResult;
  }