mil.nga.geopackage.GeoPackageManager Java Examples

The following examples show how to use mil.nga.geopackage.GeoPackageManager. 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: TestSetupTeardown.java    From geopackage-android-map with MIT License 6 votes vote down vote up
/**
 * Set up the import database
 * 
 * @param activity
 * @param testContext
 * @return
 */
public static GeoPackage setUpImport(Activity activity, Context testContext) {

	GeoPackageManager manager = GeoPackageFactory.getManager(activity);

	// Delete
	manager.delete(TestConstants.IMPORT_DB_NAME);

	// Copy the test db file from assets to the internal storage
	TestUtils.copyAssetFileToInternalStorage(activity, testContext,
			TestConstants.IMPORT_DB_FILE_NAME);

	// Import
	String importLocation = TestUtils.getAssetFileInternalStorageLocation(
			activity, TestConstants.IMPORT_DB_FILE_NAME);
	manager.importGeoPackage(new File(importLocation));

	// Open
	GeoPackage geoPackage = manager.open(TestConstants.IMPORT_DB_NAME);
	if (geoPackage == null) {
		throw new GeoPackageException("Failed to open database");
	}

	return geoPackage;
}
 
Example #2
Source File: PropertiesManagerTest.java    From geopackage-android with MIT License 6 votes vote down vote up
/**
 * Test properties extension with cache of GeoPackages
 *
 * @throws Exception upon error
 */
@Test
public void testPropertiesManagerWithCache() throws Exception {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    GeoPackageCache cache = new GeoPackageCache(manager);

    List<String> geoPackages = createGeoPackageNames();

    for (String name : geoPackages) {
        cache.getOrOpen(name);
    }

    PropertiesManager propertiesManager = new PropertiesManager(cache);
    testPropertiesManager(propertiesManager);
}
 
Example #3
Source File: LoadGeoPackageTestCase.java    From geopackage-android with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws IOException
 * @throws SQLException
 */
@Override
protected GeoPackage getGeoPackage() throws Exception {
    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Delete
    manager.delete(name);

    // Copy the test db file from assets to the internal storage
    TestUtils.copyAssetFileToInternalStorage(activity, testContext,
            file);

    // Import
    String importLocation = TestUtils.getAssetFileInternalStorageLocation(
            activity, file);
    manager.importGeoPackage(new File(importLocation));

    // Open
    GeoPackage geoPackage = manager.open(name);
    if (geoPackage == null) {
        throw new GeoPackageException("Failed to open database");
    }

    return geoPackage;
}
 
Example #4
Source File: ImportCoverageDataGeoPackageTestCase.java    From geopackage-android with MIT License 6 votes vote down vote up
@Override
protected GeoPackage getGeoPackage() throws Exception {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Delete
    manager.delete(TestConstants.IMPORT_COVERAGE_DATA_DB_NAME);

    // Copy the test db file from assets to the internal storage
    TestUtils.copyAssetFileToInternalStorage(activity, testContext,
            TestConstants.IMPORT_COVERAGE_DATA_DB_FILE_NAME);

    // Import
    String importLocation = TestUtils.getAssetFileInternalStorageLocation(
            activity, TestConstants.IMPORT_COVERAGE_DATA_DB_FILE_NAME);
    manager.importGeoPackage(new File(importLocation));

    // Open
    GeoPackage geoPackage = manager.open(TestConstants.IMPORT_COVERAGE_DATA_DB_NAME);
    if (geoPackage == null) {
        throw new GeoPackageException("Failed to open database");
    }

    return geoPackage;
}
 
Example #5
Source File: GeoPackageExample.java    From geopackage-android with MIT License 6 votes vote down vote up
private static void exportGeoPackage(Context context) throws IOException {

        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

            GeoPackageManager manager = GeoPackageFactory.getManager(context);

            String name = GeoPackageValidate.addGeoPackageExtension(GEOPACKAGE_NAME + "-" + System.currentTimeMillis());
            manager.exportGeoPackage(GEOPACKAGE_NAME,
                    name,
                    Environment.DIRECTORY_DOCUMENTS,
                    MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL));

            String path = "/storage/emulated/0/Documents/" + name;
            Log.i(LOG_NAME, "Created: " + path);
            Log.i(LOG_NAME, "To copy GeoPackage, run: "
                    + "adb pull " + path + " " + GeoPackageValidate.addGeoPackageExtension(GEOPACKAGE_NAME));
        } else {
            Log.w(LOG_NAME,
                    "To export the GeoPackage, grant GeoPackageSDKTests Storage permission on the emulator or phone");
        }

    }
 
Example #6
Source File: TestSetupTeardown.java    From geopackage-android with MIT License 6 votes vote down vote up
/**
 * Set up the import database
 *
 * @param activity
 * @param testContext
 * @return
 */
public static GeoPackage setUpImport(Activity activity, Context testContext) {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Delete
    manager.delete(TestConstants.IMPORT_DB_NAME);

    // Copy the test db file from assets to the internal storage
    TestUtils.copyAssetFileToInternalStorage(activity, testContext,
            TestConstants.IMPORT_DB_FILE_NAME);

    // Import
    String importLocation = TestUtils.getAssetFileInternalStorageLocation(
            activity, TestConstants.IMPORT_DB_FILE_NAME);
    manager.importGeoPackage(new File(importLocation));

    // Open
    GeoPackage geoPackage = manager.open(TestConstants.IMPORT_DB_NAME);
    if (geoPackage == null) {
        throw new GeoPackageException("Failed to open database");
    }

    return geoPackage;
}
 
Example #7
Source File: ImportCoverageDataTiffGeoPackageTestCase.java    From geopackage-android with MIT License 6 votes vote down vote up
@Override
protected GeoPackage getGeoPackage() throws Exception {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Delete
    manager.delete(TestConstants.IMPORT_COVERAGE_DATA_TIFF_DB_NAME);

    // Copy the test db file from assets to the internal storage
    TestUtils.copyAssetFileToInternalStorage(activity, testContext,
            TestConstants.IMPORT_COVERAGE_DATA_TIFF_DB_FILE_NAME);

    // Import
    String importLocation = TestUtils.getAssetFileInternalStorageLocation(
            activity, TestConstants.IMPORT_COVERAGE_DATA_TIFF_DB_FILE_NAME);
    manager.importGeoPackage(new File(importLocation));

    // Open
    GeoPackage geoPackage = manager.open(TestConstants.IMPORT_COVERAGE_DATA_TIFF_DB_NAME);
    if (geoPackage == null) {
        throw new GeoPackageException("Failed to open database");
    }

    return geoPackage;
}
 
Example #8
Source File: GeoPackageManagerTest.java    From geopackage-android with MIT License 6 votes vote down vote up
/**
 * Create the externally linked GeoPackage
 *
 * @param manager
 * @param externalDirectory
 * @param createFile
 * @param testCase
 */
private void createExternal(GeoPackageManager manager, File externalDirectory, File createFile, int testCase) {
    boolean created = false;
    switch (testCase) {
        case 0:
            created = manager.createFile(createFile);
            break;
        case 1:
            created = manager.createFile(TestConstants.IMPORT_DB_NAME, createFile);
            break;
        case 2:
            created = manager.createAtPath(TestConstants.IMPORT_DB_NAME, externalDirectory);
            break;
        default:
            fail("Unsupported test case");
    }
    assertTrue("Database not created",
            created);
}
 
Example #9
Source File: TestSetupTeardown.java    From geopackage-android-map with MIT License 5 votes vote down vote up
/**
 * Tear down the create database
 * 
 * @param activity
 * @param geoPackage
 */
public static void tearDownCreate(Activity activity, GeoPackage geoPackage) {

	// Close
	if (geoPackage != null) {
		geoPackage.close();
	}

	// Delete
	GeoPackageManager manager = GeoPackageFactory.getManager(activity);
	manager.delete(TestConstants.TEST_DB_NAME);
}
 
Example #10
Source File: IndexerTask.java    From geopackage-mapcache-android with MIT License 5 votes vote down vote up
/**
 * Index features
 *
 * @param activity
 * @param callback
 * @param database
 * @param tableName
 * @param indexLocation
 */
public static void indexFeatures(Activity activity, IIndexerTask callback,
                                 String database, String tableName,
                                 FeatureIndexType indexLocation) {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    GeoPackage geoPackage = manager.open(database);

    FeatureDao featureDao = geoPackage.getFeatureDao(tableName);

    FeatureIndexManager indexer = new FeatureIndexManager(activity, geoPackage, featureDao);
    indexer.setIndexLocation(indexLocation);

    ProgressDialog progressDialog = new ProgressDialog(activity);
    final IndexerTask indexTask = new IndexerTask(activity,
            callback, progressDialog, geoPackage, indexer);

    int max = featureDao.count();
    indexTask.setMax(max);
    indexer.setProgress(indexTask);

    progressDialog.setMessage(activity
            .getString(R.string.geopackage_table_index_features_index_title)
            + ": "
            + geoPackage.getName() + " - " + tableName);
    progressDialog.setCancelable(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setIndeterminate(false);
    progressDialog.setMax(max);
    progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE,
            activity.getString(R.string.button_cancel_label),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    indexTask.cancel(true);
                }
            });

    indexTask.execute();
}
 
Example #11
Source File: GeoPackageCacheUtils.java    From mage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Get a cache name for the cache file
 *
 * @param manager
 * @param cacheFile
 * @return cache name
 */
public static String getCacheName(GeoPackageManager manager, File cacheFile) {

    // Get the cache name
    String cacheName = MediaUtility.getFileNameWithoutExtension(cacheFile);

    // Adjust the name until it is unique
    final String baseCacheName = cacheName;
    int nameCount = 0;
    while (manager.exists(cacheName)) {
        cacheName = baseCacheName + "_" + (++nameCount);
    }

    return cacheName;
}
 
Example #12
Source File: GeoPackageCacheUtils.java    From mage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Import the GeoPackage file as an external link if it does not exist
 *
 * @param manager
 * @param cacheFile
 * @return cache name when imported, null when not imported
 */
public static String importGeoPackage(GeoPackageManager manager, File cacheFile) {

    String importedCacheName = null;

    if (!manager.existsAtExternalFile(cacheFile)) {

        // Get the cache name
        String cacheName = getCacheName(manager, cacheFile);

        // Import the GeoPackage as a linked file
        try{
            if (manager.importGeoPackageAsExternalLink(cacheFile, cacheName)) {
                importedCacheName = cacheName;
            }
        }catch(Exception e){
            Log.e(GeoPackageCacheUtils.class.getSimpleName(), "Failed to import file as GeoPackage. path: " + cacheFile.getAbsolutePath() + ", name: " + cacheName + ", error: " +e.getMessage());

            // Delete the cache file
            if(cacheFile.canWrite()){
                try {
                    cacheFile.delete();
                }catch(Exception error){
                    Log.e(GeoPackageCacheUtils.class.getSimpleName(), "Failed to delete file: " + cacheFile.getAbsolutePath() + ", error: " + error.getMessage());
                }
            }

        }
    }

    return importedCacheName;
}
 
Example #13
Source File: TileOverlayPreferenceActivity.java    From mage-android with Apache License 2.0 5 votes vote down vote up
private void saveGeopackageLayers(Collection<Layer> remoteLayers) {
    Context context = getActivity().getApplicationContext();
    LayerHelper layerHelper = LayerHelper.getInstance(context);
    try {
        // get local layers
        Collection<Layer> localLayers = layerHelper.readAll("GeoPackage");

        Map<String, Layer> remoteIdToLayer = new HashMap<>(localLayers.size());
        for(Layer layer : localLayers){
            remoteIdToLayer.put(layer.getRemoteId(), layer);
        }

        GeoPackageManager manager = GeoPackageFactory.getManager(context);
        for (Layer remoteLayer : remoteLayers) {
            // Check if its loaded
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                    String.format("MAGE/geopackages/%s/%s", remoteLayer.getRemoteId(), remoteLayer.getFileName()));
            if (file.exists() && manager.existsAtExternalFile(file)) {
                remoteLayer.setLoaded(true);
            }
            if(!localLayers.contains(remoteLayer)) {
                layerHelper.create(remoteLayer);
            }else {
                Layer localLayer = remoteIdToLayer.get(remoteLayer.getRemoteId());
                //Only remove a local layer if the even has changed
                if (!remoteLayer.getEvent().equals(localLayer.getEvent())) {
                    layerHelper.delete(localLayer.getId());
                    layerHelper.create(remoteLayer);
                }
            }
        }
    } catch (LayerException e) {
        Log.e(LOG_NAME, "Error saving geopackage layers", e);
    }
}
 
Example #14
Source File: CacheProvider.java    From mage-android with Apache License 2.0 5 votes vote down vote up
/**
 * Get GeoPackage Cache Overlay for the database file
 *
 * @param context
 * @param cache
 * @param geoPackageManager
 * @return cache overlay
 */
public GeoPackageCacheOverlay getGeoPackageCacheOverlay(Context context, File cache, GeoPackageManager geoPackageManager) {

    GeoPackageCacheOverlay cacheOverlay = null;

    // Import the GeoPackage if needed
    String cacheName = GeoPackageCacheUtils.importGeoPackage(geoPackageManager, cache);
    if(cacheName != null){
        // Get the GeoPackage overlay
        cacheOverlay = getGeoPackageCacheOverlay(context, geoPackageManager, cacheName);
    }

    return cacheOverlay;
}
 
Example #15
Source File: GeoPackageDownloadManager.java    From mage-android with Apache License 2.0 5 votes vote down vote up
private void loadGeopackage(long downloadId, GeoPackageDownloadListener listener) {
    synchronized (downloadLock) {
        try {
            Layer layer = layerHelper.getByDownloadId(downloadId);

            if (layer != null) {
                String relativePath = getRelativePath(layer);
                GeoPackageManager geoPackageManager = GeoPackageFactory.getManager(context);
                CacheProvider cacheProvider = CacheProvider.getInstance(context);
                File cache = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), relativePath);
                CacheOverlay overlay = cacheProvider.getGeoPackageCacheOverlay(context, cache, geoPackageManager);
                if (overlay != null) {
                    cacheProvider.addCacheOverlay(overlay);
                }

                layer.setRelativePath(relativePath);
                layer.setLoaded(true);
                layerHelper.update(layer);

                if (listener != null) {
                    listener.onGeoPackageDownloaded(layer, overlay);
                }
            }
        } catch (LayerException e) {
            Log.e(LOG_NAME, "Error saving layer", e);
        }
    }
}
 
Example #16
Source File: GeoPackageExample.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * Test making the GeoPackage example
 *
 * @throws SQLException upon error
 * @throws IOException  upon error
 */
@Test
public void testExample() throws SQLException, IOException, NameNotFoundException {

    create();

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    GeoPackage geoPackage = manager.open(GEOPACKAGE_NAME);
    TestCase.assertNotNull(geoPackage);
    geoPackage.close();

    TestCase.assertTrue(manager.delete(GEOPACKAGE_NAME));
}
 
Example #17
Source File: GeoPackageManagerTest.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * Test creating and deleting a database
 */
@Test
public void testCreateOpenDelete() {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Verify does not exist
    assertFalse("Database already exists",
            manager.exists(TestConstants.TEST_DB_NAME));
    assertFalse("Database already returned in the set", manager
            .databaseSet().contains(TestConstants.TEST_DB_NAME));

    // Create
    assertTrue("Database failed to create",
            manager.create(TestConstants.TEST_DB_NAME));
    assertTrue("Database does not exist",
            manager.exists(TestConstants.TEST_DB_NAME));
    assertTrue("Database not returned in the set", manager.databaseSet()
            .contains(TestConstants.TEST_DB_NAME));

    // Open
    GeoPackage geoPackage = manager.open(TestConstants.TEST_DB_NAME);
    assertNotNull("Failed to open database", geoPackage);
    geoPackage.close();

    // Open with inverse validation
    manager.setOpenHeaderValidation(!manager.isOpenHeaderValidation());
    manager.setOpenIntegrityValidation(!manager.isOpenIntegrityValidation());
    geoPackage = manager.open(TestConstants.TEST_DB_NAME);
    assertNotNull("Failed to open database", geoPackage);
    geoPackage.close();

    // Delete
    assertTrue("Database not deleted",
            manager.delete(TestConstants.TEST_DB_NAME));
    assertFalse("Database exists after delete",
            manager.exists(TestConstants.TEST_DB_NAME));
    assertFalse("Database returned in the set after delete", manager
            .databaseSet().contains(TestConstants.TEST_DB_NAME));
}
 
Example #18
Source File: GeoPackageManagerTest.java    From geopackage-android with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    // Delete existing test databases
    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    manager.delete(TestConstants.TEST_DB_NAME);
    manager.delete(TestConstants.IMPORT_DB_NAME);
    manager.delete(IMPORT_CORRUPT_DB_NAME);
}
 
Example #19
Source File: TestSetupTeardown.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * Tear down the import database
 *
 * @param activity
 * @param geoPackage
 */
public static void tearDownImport(Activity activity, GeoPackage geoPackage) {

    // Close
    if (geoPackage != null) {
        geoPackage.close();
    }

    // Delete
    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    manager.delete(TestConstants.IMPORT_DB_NAME);
}
 
Example #20
Source File: TestSetupTeardown.java    From geopackage-android-map with MIT License 5 votes vote down vote up
/**
 * Tear down the import database
 * 
 * @param activity
 * @param geoPackage
 */
public static void tearDownImport(Activity activity, GeoPackage geoPackage) {

	// Close
	if (geoPackage != null) {
		geoPackage.close();
	}

	// Delete
	GeoPackageManager manager = GeoPackageFactory.getManager(activity);
	manager.delete(TestConstants.IMPORT_DB_NAME);
}
 
Example #21
Source File: TestSetupTeardown.java    From geopackage-android with MIT License 5 votes vote down vote up
/**
 * Tear down the create database
 *
 * @param activity
 * @param geoPackage
 */
public static void tearDownCreate(Activity activity, GeoPackage geoPackage) {

    // Close
    if (geoPackage != null) {
        geoPackage.close();
    }

    // Delete
    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    manager.delete(TestConstants.TEST_DB_NAME);
}
 
Example #22
Source File: LoadGeoPackageTestCase.java    From geopackage-android with MIT License 5 votes vote down vote up
@After
public void tearDown() throws Exception {

    // Close
    if (geoPackage != null) {
        geoPackage.close();
    }

    // Delete
    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    manager.delete(name);

}
 
Example #23
Source File: TestSetupTeardown.java    From geopackage-android-map with MIT License 4 votes vote down vote up
/**
 * Set up the create database
 * 
 * @param activity
 * @param testContext
 * @param features
 * @param allowEmptyFeatures
 * @param tiles
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static GeoPackage setUpCreate(Activity activity,
		Context testContext, boolean features, boolean allowEmptyFeatures, boolean tiles)
		throws SQLException, IOException {

	GeoPackageManager manager = GeoPackageFactory.getManager(activity);

	// Delete
	manager.delete(TestConstants.TEST_DB_NAME);

	// Create
	manager.create(TestConstants.TEST_DB_NAME);

	// Open
	GeoPackage geoPackage = manager.open(TestConstants.TEST_DB_NAME);
	if (geoPackage == null) {
		throw new GeoPackageException("Failed to open database");
	}

	TestCase.assertEquals("Application Id", geoPackage.getApplicationId(), GeoPackageConstants.APPLICATION_ID);
	TestCase.assertEquals("User Version", geoPackage.getUserVersion(), GeoPackageConstants.USER_VERSION);
	String userVersionString = String.valueOf(geoPackage.getUserVersion());
	String majorVersion = userVersionString.substring(0, userVersionString.length() - 4);
	String minorVersion = userVersionString.substring(userVersionString.length() - 4, userVersionString.length() - 2);
	String patchVersion = userVersionString.substring(userVersionString.length() - 2);
	TestCase.assertEquals("Major User Version", geoPackage.getUserVersionMajor(), Integer.valueOf(majorVersion).intValue());
	TestCase.assertEquals("Minor User Version", geoPackage.getUserVersionMinor(), Integer.valueOf(minorVersion).intValue());
	TestCase.assertEquals("Patch User Version", geoPackage.getUserVersionPatch(), Integer.valueOf(patchVersion).intValue());

	if (features) {
		setUpCreateFeatures(geoPackage, allowEmptyFeatures);
	}

	if (tiles) {
		setUpCreateTiles(testContext, geoPackage);
	}

	setUpCreateCommon(geoPackage);

	return geoPackage;
}
 
Example #24
Source File: GeoPackageManagerTest.java    From geopackage-android with MIT License 4 votes vote down vote up
/**
 * Test creating a database GeoPackage file as an external link
 */
private void createExternal(int testCase) {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Verify does not exist
    assertFalse("Database already exists",
            manager.exists(TestConstants.IMPORT_DB_NAME));
    assertFalse("Database already returned in the set", manager
            .databaseSet().contains(TestConstants.IMPORT_DB_NAME));

    // Create
    File externalDirectory = activity.getExternalCacheDir();
    File createFile = new File(externalDirectory, TestConstants.IMPORT_DB_FILE_NAME);
    createFile.delete();
    createExternal(manager, externalDirectory, createFile, testCase);
    assertTrue("Database does not exist",
            manager.exists(TestConstants.IMPORT_DB_NAME));
    assertTrue("Database not returned in the set", manager.databaseSet()
            .contains(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validate(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validateHeader(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validateIntegrity(TestConstants.IMPORT_DB_NAME));

    // Open
    GeoPackage geoPackage = manager.open(TestConstants.IMPORT_DB_NAME);
    assertNotNull("Failed to open database", geoPackage);
    geoPackage.close();

    // Attempt to create again
    try {
        createExternal(manager, externalDirectory, createFile, testCase);
        fail("Creating database again did not cause exception");
    } catch (GeoPackageException e) {
        // expected
    }

    // Delete
    assertTrue("Database not deleted",
            manager.delete(TestConstants.IMPORT_DB_NAME));
    assertFalse("Database exists after delete",
            manager.exists(TestConstants.IMPORT_DB_NAME));
    assertFalse("Database returned in the set after delete", manager
            .databaseSet().contains(TestConstants.IMPORT_DB_NAME));
    assertTrue("Create file could not be deleted", createFile.delete());

    // Import and Open with inverse validation
    manager.setImportHeaderValidation(!manager.isImportHeaderValidation());
    manager.setImportIntegrityValidation(!manager.isImportIntegrityValidation());
    manager.setOpenHeaderValidation(!manager.isOpenHeaderValidation());
    manager.setOpenIntegrityValidation(!manager.isOpenIntegrityValidation());

    // Create
    createExternal(manager, externalDirectory, createFile, testCase);
    assertTrue("Database does not exist",
            manager.exists(TestConstants.IMPORT_DB_NAME));
    assertTrue("Database not returned in the set", manager.databaseSet()
            .contains(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validate(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validateHeader(TestConstants.IMPORT_DB_NAME));
    assertTrue(manager.validateIntegrity(TestConstants.IMPORT_DB_NAME));

    // Open
    geoPackage = manager.open(TestConstants.IMPORT_DB_NAME);
    assertNotNull("Failed to open database", geoPackage);
    geoPackage.close();

    // Delete
    assertTrue("Database not deleted",
            manager.delete(TestConstants.IMPORT_DB_NAME));
    assertFalse("Database exists after delete",
            manager.exists(TestConstants.IMPORT_DB_NAME));
    assertFalse("Database returned in the set after delete", manager
            .databaseSet().contains(TestConstants.IMPORT_DB_NAME));

    // Delete the file
    assertTrue("Create file could not be deleted", createFile.delete());

}
 
Example #25
Source File: LoadTilesTask.java    From geopackage-mapcache-android with MIT License 4 votes vote down vote up
/**
 * Load tiles from a URL
 *
 * @param activity
 * @param callback
 * @param active
 * @param database
 * @param tableName
 * @param tileUrl
 * @param minZoom
 * @param maxZoom
 * @param compressFormat
 * @param compressQuality
 * @param googleTiles
 * @param boundingBox
 * @param scaling
 * @param authority
 * @param code
 */
public static void loadTiles(Activity activity, ILoadTilesTask callback,
                             GeoPackageDatabases active, String database, String tableName,
                             String tileUrl, int minZoom, int maxZoom,
                             CompressFormat compressFormat, Integer compressQuality,
                             boolean googleTiles, BoundingBox boundingBox, TileScaling scaling, String authority, String code) {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    GeoPackage geoPackage = manager.open(database);

    Projection projection = ProjectionFactory.getProjection(authority, code);
    BoundingBox bbox = transform(boundingBox, projection);

    TileGenerator tileGenerator = new UrlTileGenerator(activity, geoPackage,
            tableName, tileUrl, minZoom, maxZoom, bbox, projection);
    setTileGenerator(activity, tileGenerator, minZoom, maxZoom, compressFormat, compressQuality, googleTiles, boundingBox, scaling);

    loadTiles(activity, callback, active, geoPackage, tableName, tileGenerator);
}
 
Example #26
Source File: TileOverlayPreferenceActivity.java    From mage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Delete the GeoPackage cache overlay
 * @param geoPackageCacheOverlay
 */
private void deleteGeoPackageCacheOverlay(GeoPackageCacheOverlay geoPackageCacheOverlay) {

    String database = geoPackageCacheOverlay.getName();

    // Get the GeoPackage file
    GeoPackageManager manager = GeoPackageFactory.getManager(getActivity());
    File path = manager.getFile(database);

    // Delete the cache from the GeoPackage manager
    manager.delete(database);

    // Attempt to delete the cache file if it is in the cache directory
    File pathDirectory = path.getParentFile();
    if(path.canWrite() && pathDirectory != null) {
        Map<StorageUtility.StorageType, File> storageLocations = StorageUtility.getWritableStorageLocations();
        for (File storageLocation : storageLocations.values()) {
            File root = new File(storageLocation, getString(R.string.overlay_cache_directory));
            if (root.equals(pathDirectory)) {
                path.delete();
                break;
            }
        }
    }

    // Check internal/external application storage
    File applicationCacheDirectory = CacheUtils.getApplicationCacheDirectory(getActivity());
    if (applicationCacheDirectory != null && applicationCacheDirectory.exists()) {
        for (File cache : applicationCacheDirectory.listFiles()) {
            if (cache.equals(path)) {
                path.delete();
                break;
            }
        }
    }

    if (path.getAbsolutePath().startsWith(String.format("%s/MAGE/geopackages", getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)))) {
        LayerHelper layerHelper = LayerHelper.getInstance(getActivity().getApplicationContext());

        try {
            String relativePath = path.getAbsolutePath().split(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/")[1];
            Layer layer = layerHelper.getByRelativePath(relativePath);
            if (layer != null) {
                layer.setLoaded(false);
                layer.setDownloadId(null);
                layerHelper.update(layer);
            }
        } catch (LayerException e) {
            Log.e(LOG_NAME, "Error setting loaded to false for path " + path, e);
        }

        if (!path.delete()) {
            Log.e(LOG_NAME, "Error deleting geopackage file from filesystem for path " + path);
        }
    }
}
 
Example #27
Source File: CacheProvider.java    From mage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Add GeoPackage Cache Overlay for the existing databases
 *
 * @param context
 * @param overlays
 * @param geoPackageManager
 */
private void addGeoPackageCacheOverlays(Context context, List<CacheOverlay> overlays, GeoPackageManager geoPackageManager) {

    // Delete any GeoPackages where the file is no longer accessible
    geoPackageManager.deleteAllMissingExternal();

    final Map<String, String> nonSideloadedGeopackages = new HashMap<>();
    try {
        LayerHelper layerHelper = LayerHelper.getInstance(context);
        List<Layer> layers = layerHelper.readAll("GeoPackage");
        for (Layer layer : layers) {
            if (!layer.isLoaded()) {
                continue;
            }

            String relativePath = layer.getRelativePath();
            if (relativePath != null) {
                File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), relativePath);
                nonSideloadedGeopackages.put(file.getName(), file.getName());
                if (!file.exists()) {
                    layer.setLoaded(true);
                    layerHelper.update(layer);
                }
            }
        }
    } catch (LayerException e) {
        Log.i(LOG_NAME, "Error reconciling downloaded layers", e);
    }

    // Add each existing database as a cache
    List<String> externalDatabases = geoPackageManager.externalDatabases();
    for (String database : externalDatabases) {
        GeoPackageCacheOverlay cacheOverlay = getGeoPackageCacheOverlay(context, geoPackageManager, database);
        if (cacheOverlay != null) {
            File f = new File(cacheOverlay.getFilePath());
            //TODO what happens if there are 2 geopackages with the same name
            if(!nonSideloadedGeopackages.containsKey(f.getName())){
                cacheOverlay.setSideloaded(true);
            }
            overlays.add(cacheOverlay);
        }
    }
}
 
Example #28
Source File: TestSetupTeardown.java    From geopackage-android with MIT License 4 votes vote down vote up
/**
 * Set up the create database
 *
 * @param activity
 * @param testContext
 * @param features
 * @param allowEmptyFeatures
 * @param tiles
 * @return
 * @throws SQLException
 * @throws IOException
 * @parma name
 */
public static GeoPackage setUpCreate(Activity activity,
                                     Context testContext, String name, boolean features, boolean allowEmptyFeatures, boolean tiles)
        throws SQLException, IOException {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);

    // Delete
    manager.delete(name);

    // Create
    manager.create(name);

    // Open
    GeoPackage geoPackage = manager.open(name);
    if (geoPackage == null) {
        throw new GeoPackageException("Failed to open database");
    }

    TestCase.assertEquals("Application Id", geoPackage.getApplicationId(), GeoPackageConstants.APPLICATION_ID);
    TestCase.assertEquals("User Version", geoPackage.getUserVersion(), GeoPackageConstants.USER_VERSION);
    String userVersionString = String.valueOf(geoPackage.getUserVersion());
    String majorVersion = userVersionString.substring(0, userVersionString.length() - 4);
    String minorVersion = userVersionString.substring(userVersionString.length() - 4, userVersionString.length() - 2);
    String patchVersion = userVersionString.substring(userVersionString.length() - 2);
    TestCase.assertEquals("Major User Version", geoPackage.getUserVersionMajor(), Integer.valueOf(majorVersion).intValue());
    TestCase.assertEquals("Minor User Version", geoPackage.getUserVersionMinor(), Integer.valueOf(minorVersion).intValue());
    TestCase.assertEquals("Patch User Version", geoPackage.getUserVersionPatch(), Integer.valueOf(patchVersion).intValue());

    if (features) {
        setUpCreateFeatures(geoPackage, allowEmptyFeatures);
    }

    if (tiles) {
        setUpCreateTiles(testContext, geoPackage);
    }

    setUpCreateCommon(geoPackage);

    return geoPackage;
}
 
Example #29
Source File: MapFragment.java    From mage-android with Apache License 2.0 4 votes vote down vote up
@Override
public View onCreateView(@NonNull LayoutInflater  inflater, ViewGroup container, Bundle savedInstanceState) {
	View view = inflater.inflate(R.layout.fragment_map, container, false);

	setHasOptionsMenu(true);

	staticGeometryCollection = new StaticGeometryCollection();

	availableLayerDownloadsIcon = view.findViewById(R.id.available_layer_downloads);
	zoomToLocationButton = view.findViewById(R.id.zoom_button);

	compassButton = view.findViewById(R.id.compass_button);
	compassButton.setOnClickListener(v -> resetMapBearing());

	searchButton = view.findViewById(R.id.map_search_button);
	if (Geocoder.isPresent()) {
		searchButton.setOnClickListener(v -> search());
	} else {
		searchButton.hide();
	}

	view.findViewById(R.id.new_observation_button).setOnClickListener(v -> onNewObservation());

	searchLayout = view.findViewById(R.id.search_layout);
	searchView = view.findViewById(R.id.search_view);
	searchView.setIconifiedByDefault(false);
	searchView.setIconified(false);
	searchView.clearFocus();

	MapsInitializer.initialize(context);

	ImageButton mapSettings = view.findViewById(R.id.map_settings);
	mapSettings.setOnClickListener(this);

	mapView = view.findViewById(R.id.mapView);
	Bundle mapState = (savedInstanceState != null) ? savedInstanceState.getBundle(MAP_VIEW_STATE): null;
	mapView.onCreate(mapState);

	mgrsBottomSheet = view.findViewById(R.id.mgrs_bottom_sheet);
	mgrsBottomSheetBehavior = BottomSheetBehavior.from(mgrsBottomSheet);
	mgrsCursor = view.findViewById(R.id.mgrs_grid_cursor);
	mgrsTextView = mgrsBottomSheet.findViewById(R.id.mgrs_code);
	mgrsGzdTextView = mgrsBottomSheet.findViewById(R.id.mgrs_gzd_zone);
	mgrs100dKmTextView = mgrsBottomSheet.findViewById(R.id.mgrs_grid_zone);
	mgrsEastingTextView = mgrsBottomSheet.findViewById(R.id.mgrs_easting);
	mgrsNorthingTextView = mgrsBottomSheet.findViewById(R.id.mgrs_northing);

	// Initialize the GeoPackage cache with a GeoPackage manager
	GeoPackageManager geoPackageManager = GeoPackageFactory.getManager(getActivity().getApplicationContext());
	geoPackageCache = new GeoPackageCache(geoPackageManager);

	locationProvider = locationPolicy.getBestLocationProvider();

	return view;
}
 
Example #30
Source File: GeoPackageTestUtils.java    From geopackage-android with MIT License 4 votes vote down vote up
/**
 * Test the GeoPackage vacuum
 *
 * @param activity   activity
 * @param geoPackage GeoPackage
 */
public static void testVacuum(Activity activity, GeoPackage geoPackage) {

    GeoPackageManager manager = GeoPackageFactory.getManager(activity);
    long size = manager.size(geoPackage.getName());

    for (String table : geoPackage.getTables()) {

        geoPackage.deleteTable(table);

        geoPackage.vacuum();

        long newSize = manager.size(geoPackage.getName());
        TestCase.assertTrue(size > newSize);
        size = newSize;

    }

}