Java Code Examples for com.j256.ormlite.dao.CloseableIterator

The following examples show how to use com.j256.ormlite.dao.CloseableIterator. 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: AndroidAPS   Author: MilosKozak   File: UploadQueue.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
String textList() {
    String result = "";
    CloseableIterator<DbRequest> iterator;
    try {
        iterator = MainApp.getDbHelper().getDbRequestInterator();
        try {
            while (iterator.hasNext()) {
                DbRequest dbr = iterator.next();
                result += "<br>";
                result += dbr.action.toUpperCase() + " ";
                result += dbr.collection + ": ";
                result += dbr.data;
            }
        } finally {
            iterator.close();
        }
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return result;
}
 
Example #2
Source Project: mage-android   Author: ngageoint   File: ObservationFeedFragment.java    License: Apache License 2.0 6 votes vote down vote up
private Cursor obtainCursor(PreparedQuery<Observation> query, Dao<Observation, Long> oDao) throws SQLException {
	Cursor c = null;
	CloseableIterator<Observation> iterator = oDao.iterator(query);

	// get the raw results which can be cast under Android
	AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
	c = results.getRawCursor();
	if (c.moveToLast()) {
		long oldestTime = c.getLong(c.getColumnIndex("last_modified"));
		Log.i(LOG_NAME, "last modified is: " + c.getLong(c.getColumnIndex("last_modified")));
		Log.i(LOG_NAME, "querying again in: " + (oldestTime - requeryTime)/60000 + " minutes");
		if (queryUpdateHandle != null) {
			queryUpdateHandle.cancel(true);
		}
		queryUpdateHandle = scheduler.schedule(new Runnable() {
			public void run() {
				updateFilter();
			}
		}, oldestTime - requeryTime, TimeUnit.MILLISECONDS);
		c.moveToFirst();
	}
	return c;
}
 
Example #3
Source Project: mage-android   Author: ngageoint   File: LocationLoadTask.java    License: Apache License 2.0 6 votes vote down vote up
private CloseableIterator<Location> iterator() throws SQLException {
	Dao<Location, Long> dao = DaoStore.getInstance(context).getLocationDao();
	QueryBuilder<Location, Long> query = dao.queryBuilder();
	Where<? extends Temporal, Long> where = query.where().ge("timestamp", locationCollection.getLatestDate());
	User currentUser = null;
	try {
		currentUser = UserHelper.getInstance(context.getApplicationContext()).readCurrentUser();
	} catch (UserException e) {
		e.printStackTrace();
	}
	if (currentUser != null) {
		where.and().ne("user_id", currentUser.getId()).and().eq("event_id", currentUser.getUserLocal().getCurrentEvent().getId());
	}
	if (filter != null) {
		filter.and(where);
	}
	query.orderBy("timestamp", false);


	return dao.iterator(query.prepare());
}
 
Example #4
Source Project: mage-android   Author: ngageoint   File: ObservationLoadTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params ) {
    CloseableIterator<Observation> iterator = null;
    try {
        iterator = iterator();
        while (iterator.hasNext() && !isCancelled()) {
            Observation o = iterator.current();
            Geometry geometry = o.getGeometry();
            Point centroid = GeometryUtils.getCentroid(geometry);
            MarkerOptions options = new MarkerOptions().position(new LatLng(centroid.getY(), centroid.getX())).icon(ObservationBitmapFactory.bitmapDescriptor(context, o));

            publishProgress(new Pair<>(options, o));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (iterator != null) {
            iterator.closeQuietly();
        }
    }

    return null;
}
 
Example #5
Source Project: mage-android   Author: ngageoint   File: ObservationLoadTask.java    License: Apache License 2.0 6 votes vote down vote up
private CloseableIterator<Observation> iterator() throws SQLException {
    Dao<Observation, Long> dao = DaoStore.getInstance(context).getObservationDao();
    QueryBuilder<Observation, Long> query = dao.queryBuilder();
    Where<Observation, Long> where = query
            .orderBy("timestamp", false)
            .where()
            .ge("last_modified", observationCollection.getLatestDate())
            .and()
            .eq("event_id", currentEventId);

    for (Filter filter : filters) {
        QueryBuilder<?, ?> filterQuery = filter.query();
        if (filterQuery != null) {
            query.join(filterQuery);
        }

        filter.and(where);
    }

    return dao.iterator(query.prepare());
}
 
Example #6
Source Project: geopackage-core-java   Author: ngageoint   File: FeatureTableCoreIndex.java    License: MIT License 6 votes vote down vote up
/**
 * Query for all Geometry Index objects
 * 
 * @return geometry indices iterator
 */
public CloseableIterator<GeometryIndex> query() {

	CloseableIterator<GeometryIndex> geometryIndices = null;

	QueryBuilder<GeometryIndex, GeometryIndexKey> qb = queryBuilder();

	try {
		geometryIndices = qb.iterator();
	} catch (SQLException e) {
		throw new GeoPackageException(
				"Failed to query for all Geometry Indices. GeoPackage: "
						+ geoPackage.getName() + ", Table Name: "
						+ tableName + ", Column Name: " + columnName,
				e);
	}

	return geometryIndices;
}
 
Example #7
Source Project: geopackage-core-java   Author: ngageoint   File: FeatureTableCoreIndex.java    License: MIT License 6 votes vote down vote up
/**
 * Query for Geometry Index objects within the Geometry Envelope
 * 
 * @param envelope
 *            geometry envelope
 * @return geometry indices iterator
 */
public CloseableIterator<GeometryIndex> query(GeometryEnvelope envelope) {

	CloseableIterator<GeometryIndex> geometryIndices = null;

	QueryBuilder<GeometryIndex, GeometryIndexKey> qb = queryBuilder(
			envelope);
	try {
		geometryIndices = qb.iterator();
	} catch (SQLException e) {
		throw new GeoPackageException(
				"Failed to query for Geometry Indices. GeoPackage: "
						+ geoPackage.getName() + ", Table Name: "
						+ tableName + ", Column Name: " + columnName,
				e);
	}

	return geometryIndices;
}
 
Example #8
Source Project: geopackage-core-java   Author: ngageoint   File: Contents.java    License: MIT License 6 votes vote down vote up
/**
 * Get the Geometry Columns, should only return one or no value
 * 
 * @return geometry columns
 */
public GeometryColumns getGeometryColumns() {
	GeometryColumns result = null;
	if (geometryColumns.size() > 1) {
		// This shouldn't happen with the unique table name constraint on
		// geometry columns
		throw new GeoPackageException(
				"Unexpected state. More than one GeometryColumn has a foreign key to the Contents. Count: "
						+ geometryColumns.size());
	} else if (geometryColumns.size() == 1) {
		CloseableIterator<GeometryColumns> iterator = geometryColumns
				.closeableIterator();
		try {
			result = iterator.next();
		} finally {
			try {
				iterator.close();
			} catch (IOException e) {
				throw new GeoPackageException(
						"Failed to close the Geometry Columns iterator", e);
			}
		}
	}
	return result;
}
 
Example #9
Source Project: geopackage-core-java   Author: ngageoint   File: Contents.java    License: MIT License 6 votes vote down vote up
/**
 * Get the Tile Matrix Set, should only return one or no value
 * 
 * @return tile matrix set
 */
public TileMatrixSet getTileMatrixSet() {
	TileMatrixSet result = null;
	if (tileMatrixSet.size() > 1) {
		// This shouldn't happen with the table name primary key on tile
		// matrix set
		throw new GeoPackageException(
				"Unexpected state. More than one TileMatrixSet has a foreign key to the Contents. Count: "
						+ tileMatrixSet.size());
	} else if (tileMatrixSet.size() == 1) {
		CloseableIterator<TileMatrixSet> iterator = tileMatrixSet
				.closeableIterator();
		try {
			result = iterator.next();
		} finally {
			try {
				iterator.close();
			} catch (IOException e) {
				throw new GeoPackageException(
						"Failed to close the Tile Matrix Set iterator", e);
			}
		}
	}
	return result;
}
 
Example #10
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testIterator() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	CloseableIterator<Foo> iterator = dao.iterator();
	assertFalse(iterator.hasNext());

	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	Foo foo2 = new Foo();
	assertEquals(1, dao.create(foo2));

	iterator = dao.iterator();
	assertTrue(iterator.hasNext());
	Foo result = iterator.next();
	assertEquals(foo1.id, result.id);
	assertTrue(iterator.hasNext());

	result = iterator.next();
	assertEquals(foo2.id, result.id);

	assertFalse(iterator.hasNext());
	assertNull(iterator.nextThrow());
}
 
Example #11
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testIteratorPrepared() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	Foo foo2 = new Foo();
	assertEquals(1, dao.create(foo2));

	PreparedQuery<Foo> query = dao.queryBuilder().where().eq(Foo.ID_COLUMN_NAME, foo2.id).prepare();
	CloseableIterator<Foo> iterator = dao.iterator(query);
	assertTrue(iterator.hasNext());
	Foo result = iterator.next();
	assertEquals(foo2.id, result.id);
	assertFalse(iterator.hasNext());
	assertNull(iterator.nextThrow());
}
 
Example #12
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIteratorNextRemoveRemoveNoNext() throws Exception {
	Dao<Foo, Object> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));
	Foo foo2 = new Foo();
	assertEquals(1, dao.create(foo2));
	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		iterator.next();
		iterator.remove();
		iterator.remove();
	} finally {
		iterator.close();
	}
}
 
Example #13
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testIteratorRemove() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	assertEquals(1, dao.queryForAll().size());

	CloseableIterator<Foo> iterator = dao.iterator();
	assertTrue(iterator.hasNext());
	Foo result = iterator.next();
	assertEquals(foo1.id, result.id);
	iterator.remove();

	assertFalse(iterator.hasNext());
	assertNull(iterator.nextThrow());

	assertEquals(0, dao.queryForAll().size());
	iterator.close();
}
 
Example #14
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testIteratorHasNextClosed() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	assertEquals(1, dao.queryForAll().size());

	CloseableIterator<Foo> iterator = dao.iterator();
	assertTrue(iterator.hasNext());
	iterator.next();

	assertFalse(iterator.hasNext());
	assertNull(iterator.nextThrow());

	iterator.close();
	assertFalse(iterator.hasNext());
}
 
Example #15
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIteratorRawResults() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	GenericRawResults<String[]> rawResults = dao.queryRaw("SELECT " + Foo.ID_COLUMN_NAME + " FROM FOO");
	CloseableIterator<String[]> iterator = rawResults.closeableIterator();
	try {
		assertTrue(iterator.hasNext());
		iterator.next();
		iterator.remove();
	} finally {
		iterator.close();
	}
}
 
Example #16
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testIteratorJdbcMoveBack() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo = new Foo();
	assertEquals(1, dao.create(foo));

	QueryBuilder<Foo, Integer> qb = dao.queryBuilder();
	qb.orderBy(Foo.VAL_COLUMN_NAME, true);
	CloseableIterator<Foo> iterator = dao.iterator(qb.prepare());
	try {
		assertEquals(foo, iterator.first());
		iterator.first();
		fail("Should have thrown");
	} finally {
		iterator.close();
	}
}
 
Example #17
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testMoveClosed() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);

	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		assertFalse(iterator.hasNext());
		assertNull(iterator.first());
		assertNull(iterator.previous());
		assertNull(iterator.current());
		assertNull(iterator.nextThrow());
		assertNull(iterator.moveRelative(10));
	} finally {
		iterator.close();
	}
}
 
Example #18
Source Project: ormlite-core   Author: j256   File: EnumToStringTypeTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testEnumToStringValue() throws Exception {
	Class<LocalEnumToString> clazz = LocalEnumToString.class;
	Dao<LocalEnumToString, Object> dao = createDao(clazz, true);
	LocalEnumToString foo = new LocalEnumToString();
	foo.ourEnum = OurEnum.SECOND;
	assertEquals(1, dao.create(foo));
	GenericRawResults<String[]> results = dao.queryRaw("select * from " + TABLE_NAME);
	CloseableIterator<String[]> iterator = results.closeableIterator();
	try {
		assertTrue(iterator.hasNext());
		String[] result = iterator.next();
		assertNotNull(result);
		assertEquals(1, result.length);
		assertFalse(OurEnum.SECOND.name().equals(result[0]));
		assertTrue(OurEnum.SECOND.toString().equals(result[0]));
	} finally {
		IOUtils.closeQuietly(iterator);
	}
}
 
Example #19
Source Project: AndroidStarter   Author: RoRoche   File: RxBaseDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Observable<CloseableIterator<DataType>> rxIterator(final PreparedQuery<DataType> preparedQuery) {
    final Func0<Observable<CloseableIterator<DataType>>> loFunc = () -> {
        try {
            return Observable.just(iterator(preparedQuery));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}
 
Example #20
Source Project: AndroidStarter   Author: RoRoche   File: RxBaseDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Observable<CloseableIterator<DataType>> rxIterator(final PreparedQuery<DataType> preparedQuery, final int resultFlags) {
    final Func0<Observable<CloseableIterator<DataType>>> loFunc = () -> {
        try {
            return Observable.just(iterator(preparedQuery, resultFlags));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}
 
Example #21
Source Project: AndroidAPS   Author: MilosKozak   File: DatabaseHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public CloseableIterator getDbRequestInterator() {
    try {
        return getDaoDbRequest().closeableIterator();
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
        return null;
    }
}
 
Example #22
Source Project: mage-android   Author: ngageoint   File: LocationLoadTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {
	CloseableIterator<Location> iterator = null;
	try {
		iterator = iterator();
		while (iterator.hasNext() && !isCancelled()) {
			Location location = iterator.current();
			User user = location.getUser();
			if (user == null) {
				continue;
			}

			Point point = GeometryUtils.getCentroid(location.getGeometry());
			LatLng latLng = new LatLng(point.getY(), point.getX());
			MarkerOptions options = new MarkerOptions().position(latLng).icon(LocationBitmapFactory.bitmapDescriptor(context, location, user));

			publishProgress(new Pair<>(options, new Pair<>(location, user)));
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		if (iterator != null) {
			iterator.closeQuietly();
		}
	}

	return null;
}
 
Example #23
Source Project: geopackage-core-java   Author: ngageoint   File: FeatureTableCoreIndex.java    License: MIT License 5 votes vote down vote up
/**
 * Query for Geometry Index objects within the bounding box, projected
 * correctly
 * 
 * @param boundingBox
 *            bounding box
 * @param projection
 *            projection of the provided bounding box
 * @return geometry indices iterator
 */
public CloseableIterator<GeometryIndex> query(BoundingBox boundingBox,
		Projection projection) {

	BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
			projection);

	CloseableIterator<GeometryIndex> geometryIndices = query(
			featureBoundingBox);

	return geometryIndices;
}
 
Example #24
Source Project: geopackage-java   Author: ngageoint   File: NumberFeaturesTile.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BufferedImage drawTile(int tileWidth, int tileHeight,
		long tileFeatureCount,
		CloseableIterator<GeometryIndex> geometryIndexResults) {

	String featureText = String.valueOf(tileFeatureCount);
	BufferedImage image = drawTile(tileWidth, tileHeight, featureText);

	return image;
}
 
Example #25
Source Project: geopackage-java   Author: ngageoint   File: DefaultFeatureTiles.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BufferedImage drawTile(int zoom, BoundingBox boundingBox,
		CloseableIterator<GeometryIndex> results) {

	FeatureTileGraphics graphics = new FeatureTileGraphics(tileWidth,
			tileHeight);

	// Feature projection to web mercator projection
	ProjectionTransform webMercatorTransform = getWebMercatorTransform();
	BoundingBox expandedBoundingBox = expandBoundingBox(boundingBox);

	boolean drawn = false;
	while (results.hasNext()) {
		GeometryIndex geometryIndex = results.next();
		FeatureRow featureRow = getFeatureIndex()
				.getFeatureRow(geometryIndex);
		if (drawFeature(zoom, boundingBox, expandedBoundingBox,
				webMercatorTransform, graphics, featureRow)) {
			drawn = true;
		}
	}
	try {
		results.close();
	} catch (IOException e) {
		log.log(Level.WARNING, "Failed to close geometry index results", e);
	}

	BufferedImage image = null;
	if (drawn) {
		image = graphics.createImage();
		image = checkIfDrawn(image);
	} else {
		graphics.dispose();
	}

	return image;
}
 
Example #26
Source Project: geopackage-java   Author: ngageoint   File: FeatureTiles.java    License: MIT License 5 votes vote down vote up
/**
 * Query for feature results in the bounding box
 *
 * @param webMercatorBoundingBox
 *            web mercator bounding box
 * @return geometry index results
 */
public CloseableIterator<GeometryIndex> queryIndexedFeatures(
		BoundingBox webMercatorBoundingBox) {

	// Create an expanded bounding box to handle features outside the tile
	// that overlap
	BoundingBox expandedQueryBoundingBox = expandBoundingBox(
			webMercatorBoundingBox);

	// Query for geometries matching the bounds in the index
	CloseableIterator<GeometryIndex> results = featureIndex
			.query(expandedQueryBoundingBox, WEB_MERCATOR_PROJECTION);

	return results;
}
 
Example #27
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIteratorRemoveNoNext() throws Exception {
	Dao<Foo, Object> dao = createDao(Foo.class, true);
	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		iterator.remove();
	} finally {
		iterator.close();
	}
}
 
Example #28
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testMultipleHasNext() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	CloseableIterator<Foo> iterator = dao.iterator();
	assertTrue(iterator.hasNext());
	assertTrue(iterator.hasNext());
	assertTrue(iterator.hasNext());
	iterator.moveToNext();
	assertFalse(iterator.hasNext());
}
 
Example #29
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testIteratorMoveAround() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	List<Foo> fooList = new ArrayList<Foo>();
	for (int i = 0; i < 10; i++) {
		Foo foo = new Foo();
		foo.val = i;
		assertEquals(1, dao.create(foo));
		fooList.add(foo);
	}

	QueryBuilder<Foo, Integer> qb = dao.queryBuilder();
	qb.orderBy(Foo.VAL_COLUMN_NAME, true);
	CloseableIterator<Foo> iterator = dao.iterator(qb.prepare(), ResultSet.TYPE_SCROLL_INSENSITIVE);
	try {
		assertEquals(fooList.get(0), iterator.first());
		assertEquals(fooList.get(0), iterator.first());
		assertEquals(fooList.get(0), iterator.current());
		assertEquals(fooList.get(1), iterator.next());
		assertEquals(fooList.get(1), iterator.current());
		assertEquals(fooList.get(0), iterator.first());
		assertEquals(fooList.get(0), iterator.current());
		assertEquals(fooList.get(1), iterator.next());
		assertTrue(iterator.hasNext());
		assertEquals(fooList.get(2), iterator.next());
		assertEquals(fooList.get(2), iterator.current());
		assertEquals(fooList.get(1), iterator.previous());
		assertEquals(fooList.get(2), iterator.next());
		assertEquals(fooList.get(1), iterator.moveRelative(-1));
		assertEquals(fooList.get(3), iterator.moveRelative(2));
		assertEquals(fooList.get(9), iterator.moveRelative(6));
		assertFalse(iterator.hasNext());
		assertNull(iterator.current());
	} finally {
		iterator.close();
	}
}
 
Example #30
Source Project: ormlite-core   Author: j256   File: SelectIteratorTest.java    License: ISC License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIteratorNextOnly() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo = new Foo();
	assertEquals(1, dao.create(foo));

	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		assertEquals(foo, iterator.next());
		iterator.next();
		fail("Should have thrown");
	} finally {
		iterator.close();
	}
}