Java Code Examples for mil.nga.geopackage.GeoPackage

The following examples show how to use mil.nga.geopackage.GeoPackage. These examples are extracted from open source projects. 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 Project: geopackage-java   Source File: UrlTileGeneratorUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Test generating tiles with random bounds and zoomss
 * 
 * @param geoPackage
 * @throws SQLException
 * @throws IOException
 */
public static void testGenerateTilesRandom(GeoPackage geoPackage)
		throws SQLException, IOException {

	for (int i = 0; i < 10; i++) {

		int minZoom = (int) (Math.random() * 3.0);
		int maxZoom = minZoom + ((int) (Math.random() * 3.0));
		Point point1 = TestUtils.createPoint(false, false);
		Point point2 = TestUtils.createPoint(false, false);
		BoundingBox boundingBox = new BoundingBox(Math.min(point1.getX(),
				point2.getX()), Math.min(point1.getY(), point2.getY()),
				Math.max(point1.getX(), point2.getX()), Math.max(
						point1.getY(), point2.getY()));
		UrlTileGenerator tileGenerator = new UrlTileGenerator(geoPackage,
				TABLE_NAME + i, URL, minZoom, maxZoom, boundingBox,
				getProjection());

		testGenerateTiles(tileGenerator);
	}
}
 
Example 2
Source Project: geopackage-android-map   Source File: GeoPackageOverlayFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Create a composite overlay linking the feature overly with
 *
 * @param featureOverlay feature overlay
 * @param geoPackage     GeoPackage
 * @return linked bounded overlay
 */
public static BoundedOverlay getLinkedFeatureOverlay(FeatureOverlay featureOverlay, GeoPackage geoPackage) {

    BoundedOverlay overlay;

    // Get the linked tile daos
    FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage);
    List<TileDao> tileDaos = linker.getTileDaosForFeatureTable(featureOverlay.getFeatureTiles().getFeatureDao().getTableName());

    if (!tileDaos.isEmpty()) {
        // Create a composite overlay to search for existing tiles before drawing from features
        overlay = getCompositeOverlay(tileDaos, featureOverlay);
    } else {
        overlay = featureOverlay;
    }

    return overlay;
}
 
Example 3
Source Project: geopackage-android   Source File: PropertiesManagerTest.java    License: MIT License 6 votes vote down vote up
private void addProperties(GeoPackage geoPackage, int i) {

        PropertiesExtension properties = new PropertiesExtension(geoPackage);

        properties.addValue(PropertyNames.TITLE, GEOPACKAGE_NAME + (i + 1));
        properties.addValue(PropertyNames.IDENTIFIER, Integer.toString(i));
        properties.addValue(EVEN_PROPERTY, i % 2 == 0 ? Boolean.TRUE.toString()
                : Boolean.FALSE.toString());
        if (i % 2 == 1) {
            properties.addValue(ODD_PROPERTY, Boolean.TRUE.toString());
        }

        if (i % COLOR_RED_FREQUENCY == 0) {
            properties.addValue(PropertyNames.TAG, COLOR_RED);
        }
        if (i % COLOR_GREEN_FREQUENCY == 0) {
            properties.addValue(PropertyNames.TAG, COLOR_GREEN);
        }
        if (i % COLOR_BLUE_FREQUENCY == 0) {
            properties.addValue(PropertyNames.TAG, COLOR_BLUE);
        }

    }
 
Example 4
Source Project: geopackage-java   Source File: SQLExec.java    License: MIT License 6 votes vote down vote up
/**
 * Execute the SQL on the GeoPackage database
 * 
 * @param database
 *            open database
 * @param sql
 *            SQL statement
 * @param maxRows
 *            max rows
 * @return results
 * @throws SQLException
 *             upon SQL error
 */
public static SQLExecResult executeSQL(GeoPackage database, String sql,
		Integer maxRows) throws SQLException {

	// If no max number of results, use the default
	if (maxRows == null) {
		maxRows = DEFAULT_MAX_ROWS;
	}

	sql = sql.trim();

	RTreeIndexExtension rtree = new RTreeIndexExtension(database);
	if (rtree.has()) {
		rtree.createAllFunctions();
	}

	SQLExecResult result = SQLExecAlterTable.alterTable(database, sql);
	if (result == null) {
		result = executeQuery(database, sql, maxRows);
	}

	return result;
}
 
Example 5
Source Project: geopackage-mapcache-android   Source File: GeoPackageRepository.java    License: MIT License 6 votes vote down vote up
/**
 * Get table Contents object
 */
public Contents getTableContents(String gpName, String tableName) {
    GeoPackage geo = null;
    try{
        geo = manager.open(gpName);
        if(geo != null) {
            ContentsDao contentsDao = geo.getContentsDao();
            Contents contents = contentsDao.queryForId(tableName);
            return contents;
        }

    } catch (Exception e){

    } finally {
        if(geo !=  null){
            geo.close();
        }
    }
    return null;
}
 
Example 6
Source Project: geopackage-android   Source File: GeoPackageExample.java    License: MIT License 6 votes vote down vote up
private static void createRelatedTablesFeaturesExtension(
        GeoPackage geoPackage, String tableName1, String tableName2) {

    RelatedTablesExtension relatedTables = new RelatedTablesExtension(
            geoPackage);

    List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
            .createAdditionalUserColumns();

    UserMappingTable userMappingTable = UserMappingTable.create(tableName1
            + "_" + tableName2, additionalMappingColumns);
    ExtendedRelation relation = relatedTables.addFeaturesRelationship(
            tableName1, tableName2, userMappingTable);

    insertRelatedTablesFeaturesExtensionRows(geoPackage, relation);
}
 
Example 7
@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 Project: geopackage-java   Source File: GeoPackageTestUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Test create feature table with metadata and additional columns
 * 
 * @param geoPackage
 * @throws SQLException
 */
public static void testCreateFeatureTableWithMetadataAdditionalColumns(
		GeoPackage geoPackage) throws SQLException {

	GeometryColumns geometryColumns = new GeometryColumns();
	geometryColumns.setId(new TableColumnKey("feature_metadata", "geom"));
	geometryColumns.setGeometryType(GeometryType.POINT);
	geometryColumns.setZ((byte) 1);
	geometryColumns.setM((byte) 0);

	BoundingBox boundingBox = new BoundingBox(-90, -45, 90, 45);

	List<FeatureColumn> additionalColumns = getFeatureColumns();

	SpatialReferenceSystem srs = geoPackage.getSpatialReferenceSystemDao()
			.getOrCreateCode(ProjectionConstants.AUTHORITY_EPSG,
					ProjectionConstants.EPSG_WEB_MERCATOR);
	geometryColumns = geoPackage.createFeatureTableWithMetadata(
			geometryColumns, additionalColumns, boundingBox, srs.getId());

	validateFeatureTableWithMetadata(geoPackage, geometryColumns, null,
			additionalColumns);
}
 
Example 9
Source Project: geopackage-java   Source File: UrlTileGenerator.java    License: MIT License 6 votes vote down vote up
/**
 * Constructor
 * 
 * @param geoPackage
 *            GeoPackage
 * @param tableName
 *            table name
 * @param tileUrl
 *            tile url
 * @param minZoom
 *            min zoom
 * @param maxZoom
 *            max zoom
 * @param boundingBox
 *            tiles bounding box
 * @param projection
 *            tiles projection
 * @since 1.2.0
 */
public UrlTileGenerator(GeoPackage geoPackage, String tableName,
		String tileUrl, int minZoom, int maxZoom, BoundingBox boundingBox,
		Projection projection) {
	super(geoPackage, tableName, minZoom, maxZoom, boundingBox, projection);

	try {
		this.tileUrl = URLDecoder.decode(tileUrl, "UTF-8");
	} catch (UnsupportedEncodingException e) {
		throw new GeoPackageException(
				"Failed to decode tile url: " + tileUrl, e);
	}

	this.urlHasXYZ = hasXYZ(tileUrl);
	this.urlHasBoundingBox = hasBoundingBox(tileUrl);

	if (!this.urlHasXYZ && !this.urlHasBoundingBox) {
		throw new GeoPackageException(
				"URL does not contain x,y,z or bounding box variables: "
						+ tileUrl);
	}
}
 
Example 10
Source Project: geopackage-java   Source File: GeoPackageExample.java    License: MIT License 6 votes vote down vote up
private void validateNGAExtensions(GeoPackage geoPackage, boolean has)
		throws SQLException {

	ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();

	TestCase.assertEquals(has && GEOMETRY_INDEX,
			extensionsDao.isTableExists() && !extensionsDao
					.queryByExtension(FeatureTableIndex.EXTENSION_NAME)
					.isEmpty());
	TestCase.assertEquals(has && FEATURE_TILE_LINK,
			new FeatureTileTableLinker(geoPackage).has());
	TestCase.assertEquals(has && TILE_SCALING,
			extensionsDao.isTableExists() && !extensionsDao
					.queryByExtension(TileTableScaling.EXTENSION_NAME)
					.isEmpty());
	TestCase.assertEquals(has && PROPERTIES,
			new PropertiesExtension(geoPackage).has());
	TestCase.assertEquals(has && CONTENTS_ID,
			new ContentsIdExtension(geoPackage).has());
	TestCase.assertEquals(has && FEATURE_STYLE,
			new FeatureStyleExtension(geoPackage).has());

}
 
Example 11
Source Project: geopackage-android   Source File: TestSetupTeardown.java    License: 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 12
Source Project: geopackage-android   Source File: GeoPackageExample.java    License: MIT License 5 votes vote down vote up
private static void createTiles(Context context, GeoPackage geoPackage) throws IOException,
        SQLException {

    geoPackage.createTileMatrixSetTable();
    geoPackage.createTileMatrixTable();

    BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
            4824705.2253603265, -11666125.00499674, 4825928.217812888);
    createTiles(context, geoPackage, "bit_systems", bitsBoundingBox, 15, 17, "png");

    BoundingBox ngaBoundingBox = new BoundingBox(-8593967.964158937,
            4685284.085768163, -8592744.971706374, 4687730.070673289);
    createTiles(context, geoPackage, "nga", ngaBoundingBox, 15, 16, "png");

}
 
Example 13
Source Project: geopackage-java   Source File: CoverageData.java    License: MIT License 5 votes vote down vote up
/**
 * Get a Tiled Gridded Coverage Data
 * 
 * @param geoPackage
 *            GeoPackage
 * @param tileDao
 *            tile dao
 * @param width
 *            coverage data response width
 * @param height
 *            coverage data response height
 * @param requestProjection
 *            request projection
 * @return coverage data
 */
public static CoverageData<?> getCoverageData(GeoPackage geoPackage,
		TileDao tileDao, Integer width, Integer height,
		Projection requestProjection) {

	TileMatrixSet tileMatrixSet = tileDao.getTileMatrixSet();
	GriddedCoverageDao griddedCoverageDao = geoPackage
			.getGriddedCoverageDao();

	GriddedCoverage griddedCoverage = null;
	try {
		if (griddedCoverageDao.isTableExists()) {
			griddedCoverage = griddedCoverageDao.query(tileMatrixSet);
		}
	} catch (SQLException e) {
		throw new GeoPackageException(
				"Failed to get Gridded Coverage for table name: "
						+ tileMatrixSet.getTableName(), e);
	}

	CoverageData<?> coverageData = null;

	GriddedCoverageDataType dataType = griddedCoverage.getDataType();
	switch (dataType) {
	case INTEGER:
		coverageData = new CoverageDataPng(geoPackage, tileDao, width,
				height, requestProjection);
		break;
	case FLOAT:
		coverageData = new CoverageDataTiff(geoPackage, tileDao, width,
				height, requestProjection);
		break;
	default:
		throw new GeoPackageException(
				"Unsupported Gridded Coverage Data Type: " + dataType);
	}

	return coverageData;
}
 
Example 14
Source Project: geopackage-java   Source File: TestSetupTeardown.java    License: MIT License 5 votes vote down vote up
/**
 * Tear down the create database
 * 
 * @param geoPackage
 */
public static void tearDownCreate(GeoPackage geoPackage) {

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

}
 
Example 15
Source Project: geopackage-android   Source File: GeoPackageExample.java    License: MIT License 5 votes vote down vote up
private void validateExtensions(GeoPackage geoPackage, boolean has)
        throws SQLException {

    ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();

    TestCase.assertEquals(has && RTREE_SPATIAL_INDEX,
            new RTreeIndexExtension(geoPackage).has());
    TestCase.assertEquals(
            has
                    && (RELATED_TABLES_FEATURES || RELATED_TABLES_MEDIA || RELATED_TABLES_SIMPLE_ATTRIBUTES),
            new RelatedTablesExtension(geoPackage).has());
    TestCase.assertEquals(
            has && COVERAGE_DATA,
            extensionsDao.isTableExists()
                    && !extensionsDao.queryByExtension(
                    CoverageData.EXTENSION_NAME).isEmpty());

    TestCase.assertEquals(has && SCHEMA,
            new SchemaExtension(geoPackage).has());
    TestCase.assertEquals(has && METADATA,
            new MetadataExtension(geoPackage).has());
    TestCase.assertEquals(
            has && NON_LINEAR_GEOMETRY_TYPES,
            extensionsDao.isTableExists()
                    && !extensionsDao
                    .queryByExtension(
                            GeometryExtensions
                                    .getExtensionName(GeometryType.CIRCULARSTRING))
                    .isEmpty());
    TestCase.assertEquals(has && WEBP, extensionsDao.isTableExists()
            && !extensionsDao
            .queryByExtension(WebPExtension.EXTENSION_NAME)
            .isEmpty());
    TestCase.assertEquals(has && CRS_WKT,
            new CrsWktExtension(geoPackage).has());

}
 
Example 16
Source Project: geopackage-java   Source File: FeatureIndexManagerUtils.java    License: MIT License 5 votes vote down vote up
private static void testTimedIndex(GeoPackage geoPackage,
		FeatureIndexType type, FeatureDao featureDao,
		List<FeatureIndexTestEnvelope> envelopes, double precision,
		boolean compareProjectionCounts, double projectionPrecision,
		boolean verbose) {
	testTimedIndex(geoPackage, type, featureDao, envelopes, precision,
			precision, compareProjectionCounts, projectionPrecision,
			verbose);
}
 
Example 17
Source Project: geopackage-java   Source File: CoverageData.java    License: MIT License 5 votes vote down vote up
/**
 * Create the coverage data tile table with metadata and extension
 * 
 * @param geoPackage
 *            GeoPackage
 * @param tableName
 *            table name
 * @param contentsBoundingBox
 *            contents bounding box
 * @param contentsSrsId
 *            contents srs id
 * @param tileMatrixSetBoundingBox
 *            tile matrix set bounding box
 * @param tileMatrixSetSrsId
 *            tile matrix set srs id
 * @param dataType
 *            gridded coverage data type
 * @return coverage data
 */
public static CoverageData<?> createTileTableWithMetadata(
		GeoPackage geoPackage, String tableName,
		BoundingBox contentsBoundingBox, long contentsSrsId,
		BoundingBox tileMatrixSetBoundingBox, long tileMatrixSetSrsId,
		GriddedCoverageDataType dataType) {

	TileMatrixSet tileMatrixSet = CoverageDataCore
			.createTileTableWithMetadata(geoPackage, tableName,
					contentsBoundingBox, contentsSrsId,
					tileMatrixSetBoundingBox, tileMatrixSetSrsId);
	TileDao tileDao = geoPackage.getTileDao(tileMatrixSet);

	CoverageData<?> coverageData = null;
	switch (dataType) {
	case INTEGER:
		coverageData = new CoverageDataPng(geoPackage, tileDao);
		break;
	case FLOAT:
		coverageData = new CoverageDataTiff(geoPackage, tileDao);
		break;
	default:
		throw new GeoPackageException(
				"Unsupported Gridded Coverage Data Type: " + dataType);
	}

	coverageData.getOrCreate();

	return coverageData;
}
 
Example 18
Source Project: osmdroid   Source File: GeopackageFeatureTilesOverlay.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getFeatureTable(String database) throws Exception {
    GeoPackage open = null;
    List<String> featureTables = new ArrayList<>();
    try {
        open = manager.open(database);
        featureTables = open.getFeatureTables();
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (open != null)
            open.close();
    }

    return featureTables;
}
 
Example 19
Source Project: geopackage-android   Source File: GeoPackageExample.java    License: MIT License 5 votes vote down vote up
private static void createFeatureTileLinkExtension(Context context, GeoPackage geoPackage)
        throws SQLException, IOException {

    List<String> featureTables = geoPackage.getFeatureTables();
    for (String featureTable : featureTables) {

        FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
        FeatureTiles featureTiles = new DefaultFeatureTiles(context, geoPackage, featureDao,
                context.getResources().getDisplayMetrics().density);

        BoundingBox boundingBox = featureDao.getBoundingBox();
        Projection projection = featureDao.getProjection();

        Projection requestProjection = ProjectionFactory
                .getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
        ProjectionTransform transform = projection
                .getTransformation(requestProjection);
        BoundingBox requestBoundingBox = boundingBox.transform(transform);

        int zoomLevel = TileBoundingBoxUtils
                .getZoomLevel(requestBoundingBox);
        zoomLevel = Math.max(zoomLevel, 8);
        zoomLevel = Math.min(zoomLevel, 19);

        int minZoom = zoomLevel - 8;
        int maxZoom = zoomLevel + 2;

        TileGenerator tileGenerator = new FeatureTileGenerator(context, geoPackage,
                featureTable + "_tiles", featureTiles, minZoom, maxZoom,
                requestBoundingBox, requestProjection);

        tileGenerator.generateTiles();
        featureTiles.close();
    }
}
 
Example 20
Source Project: geopackage-android   Source File: GeoPackageExample.java    License: MIT License 5 votes vote down vote up
private static void createPropertiesExtension(GeoPackage geoPackage) {

        PropertiesExtension properties = new PropertiesExtension(geoPackage);

        String dateTime = DateConverter.dateTimeConverter().stringValue(
                new Date());

        properties.addValue(PropertyNames.TITLE, "GeoPackage Android Example");
        properties.addValue(PropertyNames.VERSION, "3.2.0");
        properties.addValue(PropertyNames.CREATOR, "NGA");
        properties.addValue(PropertyNames.PUBLISHER, "NGA");
        properties.addValue(PropertyNames.CONTRIBUTOR, "Brian Osborn");
        properties.addValue(PropertyNames.CONTRIBUTOR, "Dan Barela");
        properties.addValue(PropertyNames.CREATED, dateTime);
        properties.addValue(PropertyNames.DATE, dateTime);
        properties.addValue(PropertyNames.MODIFIED, dateTime);
        properties
                .addValue(
                        PropertyNames.DESCRIPTION,
                        "GeoPackage example created by https://github.com/ngageoint/geopackage-android/blob/master/geopackage-sdk/src/androidTest/java/mil/nga/geopackage/test/GeoPackageExample.java");
        properties.addValue(PropertyNames.IDENTIFIER, "geopackage-android");
        properties.addValue(PropertyNames.LICENSE, "MIT");
        properties
                .addValue(
                        PropertyNames.SOURCE,
                        "http://github.com/ngageoint/GeoPackage/blob/master/docs/examples/android/example.gpkg");
        properties.addValue(PropertyNames.SUBJECT, "Examples");
        properties.addValue(PropertyNames.TYPE, "Examples");
        properties.addValue(PropertyNames.URI,
                "http://github.com/ngageoint/geopackage-android");
        properties.addValue(PropertyNames.TAG, "NGA");
        properties.addValue(PropertyNames.TAG, "Example");
        properties.addValue(PropertyNames.TAG, "BIT Systems");

    }
 
Example 21
Source Project: geopackage-java   Source File: ExtensionsUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Test create
 * 
 * @param geoPackage
 * @throws SQLException
 */
public static void testCreate(GeoPackage geoPackage) throws SQLException {

	ExtensionsDao dao = geoPackage.getExtensionsDao();

	if (dao.isTableExists()) {
		// Get current count
		long count = dao.countOf();

		// Create new extensions
		String tableName = "CREATE_TABLE_NAME";
		String columnName = "CREATE_COLUMN_NAME";
		String author = "nga";
		String extension = "create_extension";
		String definition = "definition";
		ExtensionScopeType scopeType = ExtensionScopeType.READ_WRITE;

		Extensions extensions = new Extensions();
		extensions.setTableName(tableName);
		extensions.setColumnName(columnName);
		extensions.setExtensionName(author, extension);
		extensions.setDefinition(definition);
		extensions.setScope(scopeType);
		dao.create(extensions);

		// Verify count
		long newCount = dao.countOf();
		TestCase.assertEquals(count + 1, newCount);

		// Verify saved extensions
		Extensions queryExtensions = dao.queryByExtension(
				extensions.getExtensionName(), extensions.getTableName(),
				extensions.getColumnName());
		TestCase.assertNotNull(queryExtensions);
		TestCase.assertEquals(tableName, queryExtensions.getTableName());
		TestCase.assertEquals(columnName, queryExtensions.getColumnName());
		TestCase.assertEquals(author + Extensions.EXTENSION_NAME_DIVIDER
				+ extension, queryExtensions.getExtensionName());
		TestCase.assertEquals(author, queryExtensions.getAuthor());
		TestCase.assertEquals(extension,
				queryExtensions.getExtensionNameNoAuthor());
		TestCase.assertEquals(definition, queryExtensions.getDefinition());
		TestCase.assertEquals(scopeType, queryExtensions.getScope());
	}

}
 
Example 22
Source Project: geopackage-android   Source File: SpatialReferenceSystemUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Test create
 * 
 * @param geoPackage
 * @throws SQLException
 */
public static void testCreate(GeoPackage geoPackage) throws SQLException {

	SpatialReferenceSystemDao dao = geoPackage
			.getSpatialReferenceSystemDao();

	// Get current count
	long count = dao.countOf();

	String srsName = "TEST_SRS_NAME";
	long srsId = 123456l;
	String organization = "TEST_ORG";
	int organizationCoordSysId = 123456;
	String definition = "TEST_DEFINITION";
	String description = "TEST_DESCRIPTION";

	// Create new srs
	SpatialReferenceSystem srs = new SpatialReferenceSystem();
	srs.setSrsName(srsName);
	srs.setSrsId(srsId);
	srs.setOrganization(organization);
	srs.setOrganizationCoordsysId(organizationCoordSysId);
	srs.setDefinition(definition);
	srs.setDescription(description);
	dao.create(srs);

	// Verify count
	long newCount = dao.countOf();
	TestCase.assertEquals(count + 1, newCount);

	// Verify saved srs
	SpatialReferenceSystem querySrs = dao.queryForId(srsId);
	TestCase.assertEquals(srsName, querySrs.getSrsName());
	TestCase.assertEquals(srsId, querySrs.getSrsId());
	TestCase.assertEquals(organization, querySrs.getOrganization());
	TestCase.assertEquals(organizationCoordSysId,
			querySrs.getOrganizationCoordsysId());
	TestCase.assertEquals(definition, querySrs.getDefinition());
	TestCase.assertEquals(description, querySrs.getDescription());

	// Test copied srs
	SpatialReferenceSystem copySrs = new SpatialReferenceSystem(querySrs);
	TestCase.assertEquals(querySrs.getSrsName(), copySrs.getSrsName());
	TestCase.assertEquals(querySrs.getId(), copySrs.getId());
	TestCase.assertEquals(querySrs.getOrganization(),
			copySrs.getOrganization());
	TestCase.assertEquals(querySrs.getOrganizationCoordsysId(),
			copySrs.getOrganizationCoordsysId());
	TestCase.assertEquals(querySrs.getDefinition(), copySrs.getDefinition());
	TestCase.assertEquals(querySrs.getDescription(),
			copySrs.getDescription());
	TestCase.assertEquals(querySrs.getDefinition_12_063(),
			copySrs.getDefinition_12_063());

	// Change pk
	long copySrsId = 654321l;
	copySrs.setSrsId(copySrsId);

	dao.create(copySrs);

	// Verify count
	long newCount2 = dao.countOf();
	TestCase.assertEquals(count + 2, newCount2);

	// Verify saved contents
	SpatialReferenceSystem queryCopiedSrs = dao.queryForId(copySrsId);
	TestCase.assertEquals(querySrs.getSrsName(),
			queryCopiedSrs.getSrsName());
	TestCase.assertEquals(copySrsId, queryCopiedSrs.getSrsId());
	TestCase.assertEquals(querySrs.getOrganization(),
			queryCopiedSrs.getOrganization());
	TestCase.assertEquals(querySrs.getOrganizationCoordsysId(),
			queryCopiedSrs.getOrganizationCoordsysId());
	TestCase.assertEquals(querySrs.getDefinition(),
			queryCopiedSrs.getDefinition());
	TestCase.assertEquals(querySrs.getDescription(),
			queryCopiedSrs.getDescription());

}
 
Example 23
Source Project: geopackage-android   Source File: TestUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Create Data Column Constraints
 *
 * @param geoPackage
 * @throws SQLException
 */
public static void createConstraints(GeoPackage geoPackage)
        throws SQLException {

    geoPackage.createDataColumnConstraintsTable();

    DataColumnConstraintsDao dao = geoPackage.getDataColumnConstraintsDao();

    DataColumnConstraints sampleRange = new DataColumnConstraints();
    sampleRange.setConstraintName(SAMPLE_RANGE_CONSTRAINT);
    sampleRange.setConstraintType(DataColumnConstraintType.RANGE);
    sampleRange.setMin(BigDecimal.ONE);
    sampleRange.setMinIsInclusive(true);
    sampleRange.setMax(BigDecimal.TEN);
    sampleRange.setMaxIsInclusive(true);
    dao.create(sampleRange);

    DataColumnConstraints sampleEnum1 = new DataColumnConstraints();
    sampleEnum1.setConstraintName(SAMPLE_ENUM_CONSTRAINT);
    sampleEnum1.setConstraintType(DataColumnConstraintType.ENUM);
    sampleEnum1.setValue("1");
    dao.create(sampleEnum1);

    DataColumnConstraints sampleEnum3 = new DataColumnConstraints();
    sampleEnum3.setConstraintName(SAMPLE_ENUM_CONSTRAINT);
    sampleEnum3.setConstraintType(DataColumnConstraintType.ENUM);
    sampleEnum3.setValue("3");
    dao.create(sampleEnum3);

    DataColumnConstraints sampleEnum5 = new DataColumnConstraints();
    sampleEnum5.setConstraintName(SAMPLE_ENUM_CONSTRAINT);
    sampleEnum5.setConstraintType(DataColumnConstraintType.ENUM);
    sampleEnum5.setValue("5");
    dao.create(sampleEnum5);

    DataColumnConstraints sampleEnum7 = new DataColumnConstraints();
    sampleEnum7.setConstraintName(SAMPLE_ENUM_CONSTRAINT);
    sampleEnum7.setConstraintType(DataColumnConstraintType.ENUM);
    sampleEnum7.setValue("7");
    dao.create(sampleEnum7);

    DataColumnConstraints sampleEnum9 = new DataColumnConstraints();
    sampleEnum9.setConstraintName(SAMPLE_ENUM_CONSTRAINT);
    sampleEnum9.setConstraintType(DataColumnConstraintType.ENUM);
    sampleEnum9.setValue("9");
    dao.create(sampleEnum9);

    DataColumnConstraints sampleGlob = new DataColumnConstraints();
    sampleGlob.setConstraintName(SAMPLE_GLOB_CONSTRAINT);
    sampleGlob.setConstraintType(DataColumnConstraintType.GLOB);
    sampleGlob.setValue("[1-2][0-9][0-9][0-9]");
    dao.create(sampleGlob);
}
 
Example 24
Source Project: geopackage-java   Source File: TestUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Add rows to the tile table
 *
 * @param geoPackage
 * @param tileMatrix
 * @param tileData
 */
public static void addRowsToTileTable(GeoPackage geoPackage,
		TileMatrix tileMatrix, byte[] tileData) {

	TileDao dao = geoPackage.getTileDao(tileMatrix.getTableName());

	for (int column = 0; column < tileMatrix.getMatrixWidth(); column++) {

		for (int row = 0; row < tileMatrix.getMatrixHeight(); row++) {

			TileRow newRow = dao.newRow();

			newRow.setZoomLevel(tileMatrix.getZoomLevel());
			newRow.setTileColumn(column);
			newRow.setTileRow(row);
			newRow.setTileData(tileData);

			dao.create(newRow);
		}

	}

}
 
Example 25
Source Project: geopackage-android   Source File: GeometryColumnsUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Test delete
 *
 * @param geoPackage
 * @throws SQLException
 */
public static void testDelete(GeoPackage geoPackage) throws SQLException {

    GeometryColumnsDao dao = geoPackage.getGeometryColumnsDao();

    if (dao.isTableExists()) {
        List<GeometryColumns> results = dao.queryForAll();

        if (!results.isEmpty()) {

            // Choose random geometry columns
            int random = (int) (Math.random() * results.size());
            GeometryColumns geometryColumns = results.get(random);

            // Delete the geometry columns
            dao.delete(geometryColumns);

            // Verify deleted
            GeometryColumns queryGeometryColumns = dao
                    .queryForId(geometryColumns.getId());
            TestCase.assertNull(queryGeometryColumns);

            // Prepared deleted
            results = dao.queryForAll();
            if (!results.isEmpty()) {

                // Choose random geometry columns
                random = (int) (Math.random() * results.size());
                geometryColumns = results.get(random);

                // Find which geometry columns to delete
                QueryBuilder<GeometryColumns, TableColumnKey> qb = dao
                        .queryBuilder();
                qb.where().eq(GeometryColumns.COLUMN_GEOMETRY_TYPE_NAME,
                        geometryColumns.getGeometryType().getName());
                PreparedQuery<GeometryColumns> query = qb.prepare();
                List<GeometryColumns> queryResults = dao.query(query);
                int count = queryResults.size();

                // Delete
                DeleteBuilder<GeometryColumns, TableColumnKey> db = dao
                        .deleteBuilder();
                db.where().eq(GeometryColumns.COLUMN_GEOMETRY_TYPE_NAME,
                        geometryColumns.getGeometryType().getName());
                PreparedDelete<GeometryColumns> deleteQuery = db.prepare();
                int deleted = dao.delete(deleteQuery);

                TestCase.assertEquals(count, deleted);

            }
        }
    }
}
 
Example 26
Source Project: geopackage-java   Source File: OAPIFeatureGeneratorTest.java    License: MIT License 4 votes vote down vote up
/**
 * Test a WFS server and create a GeoPackage
 * 
 * @param server
 *            server url
 * @param collection
 *            collection name
 * @param name
 *            geoPackage and table name
 * @param limit
 *            request limit
 * @param totalLimit
 *            total limit
 * @param boundingBox
 *            bounding box
 * @param time
 *            time
 * @param period
 *            period or end time
 * @param progressFrequency
 *            progress frequency
 * @throws SQLException
 *             upon error
 */
private void testServer(String server, String collection, String name,
		Integer limit, Integer totalLimit, BoundingBox boundingBox,
		String time, String period, int progressFrequency)
		throws SQLException {

	File file = new File(PATH + name + ".gpkg");

	file.delete();

	GeoPackageManager.create(file);
	GeoPackage geoPackage = GeoPackageManager.open(file);

	OAPIFeatureGenerator generator = new OAPIFeatureGenerator(geoPackage,
			name, server, collection);
	generator.setLimit(limit);
	generator.setTotalLimit(totalLimit);
	generator.setBoundingBox(boundingBox);
	generator.setTime(time);
	generator.setPeriod(period);
	generator.setDownloadAttempts(3);
	generator.setProgress(new Progress(collection, progressFrequency, 10));

	int count = generator.generateFeatures();
	if (totalLimit != null) {
		TestCase.assertEquals(totalLimit.intValue(), count);
	}

	FeatureDao featureDao = generator.getFeatureDao();
	if (totalLimit != null) {
		TestCase.assertEquals(totalLimit.intValue(), featureDao.count());
	}

	RTreeIndexExtension rTree = new RTreeIndexExtension(geoPackage);
	rTree.create(featureDao.getTable());

	BoundingBox dataBounds = geoPackage
			.getBoundingBox(featureDao.getTableName());
	Contents contents = featureDao.getContents();
	contents.setBoundingBox(dataBounds);
	geoPackage.getContentsDao().update(contents);

	SQLExec.executeSQL(geoPackage,
			"PRAGMA table_info(\"" + generator.getTableName() + "\")")
			.printResults();
	SQLExec.executeSQL(geoPackage,
			"SELECT * FROM \"" + generator.getTableName() + "\"")
			.printResults();

	geoPackage.close();

}
 
Example 27
Source Project: geopackage-java   Source File: GeoPackageExample.java    License: MIT License 4 votes vote down vote up
private static void createAttributes(GeoPackage geoPackage) {

		List<AttributesColumn> columns = new ArrayList<AttributesColumn>();

		columns.add(AttributesColumn.createColumn(TEXT_COLUMN,
				GeoPackageDataType.TEXT, false, ""));
		columns.add(AttributesColumn.createColumn(REAL_COLUMN,
				GeoPackageDataType.REAL));
		columns.add(AttributesColumn.createColumn(BOOLEAN_COLUMN,
				GeoPackageDataType.BOOLEAN));
		columns.add(AttributesColumn.createColumn(BLOB_COLUMN,
				GeoPackageDataType.BLOB));
		columns.add(AttributesColumn.createColumn(INTEGER_COLUMN,
				GeoPackageDataType.INTEGER));
		columns.add(AttributesColumn.createColumn(TEXT_LIMITED_COLUMN,
				GeoPackageDataType.TEXT,
				(long) UUID.randomUUID().toString().length()));
		columns.add(AttributesColumn.createColumn(BLOB_LIMITED_COLUMN,
				GeoPackageDataType.BLOB,
				(long) UUID.randomUUID().toString().getBytes().length));
		columns.add(AttributesColumn.createColumn(DATE_COLUMN,
				GeoPackageDataType.DATE));
		columns.add(AttributesColumn.createColumn(DATETIME_COLUMN,
				GeoPackageDataType.DATETIME));

		AttributesTable attributesTable = geoPackage
				.createAttributesTableWithId("attributes", columns);

		AttributesDao attributesDao = geoPackage
				.getAttributesDao(attributesTable.getTableName());

		for (int i = 0; i < 10; i++) {

			AttributesRow newRow = attributesDao.newRow();

			newRow.setValue(TEXT_COLUMN, UUID.randomUUID().toString());
			newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
			newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
			newRow.setValue(BLOB_COLUMN,
					UUID.randomUUID().toString().getBytes());
			newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
			newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
			newRow.setValue(BLOB_LIMITED_COLUMN,
					UUID.randomUUID().toString().getBytes());
			newRow.setValue(DATE_COLUMN, new Date());
			newRow.setValue(DATETIME_COLUMN, new Date());

			attributesDao.create(newRow);

		}
	}
 
Example 28
Source Project: mage-android   Source File: MapFragment.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Add the GeoPackage Tile Table Cache Overlay
 * @param enabledCacheOverlays
 * @param tileTableCacheOverlay
 * @param geoPackage
 * @param linkedToFeatures
 */
private void addGeoPackageTileCacheOverlay(Map<String, CacheOverlay> enabledCacheOverlays, GeoPackageTileTableCacheOverlay tileTableCacheOverlay, GeoPackage geoPackage, boolean linkedToFeatures){
	// Retrieve the cache overlay if it already exists (and remove from cache overlays)
	CacheOverlay cacheOverlay = cacheOverlays.remove(tileTableCacheOverlay.getCacheName());
	if(cacheOverlay != null){
		// If the existing cache overlay is being replaced, create a new cache overlay
		if(tileTableCacheOverlay.getParent().isAdded()){
			cacheOverlay = null;
		}
	}
	if(cacheOverlay == null){
		// Create a new GeoPackage tile provider and add to the map
		TileDao tileDao = geoPackage.getTileDao(tileTableCacheOverlay.getName());

		TileTableScaling tileTableScaling = new TileTableScaling(geoPackage, tileDao);
		TileScaling tileScaling = tileTableScaling.get();

		BoundedOverlay overlay = GeoPackageOverlayFactory
				.getBoundedOverlay(tileDao, getResources().getDisplayMetrics().density, tileScaling);

		TileOverlayOptions overlayOptions = null;
		if(linkedToFeatures){
			overlayOptions = createFeatureTileOverlayOptions(overlay);
		}else {
			overlayOptions = createTileOverlayOptions(overlay);
		}
		TileOverlay tileOverlay = map.addTileOverlay(overlayOptions);
		tileTableCacheOverlay.setTileOverlay(tileOverlay);

		// Check for linked feature tables
		tileTableCacheOverlay.clearFeatureOverlayQueries();
		FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage);
		List<FeatureDao> featureDaos = linker.getFeatureDaosForTileTable(tileDao.getTableName());
		for(FeatureDao featureDao: featureDaos){

			// Create the feature tiles
			FeatureTiles featureTiles = new DefaultFeatureTiles(getActivity(), geoPackage, featureDao,
					getResources().getDisplayMetrics().density);

			// Add the feature overlay query
			FeatureOverlayQuery featureOverlayQuery = new FeatureOverlayQuery(getActivity(), overlay, featureTiles);
			tileTableCacheOverlay.addFeatureOverlayQuery(featureOverlayQuery);
		}

		cacheOverlay = tileTableCacheOverlay;
	}
	// Add the cache overlay to the enabled cache overlays
	enabledCacheOverlays.put(cacheOverlay.getCacheName(), cacheOverlay);
}
 
Example 29
Source Project: geopackage-java   Source File: GeoPackageTestUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Validate feature table with metadata
 * 
 * @param geoPackage
 * @throws SQLException
 */
private static void validateFeatureTableWithMetadata(GeoPackage geoPackage,
		GeometryColumns geometryColumns, String idColumn,
		List<FeatureColumn> additionalColumns) throws SQLException {

	GeometryColumnsDao dao = geoPackage.getGeometryColumnsDao();

	GeometryColumns queryGeometryColumns = dao
			.queryForId(geometryColumns.getId());
	TestCase.assertNotNull(queryGeometryColumns);

	TestCase.assertEquals(geometryColumns.getTableName(),
			queryGeometryColumns.getTableName());
	TestCase.assertEquals(geometryColumns.getColumnName(),
			queryGeometryColumns.getColumnName());
	TestCase.assertEquals(GeometryType.POINT,
			queryGeometryColumns.getGeometryType());
	TestCase.assertEquals(geometryColumns.getZ(),
			queryGeometryColumns.getZ());
	TestCase.assertEquals(geometryColumns.getM(),
			queryGeometryColumns.getM());

	FeatureDao featureDao = geoPackage
			.getFeatureDao(geometryColumns.getTableName());
	FeatureRow featureRow = featureDao.newRow();

	TestCase.assertEquals(
			2 + (additionalColumns != null ? additionalColumns.size() : 0),
			featureRow.columnCount());
	if (idColumn == null) {
		idColumn = "id";
	}
	TestCase.assertEquals(idColumn, featureRow.getColumnName(0));
	TestCase.assertEquals(geometryColumns.getColumnName(),
			featureRow.getColumnName(1));

	if (additionalColumns != null) {
		TestCase.assertEquals("test_text", featureRow.getColumnName(2));
		TestCase.assertEquals("test_real", featureRow.getColumnName(3));
		TestCase.assertEquals("test_boolean", featureRow.getColumnName(4));
		TestCase.assertEquals("test_blob", featureRow.getColumnName(5));
		TestCase.assertEquals("test_integer", featureRow.getColumnName(6));
		TestCase.assertEquals("test_text_limited",
				featureRow.getColumnName(7));
		TestCase.assertEquals("test_blob_limited",
				featureRow.getColumnName(8));
	}
}
 
Example 30
Source Project: geopackage-android   Source File: DataColumnsUtils.java    License: MIT License 4 votes vote down vote up
/**
 * Test delete
 *
 * @param geoPackage
 * @throws SQLException
 */
public static void testDelete(GeoPackage geoPackage) throws SQLException {

	DataColumnsDao dao = geoPackage.getDataColumnsDao();
	if (dao.isTableExists()) {
		List<DataColumns> results = dao.queryForAll();

		if (!results.isEmpty()) {

			// Choose random data columns
			int random = (int) (Math.random() * results.size());
			DataColumns dataColumns = results.get(random);

			// Delete the data columns
			dao.delete(dataColumns);

			// Verify deleted
			DataColumns queryDataColumns = dao.queryForId(dataColumns
					.getId());
			TestCase.assertNull(queryDataColumns);

			// Prepared deleted
			results = dao.queryForAll();
			if (!results.isEmpty()) {

				// Choose random data columns
				random = (int) (Math.random() * results.size());
				dataColumns = results.get(random);

				// Find which data columns to delete
				QueryBuilder<DataColumns, TableColumnKey> qb = dao
						.queryBuilder();
				qb.where().eq(DataColumns.COLUMN_TABLE_NAME,
						dataColumns.getTableName());
				PreparedQuery<DataColumns> query = qb.prepare();
				List<DataColumns> queryResults = dao.query(query);
				int count = queryResults.size();

				// Delete
				DeleteBuilder<DataColumns, TableColumnKey> db = dao
						.deleteBuilder();
				db.where().eq(DataColumns.COLUMN_TABLE_NAME,
						dataColumns.getTableName());
				PreparedDelete<DataColumns> deleteQuery = db.prepare();
				int deleted = dao.delete(deleteQuery);

				TestCase.assertEquals(count, deleted);

			}
		}
	}
}