Java Code Examples for com.googlecode.cqengine.resultset.ResultSet#iterator()

The following examples show how to use com.googlecode.cqengine.resultset.ResultSet#iterator() . 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: ResultSets.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Collection-like view of the given ResultSet.
 * <p/>
 * The collection simply delegates to the ResultSet, which in turn will reflect
 * any changes made to the underlying IndexedCollection by other threads.
 * For example consecutive calls to the size() method
 * may return different values if objects are added to or removed from the IndexedCollection.
 *
 * @param resultSet The ResultSet to wrap
 * @return A Collection-like view of the given ResultSet
 */
public static <O> Collection<O> asCollection(final ResultSet<O> resultSet) {
    return new AbstractCollection<O>() {
        @Override
        public Iterator<O> iterator() {
            return resultSet.iterator();
        }
        @Override
        public int size() {
            return resultSet.size();
        }

        @Override
        public boolean contains(Object o) {
            @SuppressWarnings("unchecked")
            O object = (O)o;
            return resultSet.contains(object);
        }

        @Override
        public boolean isEmpty() {
            return resultSet.isEmpty();
        }
    };
}
 
Example 2
Source File: SQLiteObjectStore.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIterator<O> iterator(QueryOptions queryOptions) {
    final ResultSet<O> rs = backingIndex.retrieve(has(primaryKeyAttribute), queryOptions);
    final Iterator<O> i = rs.iterator();
    class CloseableIteratorImpl extends UnmodifiableIterator<O> implements CloseableIterator<O> {

        @Override
        public boolean hasNext() {
            return i.hasNext();
        }

        @Override
        public O next() {
            return i.next();
        }

        @Override
        public void close() {
            rs.close();
        }
    }
    return new CloseableIteratorImpl();
}
 
Example 3
Source File: OffHeapPersistenceConcurrencyTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    sequenceLog.add(taskName + " started and about to access collection");
    ResultSet<Car> backgroundResults = collection.retrieve(between(Car.CAR_ID, 40, 59));
    Iterator<Car> iterator = backgroundResults.iterator();
    int count = 0;
    for (; iterator.hasNext() && count < 5; count++) {
        iterator.next();
    }
    sequenceLog.add(taskName + " pausing mid-read");
    sleep(millisecondsToPauseMidRequest);
    sequenceLog.add(taskName + " resuming read");
    while (iterator.hasNext()) {
        iterator.next();
        count++;
    }
    backgroundResults.close();
    sequenceLog.add(taskName + " finished reading " + count + " items");
}
 
Example 4
Source File: DiskPersistenceConcurrencyTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    sequenceLog.add(taskName + " started and about to access collection");
    ResultSet<Car> backgroundResults = collection.retrieve(between(Car.CAR_ID, 40, 59));
    Iterator<Car> iterator = backgroundResults.iterator();
    int count = 0;
    for (; iterator.hasNext() && count < 5; count++) {
        iterator.next();
    }
    sequenceLog.add(taskName + " pausing mid-read");
    sleep(millisecondsToPauseMidRequest);
    sequenceLog.add(taskName + " resuming read");
    while (iterator.hasNext()) {
        iterator.next();
        count++;
    }
    backgroundResults.close();
    sequenceLog.add(taskName + " finished reading " + count + " items");
}
 
Example 5
Source File: CollectionQueryEngine.java    From cqengine with Apache License 2.0 5 votes vote down vote up
Iterator<O> retrieveWithIndexOrderingMissingResults(final Query<O> query, QueryOptions queryOptions, Attribute<O, Comparable> primarySortAttribute, List<AttributeOrder<O>> allSortOrders, boolean attributeCanHaveMoreThanOneValue) {
    // Ensure that at the end of processing the request, that we close any resources we opened...
    final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();

    // Retrieve missing objects from the secondary index on objects which don't have a value for the primary sort attribute...
    Not<O> missingValuesQuery = not(has(primarySortAttribute));
    ResultSet<O> missingResults = retrieveRecursive(missingValuesQuery, queryOptions);

    // Ensure that this is closed...
    closeableResourceGroup.add(missingResults);

    Iterator<O> missingResultsIterator = missingResults.iterator();
    // Filter the objects from the secondary index, to ensure they match the query...
    missingResultsIterator = filterIndexOrderingCandidateResults(missingResultsIterator, query, queryOptions);

    // Determine if we need to sort the missing objects...
    Index<O> indexForMissingObjects = standingQueryIndexes.get(missingValuesQuery);
    final List<AttributeOrder<O>> sortOrdersForBucket = determineAdditionalSortOrdersForIndexOrdering(allSortOrders, attributeCanHaveMoreThanOneValue, indexForMissingObjects, queryOptions);

    if (!sortOrdersForBucket.isEmpty()) {
        // We do need to sort the missing objects...
        Comparator<O> comparator = new AttributeOrdersComparator<O>(sortOrdersForBucket, queryOptions);
        missingResultsIterator = IteratorUtil.materializedSort(missingResultsIterator, comparator);
    }

    return missingResultsIterator;
}
 
Example 6
Source File: TransactionalIndexedCollection.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Override
public boolean retainAll(final Collection<?> c) {
    synchronized (writeMutex) {
        QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
        try {
            // Copy objects into a new set removing nulls.
            // CQEngine does not permit nulls in queries, but the spec of {@link Collection#retainAll} does.
            Set<O> objectsToRetain = new HashSet<O>(c.size());
            for (Object object : c) {
                if (object != null) {
                    @SuppressWarnings("unchecked") O o = (O)object;
                    objectsToRetain.add(o);
                }
            }
            // Prepare a query which will match objects in the collection which are not contained in the given
            // collection of objects to retain and therefore which need to be removed from the collection...
            // We prepare the query to use the same QueryOptions as above.
            // Any resources opened for the query which need to be closed,
            // will be added to the QueryOptions and closed at the end of this method.
            @SuppressWarnings("unchecked")
            ResultSet<O> objectsToRemove = super.retrieve(not(in(selfAttribute(objectType), objectsToRetain)), queryOptions);

            Iterator<O> objectsToRemoveIterator = objectsToRemove.iterator();
            if (!objectsToRemoveIterator.hasNext()) {
                return false;
            }

            // Configure new reading threads to exclude the objects we will remove,
            // then wait for this to take effect across all threads...
            incrementVersion(objectsToRemove);

            // Now remove the given objects...
            boolean modified = doRemoveAll(objectsToRemove, queryOptions);

            // Finally, remove the exclusion,
            // then wait for this to take effect across all threads...
            incrementVersion(Collections.<O>emptySet());

            return modified;
        }
        finally {
            closeRequestScopeResourcesIfNecessary(queryOptions);
        }
    }
}
 
Example 7
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testNewResultSet_Iterator_Exception_Close() throws Exception{

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenThrow(new SQLException("SQL exception"));
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));

    // Iterator
    try {
        ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES,
                OBJECT_TO_ID,
                idToObject,
                "")

                .retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));

        assertNotNull(carsWithAbs);
        Iterator<Car> carsWithAbsIterator = carsWithAbs.iterator();
        assertNotNull(carsWithAbsIterator.next());
        carsWithAbsIterator.next();// Should throw exception!

    }finally {
        verify(connection, times(0)).close(); // Connection should be left open
        verify(preparedStatement, times(1)).close();
        verify(resultSet, times(1)).close();
    }

}
 
Example 8
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewResultSet_Iterator_Close() throws Exception{


    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenReturn(3);
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
    when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            idToObject,
            "")

            .retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));


    assertNotNull(carsWithAbs);
    Iterator carsWithAbsIterator = carsWithAbs.iterator();

    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertFalse(carsWithAbsIterator.hasNext());

    // The end of the iteration should close the resources
    verify(connection, times(0)).close(); // Connection should be left open
    verify(preparedStatement, times(1)).close();
    verify(resultSet, times(1)).close();

}
 
Example 9
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewResultSet_Close() throws Exception{

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);

    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenReturn(3);
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
    when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            idToObject,
            "")

            .retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));

    assertNotNull(carsWithAbs);
    Iterator carsWithAbsIterator = carsWithAbs.iterator();
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    // Do not continue with the iteration, but close
    carsWithAbs.close();

    verify(connection, times(0)).close(); // Connection should be left open
    verify(preparedStatement, times(1)).close();
    verify(resultSet, times(1)).close();

}
 
Example 10
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testNewResultSet_FilterQuery_Iterator_Exception_Close() throws Exception{

    // Mocks
    FilterQuery<Car, String> filterQuery = mockFilterQuery();
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(statement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenThrow(new SQLException("SQL exception"));
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));

    // Iterator
    try {
        ResultSet<Car> cars = new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES,
                OBJECT_TO_ID,
                idToObject,
                "")

                .retrieve(filterQuery, createQueryOptions(connectionManager));

        assertNotNull(cars);
        Iterator<Car> carsWithAbsIterator = cars.iterator();
        assertNotNull(carsWithAbsIterator.next());
        carsWithAbsIterator.next();// Should throw exception!

    }finally {
        verify(connection, times(0)).close(); // Connection should be left open
        verify(statement, times(1)).close();
        verify(resultSet, times(1)).close();
    }

}
 
Example 11
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewResultSet_FilterQuery_Iterator_Close() throws Exception{

    // Mocks
    FilterQuery<Car, String> filterQuery = mockFilterQuery();
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(statement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenReturn(1).thenReturn(2).thenReturn(3).thenReturn(4).thenReturn(5);
    when(resultSet.getString(2)).thenReturn("abs").thenReturn("gps").thenReturn("airbags").thenReturn("abs").thenReturn("").thenReturn("gps");
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
    when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
    when(idToObject.getValue(eq(5), anyQueryOptions())).thenReturn(data.get(4));

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            idToObject,
            "")

            .retrieve(filterQuery, createQueryOptions(connectionManager));


    assertNotNull(carsWithAbs);
    Iterator carsWithAbsIterator = carsWithAbs.iterator();

    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    assertFalse(carsWithAbsIterator.hasNext());

    // The end of the iteration should close the resources
    verify(connection, times(0)).close(); // Connection should be left open
    verify(statement, times(1)).close();
    verify(resultSet, times(1)).close();

}
 
Example 12
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewResultSet_FilterQuery_Close() throws Exception{

    // Mocks
    FilterQuery<Car, String> filterQuery = mockFilterQuery();
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);

    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(statement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenReturn(1).thenReturn(2).thenReturn(3).thenReturn(4).thenReturn(5);
    when(resultSet.getString(2)).thenReturn("abs").thenReturn("gps").thenReturn("airbags").thenReturn("abs").thenReturn("").thenReturn("gps");
    when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
    when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
    when(idToObject.getValue(eq(5), anyQueryOptions())).thenReturn(data.get(4));

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            idToObject,
            "")

            .retrieve(filterQuery, createQueryOptions(connectionManager));

    assertNotNull(carsWithAbs);
    Iterator carsWithAbsIterator = carsWithAbs.iterator();
    assertTrue(carsWithAbsIterator.hasNext());
    assertNotNull(carsWithAbsIterator.next());
    // Do not continue with the iteration, but close
    carsWithAbs.close();

    verify(connection, times(0)).close(); // Connection should be left open
    verify(statement, times(1)).close();
    verify(resultSet, times(1)).close();

}