com.j256.ormlite.dao.CloseableIterator Java Examples

The following examples show how to use com.j256.ormlite.dao.CloseableIterator. 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: FeatureTableCoreIndex.java    From geopackage-core-java with 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 #2
Source File: SelectIteratorTest.java    From ormlite-core with 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 #3
Source File: SelectIteratorTest.java    From ormlite-core with 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 #4
Source File: SelectIteratorTest.java    From ormlite-core with 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 #5
Source File: SelectIteratorTest.java    From ormlite-core with 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 #6
Source File: SelectIteratorTest.java    From ormlite-core with 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 #7
Source File: SelectIteratorTest.java    From ormlite-core with 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 #8
Source File: Contents.java    From geopackage-core-java with 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 #9
Source File: Contents.java    From geopackage-core-java with 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 #10
Source File: FeatureTableCoreIndex.java    From geopackage-core-java with 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 #11
Source File: SelectIteratorTest.java    From ormlite-core with 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 #12
Source File: ObservationLoadTask.java    From mage-android with 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 #13
Source File: ObservationLoadTask.java    From mage-android with 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 #14
Source File: LocationLoadTask.java    From mage-android with 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 #15
Source File: ObservationFeedFragment.java    From mage-android with 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 #16
Source File: EnumToStringTypeTest.java    From ormlite-core with 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 #17
Source File: UploadQueue.java    From AndroidAPS with 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 #18
Source File: SelectIteratorTest.java    From ormlite-core with 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 #19
Source File: SelectIteratorTest.java    From ormlite-core with 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 #20
Source File: LocationLoadTask.java    From mage-android with 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 #21
Source File: RxBaseDaoImpl.java    From AndroidStarter with 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 #22
Source File: SelectIteratorTest.java    From ormlite-core with 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 #23
Source File: RxBaseDaoImpl.java    From AndroidStarter with 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 #24
Source File: FeatureTiles.java    From geopackage-java with 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 #25
Source File: QueryBuilderTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testQueryRawMax() throws Exception {
	Dao<Foo, Object> dao = createDao(Foo.class, true);

	Foo foo1 = new Foo();
	foo1.stringField = "1";
	foo1.val = 10;
	assertEquals(1, dao.create(foo1));
	Foo foo2 = new Foo();
	foo2.stringField = "1";
	foo2.val = 20;
	assertEquals(1, dao.create(foo2));
	Foo foo3 = new Foo();
	foo3.stringField = "2";
	foo3.val = 30;
	assertEquals(1, dao.create(foo3));
	Foo foo4 = new Foo();
	foo4.stringField = "2";
	foo4.val = 40;
	assertEquals(1, dao.create(foo4));

	QueryBuilder<Foo, Object> qb = dao.queryBuilder();
	qb.selectRaw("string, max(val) as val");
	qb.groupBy(Foo.STRING_COLUMN_NAME);
	GenericRawResults<Foo> results = dao.queryRaw(qb.prepareStatementString(), dao.getRawRowMapper());
	assertNotNull(results);
	CloseableIterator<Foo> iterator = results.closeableIterator();
	try {
		assertTrue(iterator.hasNext());
		assertEquals(foo2.val, iterator.next().val);
		assertTrue(iterator.hasNext());
		assertEquals(foo4.val, iterator.next().val);
		assertFalse(iterator.hasNext());
	} finally {
		iterator.close();
	}
}
 
Example #26
Source File: SelectIteratorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testMoveNone() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);

	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		assertNull(iterator.current());
	} finally {
		iterator.close();
	}

	iterator = dao.iterator();
	try {
		assertNull(iterator.previous());
	} finally {
		iterator.close();
	}

	iterator = dao.iterator();
	try {
		assertNull(iterator.moveRelative(1));
	} finally {
		iterator.close();
	}

	iterator = dao.iterator();
	try {
		assertNull(iterator.nextThrow());
	} finally {
		iterator.close();
	}
}
 
Example #27
Source File: DefaultFeatureTiles.java    From geopackage-java with 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 #28
Source File: NumberFeaturesTile.java    From geopackage-java with 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 #29
Source File: SelectIteratorTest.java    From ormlite-core with 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 File: SelectIteratorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testFirstCurrent() 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.current());
		assertFalse(iterator.hasNext());
		assertNull(iterator.current());
	} finally {
		iterator.close();
	}
}