repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/compound/support/TupleCombinationGenerator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.compound.support;
import java.util.*;
/**
* Contains static utility methods for generating combinations of elements <i>between</i> lists.
* <p/>
* A major use of this class is to build compound indexes on several attributes where some attributes have multiple
* values - {@link com.googlecode.cqengine.attribute.MultiValueAttribute}. In those cases the index must store entries
* for all of the combinations of attribute values.
*
* @author Niall Gallagher
*/
public class TupleCombinationGenerator {
/**
* Given a list of lists as input, determines all combinations of objects <i>between</i> the input lists, with
* no repetition. Combinations are returned as if the lists were navigated using preordered depth-first search.
* <p/>
* Example:
* <pre>
* List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
* add(Arrays.<Object>asList(1));
* add(Arrays.<Object>asList("bar", "baz"));
* add(Arrays.<Object>asList(2.0, 3.0, 4.0));
* }};
* System.out.println(generateCombinations(inputLists));
* </pre>
* The example code above prints:
* <pre>[[1, bar, 2.0], [1, bar, 3.0], [1, bar, 4.0], [1, baz, 2.0], [1, baz, 3.0], [1, baz, 4.0]]</pre>
* <p/>
* @param inputLists A list of lists, each inner list containing objects to be combined with objects from the
* other lists
* @param <T> The type of objects in the lists (supply {@link Object} if mixing types)
* @return Combinations of objects between the input lists
*/
public static <T> List<List<T>> generateCombinations(List<? extends Iterable<T>> inputLists) {
if (inputLists.isEmpty()) {
return Collections.emptyList();
}
List<List<T>> results = new ArrayList<List<T>>();
Iterable<T> currentList = inputLists.get(0);
if (inputLists.size() == 1) {
for (T object : currentList) {
// This is the last list in the input lists supplied - processed first due to eager recursion below.
// Add each object in this input list as a single element in its own new LinkedList.
// The other branch will subsequently add objects from preceding input lists
// to the _start_ of this LinkedList. We use LinkedList to avoid shuffling elements.
results.add(new LinkedList<T>(Collections.singleton(object)));
}
}
else {
// Start processing objects from the first input list supplied,
// but note that we will call this method recursively before we move on to the next object...
for (T object : currentList) {
// Prepare a tail list of the input lists (the input lists after this first one).
// The tail list is actually a _view_ onto the original input lists, (no data is copied)...
List<? extends Iterable<T>> tail = inputLists.subList(1, inputLists.size());
// Call this method recursively, getting the first objects in the tail lists first...
for (List<T> permutations : generateCombinations(tail)) {
// Insert the object from the first list at the _start_ of the permutations list...
permutations.add(0, object);
// As the stack unwinds, we have assembled permutations in the correct order.
// Add each permutation to results, to return to the preceding stack frame or to the caller...
results.add(permutations);
}
}
}
return results;
}
/**
* Private constructor, not used.
*/
TupleCombinationGenerator() {
}
}
| 4,430 | 46.645161 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/compound/support/CompoundQuery.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.compound.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.SimpleQuery;
import com.googlecode.cqengine.query.logical.And;
import java.util.ArrayList;
import java.util.List;
/**
* A query which wraps a {@link CompoundAttribute}, used only in the query engine's internal communication
* with a {@link com.googlecode.cqengine.index.compound.CompoundIndex}.
* <p/>
* @author Niall Gallagher
*/
public class CompoundQuery<O> implements Query<O> {
private final And<O> andQuery;
private final CompoundAttribute<O> compoundAttribute;
public CompoundQuery(And<O> andQuery, CompoundAttribute<O> compoundAttribute) {
this.andQuery = andQuery;
this.compoundAttribute = compoundAttribute;
}
/**
* {@inheritDoc}
* <p/>
* This implementation for {@link CompoundQuery} iterates each of the child {@link Equal} queries of the
* {@link And} query from which the {@link CompoundQuery} was constructed, and for each child {@link Equal} query,
* tests if the given object matches that query.
*
* @return True if the object matches all of the child {@link Equal} queries, false if the object does not match
* one or more child {@link Equal} queries
*/
@Override
public boolean matches(O object, QueryOptions queryOptions) {
for (SimpleQuery<O, ?> simpleQuery : andQuery.getSimpleQueries()) {
Equal<O, ?> equal = (Equal<O, ?>) simpleQuery;
if (!equal.matches(object, queryOptions)) {
return false;
}
}
return true;
}
public And<O> getAndQuery() {
return andQuery;
}
public CompoundAttribute<O> getCompoundAttribute() {
return compoundAttribute;
}
public CompoundValueTuple<O> getCompoundValueTuple() {
List<Object> attributeValues = new ArrayList<Object>(andQuery.getSimpleQueries().size());
for (SimpleQuery<O, ?> simpleQuery : andQuery.getSimpleQueries()) {
Equal<O, ?> equal = (Equal<O, ?>) simpleQuery;
attributeValues.add(equal.getValue());
}
return new CompoundValueTuple<O>(attributeValues);
}
public static <O> CompoundQuery<O> fromAndQueryIfSuitable(And<O> andQuery) {
if (andQuery.hasLogicalQueries() || andQuery.hasComparativeQueries()) {
return null;
}
List<Attribute<O, ?>> attributeList = new ArrayList<Attribute<O, ?>>(andQuery.getSimpleQueries().size());
for (SimpleQuery<O, ?> simpleQuery : andQuery.getSimpleQueries()) {
if (!(simpleQuery instanceof Equal)) {
return null;
}
attributeList.add(simpleQuery.getAttribute());
}
CompoundAttribute<O> compoundAttribute = new CompoundAttribute<O>(attributeList);
return new CompoundQuery<O>(andQuery, compoundAttribute);
}
}
| 3,724 | 36.626263 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/compound/support/CompoundAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.compound.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
/**
* A private implementation of {@link Attribute} used internally by
* {@link com.googlecode.cqengine.index.compound.CompoundIndex}, which groups several other attributes.
* <p/>
* Note that, being like regular {@link com.googlecode.cqengine.attribute.Attribute}s, objects of this type
* do not represent values but rather the means to obtain values from fields in an object. <i>Values</i> for compound
* attributes are encapsulated separately in {@link CompoundValueTuple} objects. The {@link Attribute#getValues(Object, com.googlecode.cqengine.query.option.QueryOptions)} method
* returns a list of these tuples for a given object.
* <p/>
* <b><u>Algorithm to generate tuples</u></b><br/>
* The list of tuples generated for a {@code CompoundAttribute} referencing a given object, depends on whether the
* {@code CompoundAttribute} groups only {@link com.googlecode.cqengine.attribute.SimpleAttribute}s, or whether it
* groups any {@link com.googlecode.cqengine.attribute.MultiValueAttribute}s.
* <ul>
* <li>
* <b>Generating tuples for a group of {@code SimpleAttribute}s</b><br/>
* If a compound attribute groups only {@link com.googlecode.cqengine.attribute.SimpleAttribute}s, then the list
* of tuples generated by the {@code CompoundAttribute} is straightforward and will contain just one tuple,
* comprising the values from each of the fields referenced by the {@code SimpleAttribute}s
* </li>
* <li>
* <b>Generating tuples for {@code MultiValueAttribute}s</b><br/>
* If a compound attribute groups one or more {@link com.googlecode.cqengine.attribute.MultiValueAttribute}s,
* then the determination of tuples is more complicated, and is as follows.
* <p/>
* {@code MultiValueAttribute}s can return multiple values from a single field in an object. The purpose of
* {@code MultiValueAttribute} is to allow an object to be indexed separately against <i>each</i> of the values
* from this field. Given that a {@code CompoundAttribute} spans multiple attributes, the presence of one or
* more {@code MultiValueAttribute}s means that <u>several possible combinations of values</u> should match the
* object in the index.
* <p/>
* To generate tuples for {@code CompoundAttribute}s spanning {@code MultiValueAttribute}s, the
* {@link Attribute#getValues(Object, com.googlecode.cqengine.query.option.QueryOptions)} method will retrieve a list of values from the object for each of the component
* attributes. It will then generate all possible combinations of values between these lists as tuples, using
* {@link TupleCombinationGenerator#generateCombinations(java.util.List)}.
* <p/>
* <u>Example:</u><br/>
* If we have the following lists of values from attributes:<br/>
* Values from first attribute: <code>1</code><br/>
* Values from second attribute: <code>"bar", "baz"</code><br/>
* Values from third attribute: <code>2.0, 3.0, 4.0</code><br/>
* The following tuples will be generated:<br/>
* <code>[[1, bar, 2.0], [1, bar, 3.0], [1, bar, 4.0], [1, baz, 2.0], [1, baz, 3.0], [1, baz, 4.0]]</code><br/>
* The {@link Attribute#getValues(Object, com.googlecode.cqengine.query.option.QueryOptions)} method would then return these tuples as a list of {@link CompoundValueTuple}
* objects
* </li>
* </ul>
*
* @author Niall Gallagher
*/
public class CompoundAttribute<O> implements Attribute<O, CompoundValueTuple<O>> {
private final List<Attribute<O, ?>> attributes;
public CompoundAttribute(List<Attribute<O, ?>> attributes) {
if (attributes.size() < 2) {
throw new IllegalStateException("Cannot create a compound index on fewer than two attributes: " + attributes.size());
}
this.attributes = attributes;
}
public int size() {
return attributes.size();
}
@Override
public Class<O> getObjectType() {
throw new UnsupportedOperationException("Method not supported by CompoundAttribute");
}
@Override
public Class<CompoundValueTuple<O>> getAttributeType() {
throw new UnsupportedOperationException("Method not supported by CompoundAttribute");
}
@Override
public String getAttributeName() {
throw new UnsupportedOperationException("Method not supported by CompoundAttribute");
}
/**
* Returns a list of {@link CompoundValueTuple} objects for the given object, containing all possible combinations
* of attribute values against which the object can be indexed.
* <p/>
* See documentation on this class itself for details of the algorithm used to generate these tuples.
*
* @param object The object from which all {@link com.googlecode.cqengine.index.compound.support.CompoundValueTuple}s are required
* @param queryOptions
* @return tuples representing all possible combinations of attribute values against which the object can be indexed
*/
@Override
public Iterable<CompoundValueTuple<O>> getValues(O object, QueryOptions queryOptions) {
// STEP 1.
// For each individual attribute comprising the compound attribute,
// ask the attribute to return a list of values for the field it references in the object.
// We get a list of values for each field because, because some fields can have multiple values,
// as supported by MultiValueAttribute. We end up with List<List<Object>>, the outer list containing
// individual lists of values from each attribute, inner lists containing values...
List<Iterable<Object>> attributeValueLists = new ArrayList<Iterable<Object>>(attributes.size());
for (Attribute<O, ?> attribute : attributes) {
@SuppressWarnings({"unchecked"})
Iterable<Object> values = (Iterable<Object>) attribute.getValues(object, queryOptions);
attributeValueLists.add(values);
}
// STEP 2.
// Generate all combinations of attribute values across these attributes.
// For example, if we have the following lists of values from attributes:
// Values for first attribute: 1
// Values for second attribute: "bar", "baz"
// Values for third attribute: 2.0, 3.0, 4.0
// ...then we should generate and index the object against the following tuples:
// [[1, bar, 2.0], [1, bar, 3.0], [1, bar, 4.0], [1, baz, 2.0], [1, baz, 3.0], [1, baz, 4.0]]
List<List<Object>> listsOfValueCombinations = TupleCombinationGenerator.generateCombinations(attributeValueLists);
// STEP 3.
// Wrap each of the unique combinations in a CompoundValueTuple object...
List<CompoundValueTuple<O>> tuples = new ArrayList<CompoundValueTuple<O>>(listsOfValueCombinations.size());
for (List<Object> valueCombination : listsOfValueCombinations) {
tuples.add(new CompoundValueTuple<O>(valueCombination));
}
// Return the list of CompoundValueTuple objects...
return tuples;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CompoundAttribute)) return false;
CompoundAttribute that = (CompoundAttribute) o;
if (!attributes.equals(that.attributes)) return false;
return true;
}
@Override
public int hashCode() {
return attributes.hashCode();
}
@Override
public String toString() {
return "CompoundAttribute{" +
"attributes=" + attributes +
'}';
}
}
| 8,521 | 48.260116 | 179 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/IdentityAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.AttributeIndex;
/**
* Implemented by indexes which persist serialized objects directly in the index instead of persisting foreign keys.
*
* @author niall.gallagher
*/
public interface IdentityAttributeIndex<A, O> extends AttributeIndex<A, O> {
/**
* Returns an attribute which given a primary key of a stored object can read (deserialize) the corresponding
* object from the identity index. This is called a foreign key attribute, because typically those keys will
* be stored in other indexes, referring to the primary keys of this index.
*/
SimpleAttribute<A, O> getForeignKeyAttribute();
}
| 1,373 | 38.257143 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/RequestScopeConnectionManager.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.support.DBUtils;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.composite.CompositePersistence;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.io.Closeable;
import java.sql.Connection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A ConnectionManager which create connections on-demand to the correct persistence for the indexes requesting the
* connection, and subsequently caches the connections, for re-use within the scope of the same request into CQEngine.
* <p/>
* Opens only one connection to each persistence, and returns the same already-open connection for subsequent requests.
* <p/>
* Connections are obtained from the {@link Persistence} object provided to the constructor.
* This can be a {@link CompositePersistence} which actually wraps more than one backing persistence.
* In that case, the {@link CompositePersistence#getPersistenceForIndex(Index)} method will be used to locate the
* correct persistence to use for the index requesting the connection.
*
* @author niall.gallagher
*/
public class RequestScopeConnectionManager implements ConnectionManager, Closeable {
final Persistence<?, ?> persistence;
// Map of open connections.
final ConcurrentMap<SQLitePersistence, Connection> openConnections = new ConcurrentHashMap<SQLitePersistence, Connection>(1, 1.0F, 1);
public RequestScopeConnectionManager(Persistence<?, ?> persistence) {
this.persistence = persistence;
}
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
index = index.getEffectiveIndex();
SQLitePersistence<?, ?> persistence = getPersistenceForIndex(index);
Connection connection = openConnections.get(persistence);
if (connection == null) {
Connection newConnection = persistence.getConnection(index, queryOptions);
Connection existingConnection = openConnections.putIfAbsent(persistence, newConnection);
if (existingConnection == null) {
connection = newConnection;
// Disable auto-commit so that all operations will be done in a transaction we control explicitly...
DBUtils.setAutoCommit(connection, false);
}
else {
// Close the new connection and return the existing one...
DBUtils.closeQuietly(newConnection);
connection = existingConnection;
}
}
return connection;
}
/**
* Commits the transactions on the open connections to all persistences, then closes the connections.
*/
public void close() {
for (Iterator<Connection> iterator = openConnections.values().iterator(); iterator.hasNext(); ) {
Connection connection = iterator.next();
DBUtils.commit(connection);
DBUtils.closeQuietly(connection);
iterator.remove();
}
}
@SuppressWarnings("unchecked")
SQLitePersistence getPersistenceForIndex(Index<?> index) {
if (persistence instanceof SQLitePersistence) {
if (persistence.supportsIndex((Index)index)) {
return (SQLitePersistence) persistence;
}
}
else if (persistence instanceof CompositePersistence) {
CompositePersistence compositePersistence = ((CompositePersistence) persistence);
Persistence indexPersistence = compositePersistence.getPersistenceForIndex(index);
if (indexPersistence instanceof SQLitePersistence) {
return (SQLitePersistence) indexPersistence;
}
}
throw new IllegalStateException("No configured Persistence implementation can support the given index: " + index);
}
@Override
public boolean isApplyUpdateForIndexEnabled(Index<?> index) {
return true;
}
}
| 4,741 | 41.720721 | 138 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/PartialSQLiteIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.PartialIndex;
import com.googlecode.cqengine.index.support.PartialSortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.NonHeapTypeIndex;
import com.googlecode.cqengine.query.Query;
import static com.googlecode.cqengine.index.sqlite.support.DBUtils.sanitizeForTableName;
/**
* A {@link PartialIndex} backed by a {@link SQLiteIndex}.
*
* @author niall.gallagher
*/
public class PartialSQLiteIndex<A extends Comparable<A>, O, K> extends PartialSortedKeyStatisticsAttributeIndex<A, O> implements NonHeapTypeIndex {
final SimpleAttribute<O, K> primaryKeyAttribute;
final SimpleAttribute<K, O> foreignKeyAttribute;
final String tableNameSuffix;
/**
* Protected constructor, called by subclasses.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param primaryKeyAttribute The {@link SimpleAttribute} used to retrieve the primary key.
* @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialSQLiteIndex(Attribute<O, A> attribute,
SimpleAttribute<O, K> primaryKeyAttribute,
SimpleAttribute<K, O> foreignKeyAttribute,
Query<O> filterQuery) {
super(attribute, filterQuery);
this.primaryKeyAttribute = primaryKeyAttribute;
this.foreignKeyAttribute = foreignKeyAttribute;
this.tableNameSuffix = "_partial_" + sanitizeForTableName(filterQuery.toString());
}
@Override
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
protected SortedKeyStatisticsAttributeIndex<A, O> createBackingIndex() {
return new SQLiteIndex(attribute, primaryKeyAttribute, foreignKeyAttribute, tableNameSuffix) {
@Override
public Index getEffectiveIndex() {
return PartialSQLiteIndex.this.getEffectiveIndex();
}
};
}
// ---------- Static factory methods to create PartialSQLiteIndex ----------
/**
* Creates a new {@link PartialSQLiteIndex}.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param primaryKeyAttribute The {@link SimpleAttribute} used to retrieve the primary key.
* @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
* @param <A> The type of the attribute.
* @param <O> The type of the object containing the attributes.
* @param <K> The type of the object key.
* @return a new instance of the {@link SQLiteIndex}
*/
public static <A extends Comparable<A>, O, K> PartialSQLiteIndex<A, O, K> onAttributeWithFilterQuery(Attribute<O, A> attribute,
SimpleAttribute<O, K> primaryKeyAttribute,
SimpleAttribute<K, O> foreignKeyAttribute,
Query<O> filterQuery) {
return new PartialSQLiteIndex<A, O, K>(attribute, primaryKeyAttribute, foreignKeyAttribute, filterQuery);
}
}
| 4,456 | 48.522222 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/SimplifiedSQLiteIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.engine.QueryEngine;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.support.indextype.NonHeapTypeIndex;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* An abstract class which wraps a {@link SQLiteIndex}, and simplifies some of its configuration options to make it
* easier to use with IndexedCollections which themselves are persistent.
* <p/>
* The primary key to be used, and the database to connect to, is obtained from the IndexedCollection.
*
* @author niall.gallagher
*/
public abstract class SimplifiedSQLiteIndex<A extends Comparable<A>, O, K extends Comparable<K>> implements SortedKeyStatisticsAttributeIndex<A, O>, NonHeapTypeIndex {
final Class<? extends SQLitePersistence> persistenceType;
final Attribute<O, A> attribute;
final String tableNameSuffix;
volatile SQLiteIndex<A, O, K> backingIndex;
protected SimplifiedSQLiteIndex(Class<? extends SQLitePersistence<O, A>> persistenceType, Attribute<O, A> attribute, String tableNameSuffix) {
this.persistenceType = persistenceType;
this.attribute = attribute;
this.tableNameSuffix = tableNameSuffix;
}
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
Persistence<O, K> persistence = SimplifiedSQLiteIndex.<O, K>getPersistenceFromQueryOptions(queryOptions);
QueryEngine<O> queryEngine = getQueryEngineFromQueryOptions(queryOptions);
final SimpleAttribute<O, K> primaryKeyAttribute = getPrimaryKeyFromPersistence(persistence);
final AttributeIndex<K, O> primaryKeyIndex = getPrimaryKeyIndexFromQueryEngine(primaryKeyAttribute, queryEngine, queryOptions);
final SimpleAttribute<K, O> foreignKeyAttribute = new SimpleAttribute<K, O>(primaryKeyAttribute.getAttributeType(), primaryKeyAttribute.getObjectType()) {
@Override
public O getValue(K primaryKeyValue, QueryOptions queryOptions) {
return primaryKeyIndex.retrieve(QueryFactory.equal(primaryKeyAttribute, primaryKeyValue), queryOptions).uniqueResult();
}
};
backingIndex = new SQLiteIndex<A, O, K>(this.attribute, primaryKeyAttribute, foreignKeyAttribute, tableNameSuffix) {
// Override getEffectiveIndex() in the backing index to return a reference to this index...
@Override
public Index<O> getEffectiveIndex() {
return SimplifiedSQLiteIndex.this.getEffectiveIndex();
}
};
backingIndex.init(objectStore, queryOptions);
}
/**
* Calls {@link SQLiteIndex#destroy(QueryOptions)} on the wrapped index.
*
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
backingIndex().destroy(queryOptions);
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
static <O, K extends Comparable<K>> Persistence<O, K> getPersistenceFromQueryOptions(QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
Persistence<O, K> persistence = (Persistence<O, K>) queryOptions.get(Persistence.class);
if (persistence == null) {
throw new IllegalStateException("A required Persistence object was not supplied in query options");
}
return persistence;
}
static <O> QueryEngine<O> getQueryEngineFromQueryOptions(QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
QueryEngine<O> queryEngine = (QueryEngine<O>) queryOptions.get(QueryEngine.class);
if (queryEngine == null) {
throw new IllegalStateException("The QueryEngine was not supplied in query options");
}
return queryEngine;
}
SimpleAttribute<O, K> getPrimaryKeyFromPersistence(Persistence<O, K> persistence) {
SimpleAttribute<O, K> primaryKey = persistence.getPrimaryKeyAttribute();
if (primaryKey == null) {
throw new IllegalStateException("This index " + getClass().getSimpleName() + " on attribute '" + attribute.getAttributeName() + "' cannot be added to the IndexedCollection, because the configured persistence was not configured with a primary key attribute.");
}
return primaryKey;
}
AttributeIndex<K, O> getPrimaryKeyIndexFromQueryEngine(SimpleAttribute<O, K> primaryKeyAttribute, QueryEngine<O> queryEngine, QueryOptions queryOptions) {
for (Index<O> index : queryEngine.getIndexes()) {
if (index instanceof AttributeIndex) {
@SuppressWarnings("unchecked")
AttributeIndex<K, O> attributeIndex = (AttributeIndex<K, O>) index;
if (primaryKeyAttribute.equals(attributeIndex.getAttribute())) {
return attributeIndex;
}
}
}
throw new IllegalStateException("This index " + getClass().getSimpleName() + " on attribute '" + attribute.getAttributeName() + "' cannot be added to the IndexedCollection yet, because it requires that an index on the primary key to be added first.");
}
SQLiteIndex<A, O, K> backingIndex() {
SQLiteIndex<A, O, K> backingIndex = this.backingIndex;
if (backingIndex == null) {
throw new IllegalStateException("This index can only be used after it has been added to an IndexedCollection");
}
return backingIndex;
}
@Override
public Attribute<O, A> getAttribute() {
return attribute;
}
@Override
public boolean isMutable() {
return true;
}
// The following methods were mostly auto-generated using IntelliJ: Code -> Generate -> Delegate Methods...
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return backingIndex().supportsQuery(query, queryOptions);
}
@Override
public boolean isQuantized() {
return backingIndex().isQuantized();
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
return backingIndex().retrieve(query, queryOptions);
}
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
return backingIndex().addAll(objectSet, queryOptions);
}
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
return backingIndex().removeAll(objectSet, queryOptions);
}
@Override
public void clear(QueryOptions queryOptions) {
backingIndex().clear(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getDistinctKeys(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions) {
return backingIndex().getDistinctKeysDescending(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getDistinctKeysDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return backingIndex().getCountForKey(key, queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(QueryOptions queryOptions) {
return backingIndex().getStatisticsForDistinctKeysDescending(queryOptions);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getStatisticsForDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions) {
return backingIndex().getKeysAndValues(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getKeysAndValues(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
return backingIndex().getKeysAndValuesDescending(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getKeysAndValuesDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SimplifiedSQLiteIndex that = (SimplifiedSQLiteIndex) o;
if (!attribute.equals(that.attribute)) return false;
return true;
}
@Override
public int hashCode() {
int result = getClass().hashCode();
result = 31 * result + attribute.hashCode();
return result;
}
}
| 10,985 | 41.253846 | 271 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/SQLiteIdentityIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.persistence.support.serialization.PersistenceConfig;
import com.googlecode.cqengine.persistence.support.serialization.PojoSerializer;
import com.googlecode.cqengine.index.support.CloseableIterable;
import com.googlecode.cqengine.index.support.KeyStatistics;
import com.googlecode.cqengine.index.support.KeyValue;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.NonHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.lang.reflect.Constructor;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* An index which allows objects to be persisted directly in the index in serialized form, and to be accessed using a
* primary key attribute (as obtained from a foreign key held elsewhere).
* <p/>
* This index actually wraps an {@link SQLiteIndex}, but configures the value that it stores for each primary key, to
* be the actual serialized bytes of the object which has that key.
*
* @author niall.gallagher
*/
public class SQLiteIdentityIndex<A extends Comparable<A>, O> implements IdentityAttributeIndex<A, O>, SortedKeyStatisticsAttributeIndex<A, O>, NonHeapTypeIndex {
final SQLiteIndex<A, O, byte[]> sqLiteIndex;
final Class<O> objectType;
final SimpleAttribute<O, A> primaryKeyAttribute;
final SimpleAttribute<A, O> foreignKeyAttribute;
final PojoSerializer<O> pojoSerializer;
public SQLiteIdentityIndex(final SimpleAttribute<O, A> primaryKeyAttribute) {
this.sqLiteIndex = new SQLiteIndex<A, O, byte[]>(
primaryKeyAttribute,
new SerializingAttribute(primaryKeyAttribute.getObjectType(), byte[].class),
new DeserializingAttribute(byte[].class, primaryKeyAttribute.getObjectType()),
"") {
// Override getEffectiveIndex() in the SQLiteIndex to return a reference to this index...
@Override
public Index<O> getEffectiveIndex() {
return SQLiteIdentityIndex.this.getEffectiveIndex();
}
};
this.objectType = primaryKeyAttribute.getObjectType();
this.primaryKeyAttribute = primaryKeyAttribute;
this.foreignKeyAttribute = new ForeignKeyAttribute();
this.pojoSerializer = createSerializer(objectType);
}
public SimpleAttribute<A, O> getForeignKeyAttribute() {
return foreignKeyAttribute;
}
/**
* Returns the attribute which given an object can read its primary key.
*/
@Override
public Attribute<O, A> getAttribute() {
return sqLiteIndex.getAttribute();
}
@Override
public boolean isMutable() {
return sqLiteIndex.isMutable();
}
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return sqLiteIndex.supportsQuery(query, queryOptions);
}
@Override
public boolean isQuantized() {
return sqLiteIndex.isQuantized();
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
return sqLiteIndex.retrieve(query, queryOptions);
}
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
return sqLiteIndex.addAll(objectSet, queryOptions);
}
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
return sqLiteIndex.removeAll(objectSet, queryOptions);
}
@Override
public void clear(QueryOptions queryOptions) {
sqLiteIndex.clear(queryOptions);
}
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
sqLiteIndex.init(objectStore, queryOptions);
}
/**
* Calls {@link SQLiteIndex#destroy(QueryOptions)} on the wrapped index.
*
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
sqLiteIndex.destroy(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions) {
return sqLiteIndex.getDistinctKeys(queryOptions);
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return sqLiteIndex.getCountForKey(key, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return sqLiteIndex.getDistinctKeys(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions) {
return sqLiteIndex.getDistinctKeysDescending(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return sqLiteIndex.getDistinctKeysDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(QueryOptions queryOptions) {
return sqLiteIndex.getStatisticsForDistinctKeysDescending(queryOptions);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return sqLiteIndex.getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return sqLiteIndex.getStatisticsForDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions) {
return sqLiteIndex.getKeysAndValues(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return sqLiteIndex.getKeysAndValues(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
return sqLiteIndex.getKeysAndValuesDescending(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return sqLiteIndex.getKeysAndValuesDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SQLiteIdentityIndex that = (SQLiteIdentityIndex) o;
if (!primaryKeyAttribute.equals(that.primaryKeyAttribute)) return false;
return true;
}
@Override
public int hashCode() {
int result = getClass().hashCode();
result = 31 * result + primaryKeyAttribute.hashCode();
return result;
}
@SuppressWarnings("unchecked")
static <O> PojoSerializer<O> createSerializer(Class<O> objectType) {
Class<? extends PojoSerializer> serializerClass = null;
try {
// Read the configured serializer from the @PersistenceConfig annotation...
PersistenceConfig persistenceConfig = objectType.getAnnotation(PersistenceConfig.class);
if (persistenceConfig == null) {
persistenceConfig = PersistenceConfig.DEFAULT_CONFIG;
}
serializerClass = persistenceConfig.serializer();
// Instantiate the serializer, supplying the parameters to its (objectType, persistenceConfig) constructor...
Constructor constructor = serializerClass.getConstructor(Class.class, PersistenceConfig.class);
Object serializerInstance = constructor.newInstance(objectType, persistenceConfig);
return (PojoSerializer<O>) serializerInstance;
}
catch (Exception e) {
throw new IllegalStateException("Failed to instantiate PojoSerializer: " + serializerClass, e);
}
}
class SerializingAttribute extends SimpleAttribute<O, byte[]> {
public SerializingAttribute(Class<O> objectType, Class<byte[]> attributeType) {
super(objectType, attributeType);
}
@Override
public byte[] getValue(O object, QueryOptions queryOptions) {
if (object == null) {
throw new NullPointerException("Object was null");
}
try {
return pojoSerializer.serialize(object);
}
catch (Exception e) {
throw new IllegalStateException("Failed to serialize object, object type: " + objectType, e);
}
}
}
class DeserializingAttribute extends SimpleAttribute<byte[], O> {
public DeserializingAttribute(Class<byte[]> objectType, Class<O> attributeType) {
super(objectType, attributeType);
}
@Override
public O getValue(byte[] bytes, QueryOptions queryOptions) {
return pojoSerializer.deserialize(bytes);
}
}
/**
* An attribute which given a primary key (or a foreign key to it) can read the corresponding
* object from this index.
*/
class ForeignKeyAttribute extends SimpleAttribute<A, O> {
public ForeignKeyAttribute() {
super(primaryKeyAttribute.getAttributeType(), objectType, ForeignKeyAttribute.class.getSimpleName() + "_" + primaryKeyAttribute.getAttributeName());
}
@Override
public O getValue(A foreignKey, QueryOptions queryOptions) {
return SQLiteIdentityIndex.this.retrieve(equal(primaryKeyAttribute, foreignKey), noQueryOptions()).uniqueResult();
}
}
/**
* Creates a new {@link SQLiteIdentityIndex} for the given primary key attribute.
*
* @param primaryKeyAttribute The {@link SimpleAttribute} representing a primary key on which the index will be built.
* @param <A> The type of the attribute.
* @param <O> The type of the object containing the attributes.
* @return a new instance of a standalone {@link SQLiteIdentityIndex}
*/
public static <A extends Comparable<A>, O> SQLiteIdentityIndex<A, O> onAttribute(final SimpleAttribute<O, A> primaryKeyAttribute) {
return new SQLiteIdentityIndex<A, O>(primaryKeyAttribute);
}
}
| 11,850 | 38.372093 | 176 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/SQLitePersistence.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.sql.Connection;
/**
* An {@link Persistence} which persists to a SQLite database.
*
* @author Silvano Riz
*/
public interface SQLitePersistence<O, A extends Comparable<A>> extends Persistence<O, A> {
/**
* Returns a {@link Connection} to the SQLite database used for persistence.
*
* @param index The {@link Index} requesting the connection.
* @param queryOptions The query options for the request
* @return The {@link Connection}
*/
Connection getConnection(Index<?> index, QueryOptions queryOptions);
/**
* @return The number of bytes used to persist the collection and/or indexes.
*/
long getBytesUsed();
/**
* Compacts the underlying persistence, which returns unused memory or disk space to the operating system.
*/
void compact();
/**
* Expands the underlying persistence by the given number of bytes in a single operation. This will usually result
* in the persistence being expanded into an additional contiguous chunk of memory or region on disk.
* <p/>
* After this method returns, the operating system will report that the memory or disk space used for persistence
* has increased by this amount, but internally the space will simply be reserved for future use. The reserved space
* will be used to store objects added to the collection subsequently, without needing to request more memory from
* the OS ad-hoc.
* <p/>
* This can reduce fragmentation of the persistence file on some OS filesystems, especially if used prior to bulk
* imports when the persistence is on a non-SSD disk.
*/
void expand(long numBytes);
/**
* Creates a {@link SQLiteIdentityIndex} which persists objects in this persistence.
* @return a {@link SQLiteIdentityIndex} which persists objects in this persistence.
*/
SQLiteIdentityIndex<A, O> createIdentityIndex();
}
| 2,746 | 37.690141 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/SimpleConnectionManager.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.sql.Connection;
/**
* An implementation of {@link ConnectionManager} which wraps a single connection.
*/
public class SimpleConnectionManager implements ConnectionManager {
final Connection connection;
public SimpleConnectionManager(Connection connection) {
this.connection = connection;
}
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
return connection;
}
@Override
public boolean isApplyUpdateForIndexEnabled(Index<?> index) {
return true;
}
}
| 1,320 | 29.022727 | 82 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/SQLiteIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.MultiValueAttribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.index.sqlite.support.DBQueries;
import com.googlecode.cqengine.index.sqlite.support.DBUtils;
import com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags;
import com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags.BulkImportExternallyManged;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.support.indextype.NonHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.FlagsEnabled;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.*;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import com.googlecode.cqengine.index.support.CloseableRequestResources.CloseableResourceGroup;
import org.sqlite.SQLiteConfig;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Iterator;
import static com.googlecode.cqengine.index.sqlite.support.DBQueries.Row;
import static com.googlecode.cqengine.index.sqlite.support.DBUtils.sanitizeForTableName;
import static com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags.BulkImportExternallyManged.LAST;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* An index backed by a table in a SQLite database.
* <p>
* This index is highly configurable, and forms the basis for other simpler indexes: {@link SQLiteIdentityIndex},
* {@link OffHeapIndex} and {@link DiskIndex}.
* </p>
* <p>
* Specifically, this index allows details of the database to which data should be persisted, to be supplied by the
* application on-the-fly in request-scope via {@link QueryOptions}, as an alternative to configuring a
* particular database statically.
* </p>
* <p>
* This is useful in applications where CQEngine does not create/destroy or
* manage the life cycle of the database itself, and so where the application requires tight control over how
* the database is accessed.
* </p>
* <p>
* <i>In applications where CQEngine manages the SQLite database, users should probably not use this
* index directly, but should use one of the simpler indexes mentioned above instead.</i>
* </p>
* <h1>
* Index implementation
* </h1>
* This index is persisted in a SQLite table with the following schema:
* <pre>
* CREATE TABLE ${table_name} (
* objectKey ${objectKey_type},
* value ${value_type},
* PRIMARY KEY (objectKey, value)
* ) WITHOUT ROWID;
*
* CREATE INDEX idx_${table}_value ON ${table} (value);
* </pre>
* Where:<br>
* <ul>
* <li>
* <i>table_name</i> is the name of the table.
* The name of the attribute (on which the index will be built) is used to name the table. A "cqtbl_" string
* will be prefixed and all the non alpha-numeric chars will be stripped out.
* </li>
* <li>
* <i>objectKey</i> stores the value from the {@code primaryKeyAttribute} for each object stored
* (generic type {@code K}).
* If the primary key is configured as {@code Car.CAR_ID} then this column will hold the carId.
* The type of the primary key attribute will be converted to the corresponding database type.
* </li>
* <li>
* <i>value</i> is the type of the indexed value (generic type {@code A}).
* If the index is built on an attribute {@code Car.MODEL}, then this will hold the car model string.
* The type of the attribute on which the index is built will be converted to the corresponding database
* type.
* </li>
* <li>
* Note that this index supports {@link MultiValueAttribute}, which means there may be more than one value for each
* objecyKey.
* </li>
* </ul>
* @author Silvano Riz
*/
public class SQLiteIndex<A extends Comparable<A>, O, K> extends AbstractAttributeIndex<A, O> implements SortedKeyStatisticsAttributeIndex<A, O>, NonHeapTypeIndex {
static final int INDEX_RETRIEVAL_COST = 80;
static final int INDEX_RETRIEVAL_COST_FILTERING = INDEX_RETRIEVAL_COST + 1;
// System property to force preexisting disk/off-heap indexes to be re-initialized (re-synced with the collection)
// at startup.
// The recommended and default setting is false. Setting this true forces old behavior of CQEngine <= 2.10.0.
static final boolean FORCE_REINIT_OF_PREEXISTING_INDEXES = Boolean.getBoolean("cqengine.reinit.preexisting.indexes");
final String tableName;
final SimpleAttribute<O, K> primaryKeyAttribute;
final SimpleAttribute<K, O> foreignKeyAttribute;
SQLiteConfig.SynchronousMode pragmaSynchronous;
SQLiteConfig.JournalMode pragmaJournalMode;
boolean canModifySyncAndJournaling;
/**
* Constructor. Note the index should normally be created via the static factory methods instead.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param primaryKeyAttribute The {@link SimpleAttribute} with which the index will retrieve the object key.
* @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
* @param tableNameSuffix An optional string to append the end of the table name used by this index;
* This can be an empty string, but cannot be null; If not an empty string, the string
* should only contain characters suitable for use in a SQLite table name; therefore see
* {@link DBUtils#sanitizeForTableName(String)}
*/
public SQLiteIndex(final Attribute<O, A> attribute,
final SimpleAttribute<O, K> primaryKeyAttribute,
final SimpleAttribute<K, O> foreignKeyAttribute,
final String tableNameSuffix) {
super(attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
add(LessThan.class);
add(GreaterThan.class);
add(Between.class);
add(StringStartsWith.class);
add(Has.class);
}});
this.tableName = sanitizeForTableName(attribute.getAttributeName()) + tableNameSuffix;
this.primaryKeyAttribute = primaryKeyAttribute;
this.foreignKeyAttribute = foreignKeyAttribute;
}
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return query instanceof FilterQuery || super.supportsQuery(query, queryOptions);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
if (query instanceof FilterQuery){
@SuppressWarnings("unchecked")
final FilterQuery<O, A> filterQuery = (FilterQuery<O, A>)query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
final Connection searchConnection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
final java.sql.ResultSet searchResultSet = DBQueries.getAllIndexEntries(tableName, searchConnection);
closeableResourceGroup.add(DBUtils.wrapAsCloseable(searchResultSet));
return new LazyIterator<O>() {
@Override
protected O computeNext() {
try {
while (true) {
if (!searchResultSet.next()) {
close();
return endOfData();
}
final K objectKey = DBUtils.getValueFromResultSet(1, searchResultSet, primaryKeyAttribute.getAttributeType());
final A objectValue = DBUtils.getValueFromResultSet(2, searchResultSet, attribute.getAttributeType());
if (filterQuery.matchesValue(objectValue, queryOptions)) {
return foreignKeyAttribute.getValue(objectKey, queryOptions);
}
}
} catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
};
}
@Override
public boolean contains(O object) {
Connection connection = null;
java.sql.ResultSet searchResultSet = null;
try {
connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
searchResultSet = DBQueries.getIndexEntryByObjectKey(primaryKeyAttribute.getValue(object, queryOptions), tableName, connection);
return lazyMatchingValuesIterable(searchResultSet).iterator().hasNext();
}finally {
DBUtils.closeQuietly(searchResultSet);
}
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST_FILTERING;// choose between indexes
}
@Override
public int getMergeCost() {
//choose between branches.
final Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
return DBQueries.count(has(primaryKeyAttribute), tableName, connection); // no need to eliminate duplicates
}
@Override
public int size() {
Connection connection = null;
java.sql.ResultSet searchResultSet = null;
try {
connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
searchResultSet = DBQueries.getAllIndexEntries(tableName, connection);
final Iterable<K> iterator = lazyMatchingValuesIterable(searchResultSet);
return IteratorUtil.countElements(iterator);
}finally {
DBUtils.closeQuietly(searchResultSet);
}
}
@Override
public void close() {
closeableResourceGroup.close();
}
// Method to retrieve all the distinct keys for the matching values from the index. Used in count and contains
Iterable<K> lazyMatchingValuesIterable(final java.sql.ResultSet searchResultSet) {
return new Iterable<K>() {
@Override
public Iterator<K> iterator() {
return new LazyIterator<K>() {
K currentKey = null;
@Override
protected K computeNext() {
try {
while (true) {
if (!searchResultSet.next()) {
close();
return endOfData();
}
final K objectKey = DBUtils.getValueFromResultSet(1, searchResultSet, primaryKeyAttribute.getAttributeType());
if (currentKey == null || !currentKey.equals(objectKey)) {
final A objectValue = DBUtils.getValueFromResultSet(2, searchResultSet, attribute.getAttributeType());
if (filterQuery.matchesValue(objectValue, queryOptions)) {
currentKey = objectKey;
return objectKey;
}
}
}
} catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
};
}
};
}
};
}else {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
final Connection searchConnection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
final java.sql.ResultSet searchResultSet = DBQueries.search(query, tableName, searchConnection); // eliminates duplicates
closeableResourceGroup.add(DBUtils.wrapAsCloseable(searchResultSet));
return new LazyIterator<O>() {
@Override
protected O computeNext() {
try {
if (!searchResultSet.next()) {
close();
return endOfData();
}
final K objectKey = DBUtils.getValueFromResultSet(1, searchResultSet, primaryKeyAttribute.getAttributeType());
return foreignKeyAttribute.getValue(objectKey, queryOptions);
} catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
};
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
final Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
return DBQueries.count(query, tableName, connection); // no need to eliminate duplicates
}
@Override
public boolean contains(O object) {
final K objectKey = primaryKeyAttribute.getValue(object, queryOptions);
final Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
return DBQueries.contains(objectKey, query, tableName, connection);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
final Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
boolean attributeHasAtMostOneValue = (attribute instanceof SimpleAttribute || attribute instanceof SimpleNullableAttribute);
boolean queryIsADisjointInQuery = query instanceof In && ((In) query).isDisjoint();
if (queryIsADisjointInQuery || attributeHasAtMostOneValue) {
return DBQueries.count(query, tableName, connection); // No need to eliminates duplicates
}else{
return DBQueries.countDistinct(query, tableName, connection); // eliminates duplicates
}
}
@Override
public void close() {
closeableResourceGroup.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
}
/**
* {@inheritDoc}
* <p/>
* Note objects can be imported into this index rapidly via this method,
* by setting flag {@link SQLiteIndexFlags#BULK_IMPORT}. See documentation on that flag for details and caveats.
*/
@Override
public boolean addAll(final ObjectSet<O> objectSet, final QueryOptions queryOptions) {
return doAddAll(objectSet, queryOptions, false);
}
boolean doAddAll(final ObjectSet<O> objectSet, final QueryOptions queryOptions, boolean isInit) {
try {
ConnectionManager connectionManager = getConnectionManager(queryOptions);
if (!connectionManager.isApplyUpdateForIndexEnabled(this)) {
return false;
}
final Connection connection = connectionManager.getConnection(this, queryOptions);
if (!FORCE_REINIT_OF_PREEXISTING_INDEXES) {
if (isInit && DBQueries.indexTableExists(tableName, connection)) {
// init() was called, but index table already exists. Skip initializing it...
return false;
}
}
// Create table if it doesn't exists...
DBQueries.createIndexTable(tableName, primaryKeyAttribute.getAttributeType(), getAttribute().getAttributeType(), connection);
// Handle the SQLite indexes on the table
final BulkImportExternallyManged bulkImportExternallyManged = queryOptions.get(BulkImportExternallyManged.class);
final boolean isBulkImport = bulkImportExternallyManged == null && FlagsEnabled.isFlagEnabled(queryOptions, SQLiteIndexFlags.BULK_IMPORT);
final boolean isSuspendSyncAndJournaling = FlagsEnabled.isFlagEnabled(queryOptions, SQLiteIndexFlags.BULK_IMPORT_SUSPEND_SYNC_AND_JOURNALING);
if ((bulkImportExternallyManged != null || isBulkImport) && !objectSet.isEmpty()) {
// Drop the SQLite index temporarily (if any) to speed up bulk import...
DBQueries.dropIndexOnTable(tableName, connection);
if (isSuspendSyncAndJournaling) {
if (!canModifySyncAndJournaling) {
throw new IllegalStateException("Cannot suspend sync and journaling because it was not possible to read the original 'synchronous' and 'journal_mode' pragmas during the index initialization.");
}
DBQueries.suspendSyncAndJournaling(connection);
} else if (canModifySyncAndJournaling) {
// Explicitly (re-)set the configured sync and journaling settings,
// because we performed some DDL operations above. Because, it seems performing some
// DDL operations can cause the previous sync and journaling settings settings to be lost.
// For more details see: https://github.com/npgall/cqengine/issues/227
DBQueries.setSyncAndJournaling(connection, pragmaSynchronous, pragmaJournalMode);
}
} else {
// Not a bulk import, create indexes...
DBQueries.createIndexOnTable(tableName, connection);
if (canModifySyncAndJournaling) {
// Explicitly (re-)set the configured sync and journaling settings,
// because we performed some DDL operations above. Because, it seems performing some
// DDL operations can cause the previous sync and journaling settings settings to be lost.
// For more details see: https://github.com/npgall/cqengine/issues/227
DBQueries.setSyncAndJournaling(connection, pragmaSynchronous, pragmaJournalMode);
}
}
Iterable<Row<K, A>> rows = rowIterable(objectSet, primaryKeyAttribute, getAttribute(), queryOptions);
final int rowsModified = DBQueries.bulkAdd(rows, tableName, connection);
if (isBulkImport || LAST.equals(bulkImportExternallyManged)) {
// Bulk import finished, recreate the SQLite index...
DBQueries.createIndexOnTable(tableName, connection);
if (isSuspendSyncAndJournaling) {
DBQueries.setSyncAndJournaling(connection, pragmaSynchronous, pragmaJournalMode);
}
}
return rowsModified > 0;
}
finally {
objectSet.close();
}
}
/**
* Utility method that transforms an {@link Iterable} of domain objects into {@link Row}s composed by object id and
* respective value.
*
* @param objects {@link Iterable} of domain objects.
* @param primaryKeyAttribute {@link SimpleAttribute} used to retrieve the object id.
* @param indexAttribute {@link Attribute} used to retrieve the value(s).
* @param queryOptions The {@link QueryOptions}.
* @return {@link Iterable} of {@link Row}s.
*/
static <O, K, A> Iterable<Row< K, A>> rowIterable(final Iterable<O> objects,
final SimpleAttribute<O, K> primaryKeyAttribute,
final Attribute<O, A> indexAttribute,
final QueryOptions queryOptions){
return new Iterable<Row<K, A>>() {
@Override
public Iterator<Row<K, A>> iterator() {
return new LazyIterator<Row<K, A>>() {
final Iterator<O> objectIterator = objects.iterator();
Iterator<A> valuesIterator = null;
K currentObjectKey;
Row<K, A> next;
@Override
protected Row<K, A> computeNext() {
while(computeNextOrNull()){
if (next!=null)
return next;
}
return endOfData();
}
boolean computeNextOrNull(){
if (valuesIterator == null || !valuesIterator.hasNext()){
if (objectIterator.hasNext()){
O next = objectIterator.next();
currentObjectKey = primaryKeyAttribute.getValue(next, queryOptions);
valuesIterator = indexAttribute.getValues(next, queryOptions).iterator();
}else{
return false;
}
}
if (valuesIterator.hasNext()){
next = new Row<K, A>(currentObjectKey, valuesIterator.next());
return true;
}else{
next = null;
return true;
}
}
};
}
};
}
@Override
public boolean removeAll(final ObjectSet<O> objectSet, final QueryOptions queryOptions) {
try {
ConnectionManager connectionManager = getConnectionManager(queryOptions);
if (!connectionManager.isApplyUpdateForIndexEnabled(this)) {
return false;
}
final Connection connection = connectionManager.getConnection(this, queryOptions);
final boolean isBulkImport = queryOptions.get(BulkImportExternallyManged.class) != null || FlagsEnabled.isFlagEnabled(queryOptions, SQLiteIndexFlags.BULK_IMPORT);
if (isBulkImport) {
// It's a bulk import, avoid creating the index on the SQLite table...
DBQueries.createIndexTable(tableName, primaryKeyAttribute.getAttributeType(), getAttribute().getAttributeType(), connection);
}
else {
// It's NOT a bulk import, create both table and index on the table...
createTableIndexIfNeeded(connection);
}
Iterable<K> objectKeys = objectKeyIterable(objectSet, primaryKeyAttribute, queryOptions);
if (canModifySyncAndJournaling) {
// Explicitly (re-)set the configured sync and journaling settings,
// because we performed some DDL operations above. Because, it seems performing some
// DDL operations can cause the previous sync and journaling settings settings to be lost.
// For more details see: https://github.com/npgall/cqengine/issues/227
DBQueries.setSyncAndJournaling(connection, pragmaSynchronous, pragmaJournalMode);
}
int rowsModified = DBQueries.bulkRemove(objectKeys, tableName, connection);
return rowsModified > 0;
}
finally {
objectSet.close();
}
}
/**
* Utility method that transforms an {@link Iterable} of domain objects into an {@link Iterable} over the objects ids.
*
* @param objects {@link Iterable} of domain objects.
* @param primaryKeyAttribute {@link SimpleAttribute} used to retrieve the object id.
* @param queryOptions The {@link QueryOptions}.
* @return {@link Iterable} over the objects ids.
*/
static <O, K> Iterable<K> objectKeyIterable(final Iterable<O> objects,
final SimpleAttribute<O, K> primaryKeyAttribute,
final QueryOptions queryOptions){
return new Iterable<K>() {
@Override
public Iterator<K> iterator() {
return new UnmodifiableIterator<K>() {
final Iterator<O> iterator = objects.iterator();
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public K next() {
O next = iterator.next();
return primaryKeyAttribute.getValue(next, queryOptions);
}
};
}
};
}
@Override
public void clear(QueryOptions queryOptions) {
ConnectionManager connectionManager = getConnectionManager(queryOptions);
if (!connectionManager.isApplyUpdateForIndexEnabled(this)) {
return;
}
final Connection connection = connectionManager.getConnection(this, queryOptions);
createTableIndexIfNeeded(connection);
DBQueries.clearIndexTable(tableName, connection);
}
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
final Connection connection = connectionManager.getConnection(this, queryOptions);
pragmaJournalMode = DBQueries.getPragmaJournalModeOrNull(connection);
pragmaSynchronous = DBQueries.getPragmaSynchronousOrNull(connection);
canModifySyncAndJournaling = pragmaJournalMode != null && pragmaSynchronous != null;
doAddAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions, true);
}
/**
* Drops the table which underpins this index from the SQLite database.
*
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
ConnectionManager connectionManager = getConnectionManager(queryOptions);
if (!connectionManager.isApplyUpdateForIndexEnabled(this)) {
return;
}
final Connection connection = connectionManager.getConnection(this, queryOptions);
DBQueries.dropIndexTable(tableName, connection);
}
/**
* Utility method to create the index table if needed.
*
* @param connection The {@link Connection}.
*/
void createTableIndexIfNeeded(final Connection connection){
DBQueries.createIndexTable(tableName, primaryKeyAttribute.getAttributeType(), getAttribute().getAttributeType(), connection);
DBQueries.createIndexOnTable(tableName, connection);
}
/**
* Utility method to extract the {@link ConnectionManager} from QueryOptions.
*
* @param queryOptions The {@link QueryOptions}.
* @return The {@link ConnectionManager}
*
* @throws IllegalStateException if the ConnectionManager is not found.
*/
ConnectionManager getConnectionManager(final QueryOptions queryOptions){
ConnectionManager connectionManager = queryOptions.get(ConnectionManager.class);
if (connectionManager == null)
throw new IllegalStateException("A ConnectionManager is required but was not provided in the QueryOptions.");
return connectionManager;
}
@Override
public CloseableIterable<A> getDistinctKeys(final QueryOptions queryOptions) {
return getDistinctKeys(null, true, null, true, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, final QueryOptions queryOptions) {
return getDistinctKeysInRange(lowerBound, lowerInclusive, upperBound, upperInclusive, false, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions) {
return getDistinctKeysDescending(null, true, null, true, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return getDistinctKeysInRange(lowerBound, lowerInclusive, upperBound, upperInclusive, true, queryOptions);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
return DBQueries.getCountOfDistinctKeys(tableName, connection);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(QueryOptions queryOptions) {
return getStatisticsForDistinctKeys(queryOptions, true);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return getStatisticsForDistinctKeys(queryOptions, false);
}
CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(final QueryOptions queryOptions, final boolean sortByKeyDescending){
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
return new CloseableIterable<KeyStatistics<A>>() {
@Override
public CloseableIterator<KeyStatistics<A>> iterator() {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
final Connection connection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
final java.sql.ResultSet resultSet = DBQueries.getDistinctKeysAndCounts(sortByKeyDescending, tableName, connection);
closeableResourceGroup.add(DBUtils.wrapAsCloseable(resultSet));
return new LazyCloseableIterator<KeyStatistics<A>>() {
@Override
protected KeyStatistics<A> computeNext() {
try {
if (!resultSet.next()) {
close();
return endOfData();
}
A key = DBUtils.getValueFromResultSet(1, resultSet, attribute.getAttributeType());
Integer count = DBUtils.getValueFromResultSet(2, resultSet, Integer.class);
return new KeyStatistics<A>(key, count);
}
catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
@Override
public void close() {
closeableResourceGroup.close();
}
};
}
};
}
CloseableIterable<A> getDistinctKeysInRange(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, final boolean descending, final QueryOptions queryOptions) {
final Query<O> query = getKeyRangeRestriction(lowerBound, lowerInclusive, upperBound, upperInclusive);
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
return new CloseableIterable<A>() {
@Override
public CloseableIterator<A> iterator() {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
final Connection searchConnection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
final java.sql.ResultSet searchResultSet = DBQueries.getDistinctKeys(query, descending, tableName, searchConnection);
closeableResourceGroup.add(DBUtils.wrapAsCloseable(searchResultSet));
return new LazyCloseableIterator<A>() {
@Override
protected A computeNext() {
try {
if (!searchResultSet.next()) {
close();
return endOfData();
}
return DBUtils.getValueFromResultSet(1, searchResultSet, attribute.getAttributeType());
}
catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
@Override
public void close() {
closeableResourceGroup.close();
}
};
}
};
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(final QueryOptions queryOptions) {
return getKeysAndValues(null, true, null, true, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, final QueryOptions queryOptions) {
return getKeysAndValuesInRange(lowerBound, lowerInclusive, upperBound, upperInclusive, false, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
return getKeysAndValuesDescending(null, true, null, true, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return getKeysAndValuesInRange(lowerBound, lowerInclusive, upperBound, upperInclusive, true, queryOptions);
}
CloseableIterable<KeyValue<A, O>> getKeysAndValuesInRange(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, final boolean descending, final QueryOptions queryOptions) {
final Query<O> query = getKeyRangeRestriction(lowerBound, lowerInclusive, upperBound, upperInclusive);
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
return new CloseableIterable<KeyValue<A, O>>() {
@Override
public CloseableIterator<KeyValue<A, O>> iterator() {
final ConnectionManager connectionManager = getConnectionManager(queryOptions);
final Connection searchConnection = connectionManager.getConnection(SQLiteIndex.this, queryOptions);
final java.sql.ResultSet searchResultSet = DBQueries.getKeysAndValues(query, descending, tableName, searchConnection);
closeableResourceGroup.add(DBUtils.wrapAsCloseable(searchResultSet));
return new LazyCloseableIterator<KeyValue<A, O>>() {
@Override
protected KeyValue<A, O> computeNext() {
try {
if (!searchResultSet.next()) {
close();
return endOfData();
}
final K objectKey = DBUtils.getValueFromResultSet(1, searchResultSet, primaryKeyAttribute.getAttributeType());
final A objectValue = DBUtils.getValueFromResultSet(2, searchResultSet, attribute.getAttributeType());
final O object = foreignKeyAttribute.getValue(objectKey, queryOptions);
return new KeyValueMaterialized<A, O>(objectValue, object);
}
catch (Exception e) {
endOfData();
close();
throw new IllegalStateException("Unable to retrieve the ResultSet item.", e);
}
}
@Override
public void close() {
closeableResourceGroup.close();
}
};
}
};
}
Query<O> getKeyRangeRestriction(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive) {
final Query<O> query;
if (lowerBound != null && upperBound != null) {
query = between(attribute, lowerBound, lowerInclusive, upperBound, upperInclusive);
}
else if (lowerBound != null) {
query = lowerInclusive ? greaterThanOrEqualTo(attribute, lowerBound) : greaterThan(attribute, lowerBound);
}
else if (upperBound != null) {
query = upperInclusive ? lessThanOrEqualTo(attribute, upperBound) : lessThan(attribute, upperBound);
}
else {
query = has(attribute);
}
return query;
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return retrieve(equal(attribute, key), queryOptions).size();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SQLiteIndex that = (SQLiteIndex) o;
if (!attribute.equals(that.attribute)) return false;
return true;
}
@Override
public int hashCode() {
int result = getClass().hashCode();
result = 31 * result + attribute.hashCode();
return result;
}
// ---------- Static factory methods to create SQLiteIndex ----------
/**
* Creates a new {@link SQLiteIndex}.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param objectKeyAttribute The {@link SimpleAttribute} used to retrieve the object key.
* @param foreignKeyAttribute The {@link SimpleAttribute} to map a query result into the domain object.
* @param <A> The type of the attribute.
* @param <O> The type of the object containing the attributes.
* @param <K> The type of the object key.
* @return a new instance of the {@link SQLiteIndex}
*/
public static <A extends Comparable<A>, O, K> SQLiteIndex<A, O, K> onAttribute(final Attribute<O, A> attribute,
final SimpleAttribute<O, K> objectKeyAttribute,
final SimpleAttribute<K, O> foreignKeyAttribute) {
return new SQLiteIndex<A, O, K>(attribute, objectKeyAttribute, foreignKeyAttribute, "");
}
}
| 43,117 | 44.772824 | 217 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/ConnectionManager.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.sql.Connection;
/**
* Connection Manager
*
* @author Silvano Riz
*/
public interface ConnectionManager {
/**
* Returns a {@link Connection}.
*
* @param index The {@link Index} requesting the connection.
* @param queryOptions The query options for the request
* @return The {@link Connection}
*/
Connection getConnection(Index<?> index, QueryOptions queryOptions);
/**
* Informs if index updates should be applied.
* This is for advanced use cases only, where the application supplies a custom ConnectionManager to CQEngine.
*
* @param index The index.
* @return true if updates on the index should be applied. False otherwise.
*/
boolean isApplyUpdateForIndexEnabled(Index<?> index);
}
| 1,535 | 31 | 114 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/support/SQLiteIndexFlags.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite.support;
import com.googlecode.cqengine.index.sqlite.SQLiteIndex;
/**
* Flags which can be set in query options (via {@link com.googlecode.cqengine.query.QueryFactory}) which allow the
* behaviour of {@link SQLiteIndex} to be adjusted.
*
* @author niall.gallagher
*/
public class SQLiteIndexFlags {
/**
* A flag which if enabled causes the SQLiteIndex to temporarily drop the index on a table prior to adding objects,
* then to restore the index after objects have been added.
* <p/>
* This should not be used if other concurrent operations might also be ongoing on the collection. It is intended
* for use when the collection is first being populated or similar, such as at application startup.
*/
public static String BULK_IMPORT = "BULK_IMPORT";
/**
* <p> A 2-values flag that enables externally managed bulk import and specifies it's status.
*/
public enum BulkImportExternallyManged {
/**
* <p> Indicates that the batch is not the last and that the SQLiteIndex shouldn't reinstate the index on the table
*/
NOT_LAST,
/**
* <p> Indicates that the batch is the last batch and that the SQLiteIndex needs to reinstate the index on the table
*/
LAST;
};
/**
* <p> Switches off the 'synchronous' and 'journal_mode' pragmas before executing a bulk import.
* Executing a bulk import with 'synchronous' and 'journal_mode' OFF can significantly increase the performances of the operation
* at a cost of a slightly higher risk of database corruption in case of system crashes or the power loses.
* <p> The default values will be re-instated after the import.
*/
public static String BULK_IMPORT_SUSPEND_SYNC_AND_JOURNALING = "BULK_IMPORT_SUSPEND_SYNC_AND_JOURNALING";
}
| 2,485 | 40.433333 | 133 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/support/DBQueries.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite.support;
import com.googlecode.concurrenttrees.common.CharSequences;
import com.googlecode.cqengine.index.sqlite.SQLiteIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.simple.*;
import org.sqlite.SQLiteConfig;
import java.sql.*;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Database (SQLite) query executor used by the {@link SQLiteIndex}.
*
* @author Silvano Riz
*/
public class DBQueries {
/**
* Represents a table row (objectId, value).
*
* @param <K> The type of the objectId.
* @param <A> The type of the value.
*/
public static class Row<K, A>{
private final K objectKey;
private final A value;
public Row(K objectKey, A value) {
this.objectKey = objectKey;
this.value = value;
}
public K getObjectKey() {
return objectKey;
}
public A getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Row row = (Row) o;
if (!objectKey.equals(row.objectKey)) return false;
if (!value.equals(row.value)) return false;
return true;
}
@Override
public int hashCode() {
int result = objectKey.hashCode();
result = 31 * result + value.hashCode();
return result;
}
}
public static <K, A> void createIndexTable(final String tableName, final Class<K> objectKeyClass, final Class<A> valueClass, final Connection connection){
final String objectKeySQLiteType = DBUtils.getDBTypeForClass(objectKeyClass);
final String objectValueSQLiteType = DBUtils.getDBTypeForClass(valueClass);
final String sqlCreateTable = String.format(
"CREATE TABLE IF NOT EXISTS cqtbl_%s (objectKey %s, value %s, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;",
tableName,
objectKeySQLiteType,
objectValueSQLiteType);
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(sqlCreateTable);
}catch (SQLException e){
throw new IllegalStateException("Unable to create index table: " + tableName, e);
}finally {
DBUtils.closeQuietly(statement);
}
}
public static boolean indexTableExists(final String tableName, final Connection connection) {
final String selectSql = String.format("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cqtbl_%s';", tableName);
Statement statement = null;
try{
statement = connection.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery(selectSql);
return resultSet.next();
}catch(Exception e){
throw new IllegalStateException("Unable to determine if table exists: " + tableName, e);
}
finally {
DBUtils.closeQuietly(statement);
}
}
public static void createIndexOnTable(final String tableName, final Connection connection){
final String sqlCreateIndex = String.format(
"CREATE INDEX IF NOT EXISTS cqidx_%s_value ON cqtbl_%s (value);",
tableName,
tableName);
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(sqlCreateIndex);
}catch (SQLException e){
throw new IllegalStateException("Unable to add index on table: " + tableName, e);
}finally {
DBUtils.closeQuietly(statement);
}
}
public static void suspendSyncAndJournaling(final Connection connection){
setSyncAndJournaling(connection, SQLiteConfig.SynchronousMode.OFF, SQLiteConfig.JournalMode.OFF);
}
public static void setSyncAndJournaling(final Connection connection, final SQLiteConfig.SynchronousMode pragmaSynchronous, final SQLiteConfig.JournalMode pragmaJournalMode){
Statement statement = null;
try {
final boolean autoCommit = DBUtils.setAutoCommit(connection, true);
statement = connection.createStatement();
statement.execute("PRAGMA synchronous = " + pragmaSynchronous.getValue());
// This little transaction will also cause a wanted fsync on the OS to flush the data still in the OS cache to disc.
statement.execute("PRAGMA journal_mode = " + pragmaJournalMode.getValue());
DBUtils.setAutoCommit(connection, autoCommit);
}catch (SQLException e){
throw new IllegalStateException("Unable to set the 'synchronous' and 'journal_mode' pragmas", e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static SQLiteConfig.SynchronousMode getPragmaSynchronousOrNull(final Connection connection){
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("PRAGMA synchronous;");
if (resultSet.next()){
final int syncPragmaId = resultSet.getInt(1);
if (!resultSet.wasNull()) {
switch (syncPragmaId){
case 0: return SQLiteConfig.SynchronousMode.OFF;
case 1: return SQLiteConfig.SynchronousMode.NORMAL;
case 2: return SQLiteConfig.SynchronousMode.FULL;
default: return null;
}
}
}
return null;
}catch (Exception e){
return null;
}finally{
DBUtils.closeQuietly(statement);
}
}
public static SQLiteConfig.JournalMode getPragmaJournalModeOrNull(final Connection connection){
Statement statement = null;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("PRAGMA journal_mode;");
if (resultSet.next()){
final String journalMode = resultSet.getString(1);
return journalMode != null ? SQLiteConfig.JournalMode.valueOf(journalMode.toUpperCase()) : null;
}
return null;
}catch (Exception e){
return null;
}finally{
DBUtils.closeQuietly(statement);
}
}
public static void dropIndexOnTable(final String tableName, final Connection connection){
final String sqlDropIndex = String.format("DROP INDEX IF EXISTS cqidx_%s_value;",tableName);
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(sqlDropIndex);
}catch (SQLException e){
throw new IllegalStateException("Unable to drop index on table: " + tableName, e);
}finally {
DBUtils.closeQuietly(statement);
}
}
public static void dropIndexTable(final String tableName, final Connection connection){
final String sqlDropIndex = String.format("DROP INDEX IF EXISTS cqidx_%s_value;",tableName);
final String sqlDropTable = String.format("DROP TABLE IF EXISTS cqtbl_%s;", tableName);
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(sqlDropIndex);
statement.executeUpdate(sqlDropTable);
}catch (SQLException e){
throw new IllegalStateException("Unable to drop index table: "+ tableName, e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static void clearIndexTable(final String tableName, final Connection connection){
final String clearTable = String.format("DELETE FROM cqtbl_%s;",tableName);
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate(clearTable);
}catch (SQLException e){
throw new IllegalStateException("Unable to clear index table: " + tableName, e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static void compactDatabase(final Connection connection){
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute("VACUUM;");
}catch (SQLException e){
throw new IllegalStateException("Unable to compact database", e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static void expandDatabase(final Connection connection, long numBytes) {
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute("CREATE TABLE IF NOT EXISTS cq_expansion (val);");
statement.execute("INSERT INTO cq_expansion VALUES (zeroblob(" + numBytes + "));");
statement.execute("DROP TABLE cq_expansion;");
}catch (SQLException e){
throw new IllegalStateException("Unable to expand database by bytes: " + numBytes, e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static long getDatabaseSize(final Connection connection){
long pageCount = readPragmaLong(connection, "PRAGMA page_count;");
long pageSize = readPragmaLong(connection, "PRAGMA page_size;");
return pageCount * pageSize;
}
static long readPragmaLong(final Connection connection, String query) {
Statement statement = null;
try {
statement = connection.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery(query);
if (!resultSet.next()){
throw new IllegalStateException("Unable to read long from pragma query. The ResultSet returned no row. Query: " + query);
}
return resultSet.getLong(1);
}catch (SQLException e){
throw new IllegalStateException("Unable to read long from pragma query", e);
}finally{
DBUtils.closeQuietly(statement);
}
}
public static <K,A> int bulkAdd(Iterable<Row<K, A>> rows, final String tableName, final Connection connection){
final String sql = String.format("INSERT OR IGNORE INTO cqtbl_%s values(?, ?);", tableName);
PreparedStatement statement = null;
int totalRowsModified = 0;
try {
statement = connection.prepareStatement(sql);
for (Row<K, A> row : rows) {
statement.setObject(1, row.getObjectKey());
statement.setObject(2, row.getValue());
statement.addBatch();
}
int[] rowsModified = statement.executeBatch();
for (int m : rowsModified) {
ensureNotNegative(m);
totalRowsModified += m;
}
return totalRowsModified;
}
catch (NullPointerException e) {
// Note: here we catch a and rethrow NullPointerException,
// to allow compatibility with Java Collections Framework,
// which requires NPE to be thrown for null arguments...
boolean rolledBack = DBUtils.rollback(connection);
NullPointerException npe = new NullPointerException("Unable to bulk add rows containing a null object to the index table: "+ tableName + ". Rolled back: " + rolledBack);
npe.initCause(e);
throw npe;
}
catch (Exception e){
boolean rolledBack = DBUtils.rollback(connection);
throw new IllegalStateException("Unable to bulk add rows to the index table: "+ tableName + ". Rolled back: " + rolledBack, e);
}finally {
DBUtils.closeQuietly(statement);
}
}
public static <K> int bulkRemove(Iterable<K> objectKeys, final String tableName, final Connection connection){
final String sql = String.format("DELETE FROM cqtbl_%s WHERE objectKey = ?;", tableName);
PreparedStatement statement = null;
Boolean previousAutocommit = null;
int totalRowsModified = 0;
try{
previousAutocommit = DBUtils.setAutoCommit(connection, false);
statement = connection.prepareStatement(sql);
for(K objectKey: objectKeys) {
statement.setObject(1, objectKey);
statement.addBatch();
}
int[] rowsModified = statement.executeBatch();
for (int m : rowsModified) {
ensureNotNegative(m);
totalRowsModified += m;
}
DBUtils.commit(connection);
return totalRowsModified;
}
catch (NullPointerException e) {
// Note: here we catch a and rethrow NullPointerException,
// to allow compatibility with Java Collections Framework,
// which requires NPE to be thrown for null arguments...
boolean rolledBack = DBUtils.rollback(connection);
NullPointerException npe = new NullPointerException("Unable to bulk remove rows containing a null object from the index table: "+ tableName + ". Rolled back: " + rolledBack);
npe.initCause(e);
throw npe;
}
catch (Exception e){
boolean rolledBack = DBUtils.rollback(connection);
throw new IllegalStateException("Unable to remove rows from the index table: " + tableName + ". Rolled back: " + rolledBack, e);
}finally{
DBUtils.closeQuietly(statement);
if (previousAutocommit != null)
DBUtils.setAutoCommit(connection, previousAutocommit);
}
}
static class WhereClause{
final String whereClause;
final Object objectToBind;
WhereClause(String whereClause, Object objectToBind){
this.whereClause = whereClause;
this.objectToBind = objectToBind;
}
}
static <O, A> PreparedStatement createAndBindSelectPreparedStatement(final String selectPrefix,
final String groupingAndSorting,
final List<WhereClause> additionalWhereClauses,
final Query<O> query,
final Connection connection) throws SQLException {
int bindingIndex = 1;
StringBuilder stringBuilder = new StringBuilder(selectPrefix).append(' ');
StringBuilder suffix = new StringBuilder();
final Class queryClass = query.getClass();
PreparedStatement statement;
if (queryClass == Has.class){
// Has is a special case, because there is no WHERE clause by default.
if (additionalWhereClauses.isEmpty()){
suffix.append(groupingAndSorting);
suffix.append(';');
}else{
stringBuilder.append("WHERE ");
for (Iterator<WhereClause> iterator = additionalWhereClauses.iterator(); iterator.hasNext(); ) {
WhereClause additionalWhereClause = iterator.next();
suffix.append(additionalWhereClause.whereClause);
if (iterator.hasNext()) {
suffix.append(" AND ");
}
}
suffix.append(groupingAndSorting);
suffix.append(';');
}
stringBuilder.append(suffix);
statement = connection.prepareStatement(stringBuilder.toString());
}else {
// Other queries have a WHERE clause by default.
if (additionalWhereClauses.isEmpty()){
suffix.append(groupingAndSorting);
suffix.append(';');
}else{
for (WhereClause additionalWhereClause : additionalWhereClauses){
suffix.append(" AND ").append(additionalWhereClause.whereClause);
}
suffix.append(groupingAndSorting);
suffix.append(';');
}
if (queryClass == Equal.class) {
@SuppressWarnings("unchecked")
final Equal<O, A> equal = (Equal<O, A>) query;
stringBuilder.append("WHERE value = ?").append(suffix);
statement = connection.prepareStatement(stringBuilder.toString());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, equal.getValue());
} else if (queryClass == In.class){
@SuppressWarnings("unchecked")
final In<O, A> in = (In<O, A>) query;
Set<A> values = in.getValues();
stringBuilder.append("WHERE value IN ( ");
for (int i=0; i<values.size(); i++){
if (i > 0){
stringBuilder.append(", ");
}
stringBuilder.append("?");
}
stringBuilder.append(")").append(suffix);
statement = connection.prepareStatement(stringBuilder.toString());
bindingIndex = DBUtils.setValuesToPreparedStatement(bindingIndex, statement, values);
} else if (queryClass == LessThan.class) {
@SuppressWarnings("unchecked")
final LessThan<O, ? extends Comparable<A>> lessThan = (LessThan<O, ? extends Comparable<A>>) query;
boolean isValueInclusive = lessThan.isValueInclusive();
if (isValueInclusive) {
stringBuilder.append("WHERE value <= ?").append(suffix);
} else {
stringBuilder.append("WHERE value < ?").append(suffix);
}
statement = connection.prepareStatement(stringBuilder.toString());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, lessThan.getValue());
} else if (queryClass == StringStartsWith.class) {
final StringStartsWith<O, ? extends CharSequence> stringStartsWith = (StringStartsWith<O, ? extends CharSequence>) query;
stringBuilder.append("WHERE value >= ? AND value < ?").append(suffix);
final String lowerBoundInclusive = CharSequences.toString(stringStartsWith.getValue());
final int len = lowerBoundInclusive.length();
final String allButLast = lowerBoundInclusive.substring(0, len - 1);
final String upperBoundExclusive = allButLast + Character.toChars(lowerBoundInclusive.charAt(len - 1) + 1)[0];
statement = connection.prepareStatement(stringBuilder.toString());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, lowerBoundInclusive);
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, upperBoundExclusive);
} else if (queryClass == GreaterThan.class) {
@SuppressWarnings("unchecked")
final GreaterThan<O, ? extends Comparable<A>> greaterThan = (GreaterThan<O, ? extends Comparable<A>>) query;
boolean isValueInclusive = greaterThan.isValueInclusive();
if (isValueInclusive) {
stringBuilder.append("WHERE value >= ?").append(suffix);
} else {
stringBuilder.append("WHERE value > ?").append(suffix);
}
statement = connection.prepareStatement(stringBuilder.toString());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, greaterThan.getValue());
} else if (queryClass == Between.class) {
@SuppressWarnings("unchecked")
final Between<O, ? extends Comparable<A>> between = (Between<O, ? extends Comparable<A>>) query;
if (between.isLowerInclusive()) {
stringBuilder.append("WHERE value >= ?");
} else {
stringBuilder.append("WHERE value > ?");
}
if (between.isUpperInclusive()) {
stringBuilder.append(" AND value <= ?");
} else {
stringBuilder.append(" AND value < ?");
}
stringBuilder.append(suffix);
statement = connection.prepareStatement(stringBuilder.toString());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, between.getLowerValue());
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, between.getUpperValue());
} else {
throw new IllegalStateException("Query " + queryClass + " not supported.");
}
}
for (WhereClause additionalWhereClause : additionalWhereClauses){
DBUtils.setValueToPreparedStatement(bindingIndex++, statement, additionalWhereClause.objectToBind);
}
return statement;
}
public static <O> int count(final Query<O> query, final String tableName, final Connection connection) {
final String selectSql = String.format("SELECT COUNT(objectKey) FROM cqtbl_%s", tableName);
PreparedStatement statement = null;
try {
statement = createAndBindSelectPreparedStatement(selectSql, "", Collections.<WhereClause>emptyList(), query, connection);
java.sql.ResultSet resultSet = statement.executeQuery();
if (!resultSet.next()) {
throw new IllegalStateException("Unable to execute count. The ResultSet returned no row. Query: " + query);
}
return resultSet.getInt(1);
}
catch (Exception e) {
throw new IllegalStateException("Unable to execute count. Query: " + query, e);
}
finally {
DBUtils.closeQuietly(statement);
}
}
public static <O> int countDistinct(final Query<O> query, final String tableName, final Connection connection){
// NOTE: Using GROUP BY is much faster than using SELECT DISTINCT in SQLite for deduplication
final String selectSql = String.format("SELECT COUNT(1) AS countDistinct FROM (SELECT objectKey FROM cqtbl_%s", tableName);
PreparedStatement statement = null;
try{
statement = createAndBindSelectPreparedStatement(selectSql, " GROUP BY objectKey)", Collections.<WhereClause>emptyList(), query, connection);
java.sql.ResultSet resultSet = statement.executeQuery();
if (!resultSet.next()){
throw new IllegalStateException("Unable to execute count. The ResultSet returned no row. Query: " + query);
}
return resultSet.getInt(1);
}catch(Exception e){
throw new IllegalStateException("Unable to execute count. Query: " + query, e);
}finally {
DBUtils.closeQuietly(statement);
}
}
public static <O> java.sql.ResultSet search(final Query<O> query, final String tableName, final Connection connection){
final String selectSql = String.format("SELECT DISTINCT objectKey FROM cqtbl_%s",tableName);
PreparedStatement statement = null;
try{
statement = createAndBindSelectPreparedStatement(selectSql, "", Collections.<WhereClause>emptyList(), query, connection);
return statement.executeQuery();
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to execute search. Query: " + query, e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static <O> java.sql.ResultSet getDistinctKeys(final Query<O> query, boolean descending, final String tableName, final Connection connection){
final String selectSql = String.format("SELECT DISTINCT value FROM cqtbl_%s",tableName);
PreparedStatement statement = null;
try{
String orderByClause = descending ? " ORDER BY value DESC" : " ORDER BY value ASC";
statement = createAndBindSelectPreparedStatement(selectSql, orderByClause, Collections.<WhereClause>emptyList(), query, connection);
return statement.executeQuery();
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to look up keys. Query: " + query, e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static <O> java.sql.ResultSet getKeysAndValues(final Query<O> query, boolean descending, final String tableName, final Connection connection){
final String selectSql = String.format("SELECT objectKey, value FROM cqtbl_%s",tableName);
PreparedStatement statement = null;
try{
String orderByClause = descending ? " ORDER BY value DESC" : " ORDER BY value ASC";
statement = createAndBindSelectPreparedStatement(selectSql, orderByClause, Collections.<WhereClause>emptyList(), query, connection);
return statement.executeQuery();
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to look up keys and values. Query: " + query, e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static int getCountOfDistinctKeys(final String tableName, final Connection connection){
final String selectSql = String.format("SELECT COUNT(DISTINCT value) FROM cqtbl_%s",tableName);
Statement statement = null;
try{
statement = connection.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery(selectSql);
if (!resultSet.next()){
throw new IllegalStateException("Unable to execute count. The ResultSet returned no row. Query: " + selectSql);
}
return resultSet.getInt(1);
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to count distinct keys.", e);
}
}
public static java.sql.ResultSet getDistinctKeysAndCounts(boolean sortByKeyDescending, final String tableName, final Connection connection){
final String selectSql = String.format("SELECT DISTINCT value, COUNT(value) AS valueCount FROM cqtbl_%s GROUP BY (value) %s", tableName, sortByKeyDescending ? "ORDER BY value DESC" : "");
Statement statement = null;
try{
statement = connection.createStatement();
return statement.executeQuery(selectSql);
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to look up index entries and counts.", e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static java.sql.ResultSet getAllIndexEntries(final String tableName, final Connection connection){
final String selectSql = String.format("SELECT objectKey, value FROM cqtbl_%s ORDER BY objectKey;",tableName);
Statement statement = null;
try{
statement = connection.createStatement();
return statement.executeQuery(selectSql);
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to look up index entries.", e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static <K> java.sql.ResultSet getIndexEntryByObjectKey(final K key , final String tableName, final Connection connection){
final String selectSql = String.format("SELECT objectKey, value FROM cqtbl_%s WHERE objectKey = ?",tableName);
PreparedStatement statement = null;
try{
statement = connection.prepareStatement(selectSql);
DBUtils.setValueToPreparedStatement(1, statement, key);
return statement.executeQuery();
}catch(Exception e){
DBUtils.closeQuietly(statement);
throw new IllegalStateException("Unable to look up index entries.", e);
}
// In case of success we leave the statement and result-set open because the iteration of an Index ResultSet is lazy.
}
public static <K, O> boolean contains(final K objectKey, final Query<O> query, final String tableName, final Connection connection){
final String selectSql = String.format("SELECT objectKey FROM cqtbl_%s", tableName);
PreparedStatement statement = null;
try{
List<WhereClause> additionalWhereClauses = Collections.singletonList(new WhereClause("objectKey = ?", objectKey));
statement = createAndBindSelectPreparedStatement(selectSql, " LIMIT 1", additionalWhereClauses, query, connection);
java.sql.ResultSet resultSet = statement.executeQuery();
return resultSet.next();
}catch (SQLException e){
throw new IllegalStateException("Unable to execute contains. Query: " + query, e);
}finally{
DBUtils.closeQuietly(statement);
}
}
static void ensureNotNegative(int value) {
if (value < 0) throw new IllegalStateException("Update returned error code: " + value);
}
}
| 30,705 | 44.829851 | 195 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/sqlite/support/DBUtils.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite.support;
import com.googlecode.concurrenttrees.common.CharSequences;
import java.io.Closeable;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Date;
/**
* A bunch of useful database utilities.
*
* @author Silvano Riz
*/
public class DBUtils {
public static Closeable wrapAsCloseable(final ResultSet resultSet){
return new Closeable() {
@Override
public void close() throws IOException {
DBUtils.closeQuietly(resultSet);
}
};
}
public static boolean setAutoCommit(final Connection connection, final boolean value){
try {
boolean previousValue = connection.getAutoCommit();
connection.setAutoCommit(value);
return previousValue;
}catch (Exception e){
throw new IllegalStateException("Unable to set the Connection autoCommit to " + value, e);
}
}
public static void commit(final Connection connection){
try {
connection.commit();
}catch (Exception e){
throw new IllegalStateException("Commit failed", e);
}
}
public static boolean rollback(final Connection connection){
try {
connection.rollback();
return true;
}catch (Exception e){
return false;
}
}
public static void closeQuietly(java.sql.ResultSet resultSet){
if (resultSet == null)
return;
try {
Statement statement = resultSet.getStatement();
if (statement != null){
statement.close();
}
}catch(Exception e){
// Ignore
}
try{
resultSet.close();
}catch (Exception e){
// Ignore
}
}
public static void closeQuietly(Statement statement){
if (statement == null)
return;
try{
statement.close();
}catch (Exception e){
// Ignore
}
}
public static void closeQuietly(Connection connection){
if (connection == null)
return;
try{
connection.close();
}catch (Exception e){
// Ignore
}
}
public static String getDBTypeForClass(final Class<?> valueType){
if ( CharSequence.class.isAssignableFrom(valueType) || BigDecimal.class.isAssignableFrom(valueType)) {
return "TEXT";
}else if (Long.class.isAssignableFrom(valueType) || Integer.class.isAssignableFrom(valueType) || Short.class.isAssignableFrom(valueType) || Boolean.class.isAssignableFrom(valueType) || Date.class.isAssignableFrom(valueType)) {
return "INTEGER";
}else if (Float.class.isAssignableFrom(valueType) || Double.class.isAssignableFrom(valueType)){
return "REAL";
}else if (valueType == byte[].class){
return "BLOB";
}else{
throw new IllegalStateException("Type " + valueType + " not supported.");
}
}
public static void setValueToPreparedStatement(int index, final PreparedStatement preparedStatement, Object value) throws SQLException {
if (value instanceof Date) {
preparedStatement.setLong(index, ((Date) value).getTime());
}else if(value instanceof CharSequence){
preparedStatement.setString(index, CharSequences.toString((CharSequence)value));
}else{
preparedStatement.setObject(index, value);
}
}
/**
* <p> Binds a set of values to the statement.
*
* @param startIndex parameter index from where to start the binding.
* @param preparedStatement the prepared statement.
* @param values The values to bind
* @return The new start index.
* @throws SQLException if the binding fails.
*/
public static int setValuesToPreparedStatement(final int startIndex, final PreparedStatement preparedStatement, final Iterable values) throws SQLException {
int index = startIndex;
for (Object value : values){
setValueToPreparedStatement(index++, preparedStatement, value);
}
return index;
}
@SuppressWarnings("unchecked")
public static <T>T getValueFromResultSet(int index, final ResultSet resultSet, final Class<T> type){
try {
if (java.sql.Date.class.isAssignableFrom(type)) {
final long time = resultSet.getLong(index);
return (T)new java.sql.Date(time);
} else if (Time.class.isAssignableFrom(type)) {
final long time = resultSet.getLong(index);
return (T)new java.sql.Time(time);
} else if (Timestamp.class.isAssignableFrom(type)) {
final long time = resultSet.getLong(index);
return (T)new java.sql.Timestamp(time);
}else if (Date.class.isAssignableFrom(type)) {
final long time = resultSet.getLong(index);
return (T)new Date(time);
} else if (Long.class.isAssignableFrom(type)) {
return (T) Long.valueOf(resultSet.getLong(index));
} else if (Integer.class.isAssignableFrom(type)) {
return (T) Integer.valueOf(resultSet.getInt(index));
} else if (Short.class.isAssignableFrom(type)) {
return (T) Short.valueOf(resultSet.getShort(index));
} else if (Float.class.isAssignableFrom(type)) {
return (T) Float.valueOf(resultSet.getFloat(index));
} else if (Double.class.isAssignableFrom(type)) {
return (T) Double.valueOf(resultSet.getDouble(index));
} else if (Boolean.class.isAssignableFrom(type)) {
return (T) Boolean.valueOf(resultSet.getBoolean(index));
} else if (BigDecimal.class.isAssignableFrom(type)) {
return (T) resultSet.getBigDecimal(index);
} else if (CharSequence.class.isAssignableFrom(type)) {
return (T) resultSet.getString(index);
} else if (byte[].class.isAssignableFrom(type)) {
return (T) resultSet.getBytes(index);
} else {
throw new IllegalStateException("Type " + type + " not supported.");
}
}catch (Exception e){
throw new IllegalStateException("Unable to read the value from the resultSet. Index:" + index + ", type: " + type, e);
}
}
/**
* Strips illegal characters so that the given string can be used as a SQLite table name.
*/
public static String sanitizeForTableName(String input) {
return input.replaceAll("[^A-Za-z0-9]", "");
}
}
| 7,431 | 32.628959 | 234 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/disk/PartialDiskIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.disk;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.PartialIndex;
import com.googlecode.cqengine.index.support.PartialSortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.DiskTypeIndex;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.query.Query;
import static com.googlecode.cqengine.index.sqlite.support.DBUtils.sanitizeForTableName;
/**
* A {@link PartialIndex} which uses {@link DiskPersistence}.
*
* @author niall.gallagher
*/
public class PartialDiskIndex<A extends Comparable<A>, O> extends PartialSortedKeyStatisticsAttributeIndex<A, O> implements DiskTypeIndex {
final String tableNameSuffix;
/**
* Protected constructor, called by subclasses.
*
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialDiskIndex(Attribute<O, A> attribute, Query<O> filterQuery) {
super(attribute, filterQuery);
this.tableNameSuffix = "_partial_" + sanitizeForTableName(filterQuery.toString());
}
@Override
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
protected SortedKeyStatisticsAttributeIndex<A, O> createBackingIndex() {
return new DiskIndex(DiskPersistence.class, attribute, tableNameSuffix) {
@Override
public Index getEffectiveIndex() {
return PartialDiskIndex.this.getEffectiveIndex();
}
};
}
// ---------- Static factory methods to create PartialDiskIndex ----------
/**
* Creates a new {@link PartialDiskIndex}. This will obtain details of the {@link DiskPersistence} to use from the
* IndexedCollection, throwing an exception if the IndexedCollection has not been configured with a suitable
* DiskPersistence.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return A {@link DiskIndex} on the given attribute.
*/
public static <A extends Comparable<A>, O> PartialDiskIndex<A, O> onAttributeWithFilterQuery(final Attribute<O, A> attribute, final Query<O> filterQuery) {
return new PartialDiskIndex<A, O>(attribute, filterQuery);
}
}
| 3,333 | 42.868421 | 159 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/disk/DiskIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.disk;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.sqlite.SimplifiedSQLiteIndex;
import com.googlecode.cqengine.index.support.indextype.DiskTypeIndex;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.WrappedResultSet;
/**
* An index persisted in a file on disk.
* <p/>
* This index is similar to the on-heap {@link com.googlecode.cqengine.index.navigable.NavigableIndex} and supports
* the same types of queries.
* <p/>
* The current implementation of this index is based on {@link com.googlecode.cqengine.index.sqlite.SQLiteIndex}.
*
* @author niall.gallagher
*/
public class DiskIndex<A extends Comparable<A>, O, K extends Comparable<K>> extends SimplifiedSQLiteIndex<A, O, K> implements DiskTypeIndex {
// An integer to add or subtract to the retrieval cost returned by SimplifiedSQLiteIndex (which ranges 80-89).
// Therefore the retrieval costs for this index will range from 90-99...
static final int INDEX_RETRIEVAL_COST_DELTA = +10;
DiskIndex(Class<? extends DiskPersistence<O, A>> persistenceType, Attribute<O, A> attribute, String tableNameSuffix) {
super(persistenceType, attribute, tableNameSuffix);
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
return new WrappedResultSet<O>(super.retrieve(query, queryOptions)) {
@Override
public int getRetrievalCost() {
return super.getRetrievalCost() + INDEX_RETRIEVAL_COST_DELTA;
}
};
}
// ---------- Static factory methods to create DiskIndex ----------
/**
* Creates a new {@link DiskIndex}. This will obtain details of the {@link DiskPersistence} to use from the
* IndexedCollection, throwing an exception if the IndexedCollection has not been configured with a suitable
* DiskPersistence.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return A {@link DiskIndex} on the given attribute.
*/
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
public static <A extends Comparable<A>, O> DiskIndex<A, O, ? extends Comparable<?>> onAttribute(final Attribute<O, A> attribute) {
return new DiskIndex(DiskPersistence.class, attribute, "");
}
}
| 3,337 | 44.108108 | 142 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/navigable/PartialNavigableIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.navigable;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.Factory;
import com.googlecode.cqengine.index.support.PartialIndex;
import com.googlecode.cqengine.index.support.PartialSortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import java.util.concurrent.ConcurrentNavigableMap;
/**
* A {@link PartialIndex} which wraps a {@link NavigableIndex} and uses {@link OnHeapPersistence}.
*
* @author niall.gallagher
*/
public class PartialNavigableIndex<A extends Comparable<A>, O> extends PartialSortedKeyStatisticsAttributeIndex<A, O> implements OnHeapTypeIndex {
final Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory;
final Factory<StoredResultSet<O>> valueSetFactory;
/**
* Protected constructor, called by subclasses.
*
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialNavigableIndex(Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute, Query<O> filterQuery) {
super(attribute, filterQuery);
this.indexMapFactory = indexMapFactory;
this.valueSetFactory = valueSetFactory;
}
@Override
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
protected SortedKeyStatisticsAttributeIndex<A, O> createBackingIndex() {
return new NavigableIndex<A, O>(indexMapFactory, valueSetFactory, attribute) {
@Override
public Index getEffectiveIndex() {
return PartialNavigableIndex.this.getEffectiveIndex();
}
};
}
// ---------- Static factory methods to create PartialNavigableIndex ----------
/**
* Creates a new {@link PartialNavigableIndex}.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return A {@link PartialNavigableIndex} on the given attribute.
*/
public static <A extends Comparable<A>, O> PartialNavigableIndex<A, O> onAttributeWithFilterQuery(Attribute<O, A> attribute, Query<O> filterQuery) {
return onAttributeWithFilterQuery(new NavigableIndex.DefaultIndexMapFactory<A, O>(), new NavigableIndex.DefaultValueSetFactory<O>(), attribute, filterQuery);
}
/**
* Creates a new {@link PartialNavigableIndex}.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
* @param indexMapFactory The index map factory to supply to the {@link NavigableIndex}.
* @param valueSetFactory The value set factory to supply to the {@link NavigableIndex}.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return A {@link PartialNavigableIndex} on the given attribute.
*/
public static <A extends Comparable<A>, O> PartialNavigableIndex<A, O> onAttributeWithFilterQuery(Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute, Query<O> filterQuery) {
return new PartialNavigableIndex<A, O>(indexMapFactory, valueSetFactory, attribute, filterQuery);
}
}
| 4,643 | 48.935484 | 269 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/navigable/NavigableIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.navigable;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.quantizer.Quantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.*;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.QuantizedResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentSkipListMap}.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* <li>
* {@link LessThan}
* </li>
* <li>
* {@link GreaterThan}
* </li>
* <li>
* {@link Between}
* </li>
* </ul>
* </ul>
* The constructor of this index accepts {@link Factory} objects, from which it will create the map and value sets it
* uses internally. This allows the application to "tune" the construction parameters of these maps/sets,
* by supplying custom factories.
* For default settings, supply {@link DefaultIndexMapFactory} and {@link DefaultValueSetFactory}.
*
* @author Niall Gallagher
*/
public class NavigableIndex<A extends Comparable<A>, O> extends AbstractMapBasedAttributeIndex<A, O, ConcurrentNavigableMap<A, StoredResultSet<O>>> implements SortedKeyStatisticsAttributeIndex<A, O>, OnHeapTypeIndex {
protected static final int INDEX_RETRIEVAL_COST = 40;
/**
* Package-private constructor, used by static factory methods. Creates a new NavigableIndex initialized to index
* the supplied attribute.
*
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built
*/
protected NavigableIndex(Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute) {
super(indexMapFactory, valueSetFactory, attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
add(LessThan.class);
add(GreaterThan.class);
add(Between.class);
add(Has.class);
}});
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
Class<?> queryClass = query.getClass();
final boolean indexIsQuantized = isQuantized();
// Process Equal queries in the same was as HashIndex...
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions);
}else if (queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions);
} else if (queryClass.equals(Has.class)) {
return deduplicateIfNecessary(indexMap.values(), query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
// Process LessThan, GreaterThan and Between queries as follows...
final IndexRangeLookupFunction<O> lookupFunction;
if (queryClass.equals(LessThan.class)) {
@SuppressWarnings("unchecked")
final LessThan<O, A> lessThan = (LessThan<O, A>) query;
lookupFunction = new IndexRangeLookupFunction<O>(query, false, true) {
@Override
public Iterable<StoredResultSet<O>> perform() {
return indexMap.headMap(
getQuantizedValue(lessThan.getValue()),
lessThan.isValueInclusive() || indexIsQuantized
).values();
}
};
}
else if (queryClass.equals(GreaterThan.class)) {
@SuppressWarnings("unchecked")
final GreaterThan<O, A> greaterThan = (GreaterThan<O, A>) query;
lookupFunction = new IndexRangeLookupFunction<O>(query, true, false) {
@Override
public Iterable<StoredResultSet<O>> perform() {
return indexMap.tailMap(
getQuantizedValue(greaterThan.getValue()),
greaterThan.isValueInclusive() || indexIsQuantized
).values();
}
};
}
else if (queryClass.equals(Between.class)) {
@SuppressWarnings("unchecked")
final Between<O, A> between = (Between<O, A>) query;
lookupFunction = new IndexRangeLookupFunction<O>(query, true, true) {
@Override
public Iterable<StoredResultSet<O>> perform() {
return indexMap.subMap(
getQuantizedValue(between.getLowerValue()),
between.isLowerInclusive() || indexIsQuantized,
getQuantizedValue(between.getUpperValue()),
between.isUpperInclusive() || indexIsQuantized
).values();
}
};
}
else {
throw new IllegalStateException("Unsupported query: " + query);
}
// Fetch results using the supplied function.
// This should return a Collection which is actually just a view onto the index
// which presents a collection of sets containing values selected by the function...
@SuppressWarnings({"unchecked"})
Iterable<ResultSet<O>> results = (Iterable<ResultSet<O>>) lookupFunction.perform();
// Add filtering for quantization (implemented by subclass supporting a Quantizer, a no-op in this class)...
results = addFilteringForQuantization(results, lookupFunction, queryOptions);
return deduplicateIfNecessary(results, query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? Collections.<O>emptySet().iterator() : filterForQuantization(rs, equal, queryOptions).iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs != null && filterForQuantization(rs, equal, queryOptions).contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? 0 : filterForQuantization(rs, equal, queryOptions).size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* An interface which when implemented encapsulates the logic to retrieve zero or more {@link ResultSet}s from an
* index, where the logic for selecting these {@link ResultSet}s is implemented by the {@link #perform()} method.
*
* @param <O> The type of object stored in the result sets
*/
protected abstract class IndexRangeLookupFunction<O> {
protected final boolean filterFirstResultSet;
protected final boolean filterLastResultSet;
protected final Query<O> query;
/**
* The following arguments are useful when the index uses a {@link com.googlecode.cqengine.quantizer.Quantizer},
* and so the stored sets of objects might need to be filtered on retrieval.
*
* @param query The query against which objects should be filtered
* @param filterFirstResultSet True if the first {@link StoredResultSet} returned by the function should be
* filtered to return only objects which actually match the query - typically true for {@link GreaterThan} and
* {@link Between} queries and false for {@link LessThan} queries
* @param filterLastResultSet True if the last {@link StoredResultSet} returned by the function should be
* filtered to return only objects which actually match the query - typically true for {@link LessThan} and
* {@link Between} queries and false for {@link GreaterThan} queries
*/
protected IndexRangeLookupFunction(Query<O> query, boolean filterFirstResultSet, boolean filterLastResultSet) {
this.query = query;
this.filterFirstResultSet = filterFirstResultSet;
this.filterLastResultSet = filterLastResultSet;
}
protected abstract Iterable<? extends ResultSet<O>> perform();
}
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions) {
return wrapNonCloseable(getDistinctKeysInRange(null, true, null, true));
}
@Override
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return wrapNonCloseable(getDistinctKeysInRange(lowerBound, lowerInclusive, upperBound, upperInclusive));
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions) {
return wrapNonCloseable(getDistinctKeysInRange(null, true, null, true).descendingSet());
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return wrapNonCloseable(getDistinctKeysInRange(lowerBound, lowerInclusive, upperBound, upperInclusive).descendingSet());
}
NavigableSet<A> getDistinctKeysInRange(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive) {
NavigableSet<A> results;
if (lowerBound != null && upperBound != null) {
results = indexMap.keySet().subSet(lowerBound, lowerInclusive, upperBound, upperInclusive);
}
else if (lowerBound != null) {
results = indexMap.keySet().tailSet(lowerBound, lowerInclusive);
}
else if (upperBound != null) {
results = indexMap.keySet().headSet(upperBound, upperInclusive);
}
else {
results = indexMap.keySet();
}
return results;
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return super.getCountForKey(key);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return super.getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return super.getStatisticsForDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(final QueryOptions queryOptions) {
final CloseableIterator<A> distinctKeysDescending = getDistinctKeysDescending(queryOptions).iterator();
return wrapNonCloseable(new Iterable<KeyStatistics<A>>() {
@Override
public Iterator<KeyStatistics<A>> iterator() {
return new LazyIterator<KeyStatistics<A>>() {
@Override
protected KeyStatistics<A> computeNext() {
if (distinctKeysDescending.hasNext()){
A key = distinctKeysDescending.next();
return new KeyStatistics<A>(key, getCountForKey(key, queryOptions));
}else{
return endOfData();
}
}
};
}
});
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions) {
return wrapNonCloseable(IteratorUtil.flatten(getKeysAndValuesInRange(null, true, null, true)));
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return wrapNonCloseable(IteratorUtil.flatten(getKeysAndValuesInRange(lowerBound, lowerInclusive, upperBound, upperInclusive)));
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
return wrapNonCloseable(IteratorUtil.flatten(getKeysAndValuesInRange(null, true, null, true).descendingMap()));
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return wrapNonCloseable(IteratorUtil.flatten(getKeysAndValuesInRange(lowerBound, lowerInclusive, upperBound, upperInclusive).descendingMap()));
}
NavigableMap<A, StoredResultSet<O>> getKeysAndValuesInRange(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive) {
NavigableMap<A, StoredResultSet<O>> results;
if (lowerBound != null && upperBound != null) {
results = indexMap.subMap(lowerBound, lowerInclusive, upperBound, upperInclusive);
}
else if (lowerBound != null) {
results = indexMap.tailMap(lowerBound, lowerInclusive);
}
else if (upperBound != null) {
results = indexMap.headMap(upperBound, upperInclusive);
}
else {
results = indexMap;
}
return results;
}
// ---------- Hook methods which can be overridden by subclasses using a Quantizer ----------
/**
* A no-op method which may be overridden by subclasses which use a
* {@link com.googlecode.cqengine.quantizer.Quantizer}.
* <p/>
* <b>This default implementation simply returns the given attribute value unmodified.</b>
* <p/>
* Returns an {@link Iterable} which is similar to the one supplied, but which transparently wraps the first
* {@link ResultSet} and/or the last {@link ResultSet} returned by the supplied {@link Iterable} in a
* {@link QuantizedResultSet}.
* <p/>
* A {@link QuantizedResultSet} transparently filters objects in the wrapped {@link ResultSet} to ensure that
* they match the given {@link Query}. This is necessary when the index uses a
* {@link com.googlecode.cqengine.quantizer.Quantizer}, where objects having several adjacent attribute values
* will be stored together in the same {@link StoredResultSet} in the index.
* <p/>
* For <i>range queries</i> ({@link LessThan}, {@link GreaterThan}, {@link Between}), the {@link StoredResultSet}s
* in an index using a quantizer at the keys in the index referenced by the query, are not guaranteed to only
* contain objects matching the values in the query, due to objects being mixed with their adjacent counterparts.
* Therefore it is necessary to filter the {@link ResultSet} at <i>either end</i> of the range.
*
* @param resultSets {@link com.googlecode.cqengine.resultset.ResultSet}s stored in the index which were found to match the range query, in ascending
* order of their associated keys
* @param lookupFunction Contains parameters specifying whether the first or last {@link com.googlecode.cqengine.resultset.ResultSet}s should be
* wrapped in a {@link com.googlecode.cqengine.resultset.filter.QuantizedResultSet}, and also encapsulates the {@link com.googlecode.cqengine.query.Query} against which objects should
* be filtered
* @param queryOptions Optional parameters for the query
*
* @return An {@link Iterable} optionally with the first and/or last {@link ResultSet}s wrapped in
* {@link QuantizedResultSet}s
*/
protected Iterable<ResultSet<O>> addFilteringForQuantization(final Iterable<ResultSet<O>> resultSets, final IndexRangeLookupFunction<O> lookupFunction, QueryOptions queryOptions) {
return resultSets;
}
/**
* A no-op method which can be overridden by a subclass to return a {@link ResultSet} which filters objects from the
* given {@link ResultSet}, to return only those objects matching the query, for the case that the index is using a
* {@link com.googlecode.cqengine.quantizer.Quantizer}.
* <p/>
* <b>This default implementation simply returns the given {@link ResultSet} unmodified.</b>
*
* @param storedResultSet A {@link com.googlecode.cqengine.resultset.ResultSet} stored against a quantized key in the index
* @param query The query against which results should be matched
* @param queryOptions Optional parameters for the query
*
* @return A {@link ResultSet} which filters objects from the given {@link ResultSet},
* to return only those objects matching the query
*/
protected ResultSet<O> filterForQuantization(ResultSet<O> storedResultSet, Query<O> query, QueryOptions queryOptions) {
return storedResultSet;
}
// ---------- Static factory methods to create NavigableIndexes ----------
/**
* Creates a new {@code NavigableIndex} on the given attribute. The attribute can be a {@link SimpleAttribute} or a
* {@link com.googlecode.cqengine.attribute.MultiValueAttribute}, as long as the type of the attribute referenced
* implements {@link Comparable}.
* <p/>
* @param attribute The attribute on which the index will be built, a {@link SimpleAttribute} or a
* {@link com.googlecode.cqengine.attribute.MultiValueAttribute} where the type of the attribute referenced
* implements {@link Comparable}
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A new HashIndex which will build an index on this attribute
*/
public static <A extends Comparable<A>, O> NavigableIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return onAttribute(new DefaultIndexMapFactory<A, O>(), new DefaultValueSetFactory<O>(), attribute);
}
/**
* Creates a new {@code NavigableIndex} on the given attribute. The attribute can be a {@link SimpleAttribute} or a
* {@link com.googlecode.cqengine.attribute.MultiValueAttribute}, as long as the type of the attribute referenced
* implements {@link Comparable}.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built, a {@link SimpleAttribute} or a
* {@link com.googlecode.cqengine.attribute.MultiValueAttribute} where the type of the attribute referenced
* implements {@link Comparable}
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A new HashIndex which will build an index on this attribute
*/
public static <A extends Comparable<A>, O> NavigableIndex<A, O> onAttribute(Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute) {
return new NavigableIndex<A, O>(indexMapFactory, valueSetFactory, attribute);
}
/**
* Creates a {@link NavigableIndex} on the given attribute using the given {@link Quantizer}.
* <p/>
* @param quantizer A {@link Quantizer} to use in this index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link NavigableIndex} on the given attribute using the given {@link Quantizer}
*/
public static <A extends Comparable<A>, O> NavigableIndex<A, O> withQuantizerOnAttribute(final Quantizer<A> quantizer, Attribute<O, A> attribute) {
return withQuantizerOnAttribute(new DefaultIndexMapFactory<A, O>(), new DefaultValueSetFactory<O>(), quantizer, attribute);
}
/**
* Creates a {@link NavigableIndex} on the given attribute using the given {@link Quantizer}.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param quantizer A {@link Quantizer} to use in this index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link NavigableIndex} on the given attribute using the given {@link Quantizer}
*/
public static <A extends Comparable<A>, O> NavigableIndex<A, O> withQuantizerOnAttribute(Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, final Quantizer<A> quantizer, Attribute<O, A> attribute) {
return new NavigableIndex<A, O>(indexMapFactory, valueSetFactory, attribute) {
// ---------- Override the hook methods related to Quantizer ----------
@Override
protected Iterable<ResultSet<O>> addFilteringForQuantization(final Iterable<ResultSet<O>> resultSets, final IndexRangeLookupFunction<O> lookupFunction, final QueryOptions queryOptions) {
if (!lookupFunction.filterFirstResultSet && !lookupFunction.filterLastResultSet) {
// No filtering required, return the same iterable...
return resultSets;
}
return new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new UnmodifiableIterator<ResultSet<O>>() {
Iterator<? extends ResultSet<O>> resultSetsIterator = resultSets.iterator();
boolean firstResultSet = true;
@Override
public boolean hasNext() {
return resultSetsIterator.hasNext();
}
@Override
public ResultSet<O> next() {
ResultSet<O> rs = resultSetsIterator.next();
if (lookupFunction.filterFirstResultSet && firstResultSet) {
// Filtering is enabled for first ResultSet, and we are processing first ResultSet.
// Wrap it in QuantizedResultSet...
firstResultSet = false;
return new QuantizedResultSet<O>(rs, lookupFunction.query, queryOptions);
}
else if (!lookupFunction.filterLastResultSet || resultSetsIterator.hasNext()) {
// Filtering is disabled for last ResultSet,
// or we are processing a ResultSet which is neither first nor last.
// Don't wrap it...
return rs;
}
else {
// Filtering is enabled for last ResultSet and we are processing last ResultSet.
// Wrap it in QuantizedResultSet...
return new QuantizedResultSet<O>(rs, lookupFunction.query, queryOptions);
}
}
};
}
};
}
@Override
protected A getQuantizedValue(A attributeValue) {
return quantizer.getQuantizedValue(attributeValue);
}
@Override
protected ResultSet<O> filterForQuantization(ResultSet<O> storedResultSet, Query<O> query, QueryOptions queryOptions) {
return new QuantizedResultSet<O>(storedResultSet, query, queryOptions);
}
@Override
public boolean isQuantized() {
return true;
}
};
}
/**
* Creates an index map using default settings.
*/
public static class DefaultIndexMapFactory<A, O> implements Factory<ConcurrentNavigableMap<A, StoredResultSet<O>>> {
@Override
public ConcurrentNavigableMap<A, StoredResultSet<O>> create() {
return new ConcurrentSkipListMap<A, StoredResultSet<O>>();
}
}
/**
* Creates a value set using default settings.
*/
public static class DefaultValueSetFactory<O> implements Factory<StoredResultSet<O>> {
@Override
public StoredResultSet<O> create() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
}
}
| 28,826 | 47.530303 | 268 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/suffix/SuffixTreeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.suffix;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.concurrenttrees.radix.node.NodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.suffix.ConcurrentSuffixTree;
import com.googlecode.concurrenttrees.suffix.SuffixTree;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.AbstractAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.DeduplicationOption;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.query.simple.StringContains;
import com.googlecode.cqengine.query.simple.StringEndsWith;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.connective.ResultSetUnion;
import com.googlecode.cqengine.resultset.connective.ResultSetUnionAll;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentSuffixTree}.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* <li>
* {@link StringEndsWith}
* </li>
* <li>
* {@link StringContains}
* </li>
* </ul>
*
* @author Niall Gallagher
*/
public class SuffixTreeIndex<A extends CharSequence, O> extends AbstractAttributeIndex<A, O> implements OnHeapTypeIndex {
private static final int INDEX_RETRIEVAL_COST = 53;
final NodeFactory nodeFactory;
volatile SuffixTree<StoredResultSet<O>> tree;
/**
* Package-private constructor, used by static factory methods.
*/
protected SuffixTreeIndex(Attribute<O, A> attribute) {
this(attribute, new DefaultCharArrayNodeFactory());
}
/**
* Package-private constructor, used by static factory methods.
*/
protected SuffixTreeIndex(Attribute<O, A> attribute, NodeFactory nodeFactory) {
super(attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(StringEndsWith.class);
add(StringContains.class);
}});
this.nodeFactory = nodeFactory;
this.tree = new ConcurrentSuffixTree<StoredResultSet<O>>(nodeFactory);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final SuffixTree<StoredResultSet<O>> tree = this.tree;
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions, tree);
}
else if (queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions, tree);
}
else if (queryClass.equals(StringEndsWith.class)) {
@SuppressWarnings("unchecked")
final StringEndsWith<O, A> stringEndsWith = (StringEndsWith<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.iterator();
}
@Override
public boolean contains(O object) {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.getMergeCost();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
else if (queryClass.equals(StringContains.class)) {
@SuppressWarnings("unchecked")
final StringContains<O, A> stringContains = (StringContains<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContaining(stringContains.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.iterator();
}
@Override
public boolean contains(O object) {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContaining(stringContains.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContaining(stringContains.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContaining(stringContains.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.getMergeCost();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final SuffixTree<StoredResultSet<O>> tree) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions, final SuffixTree<StoredResultSet<O>> tree) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? Collections.<O>emptySet().iterator() : rs.iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs != null && rs.contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* If a query option specifying logical deduplication was supplied, wrap the given result sets in
* {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
* <p/>
* An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
* {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
*
* @param results Provides the result sets to union
* @param query The query for which the union is being constructed
* @param queryOptions Specifies whether or not logical deduplication is required
* @return A union view over the given result sets
*/
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
if (DeduplicationOption.isLogicalElimination(queryOptions)
&& !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
return new ResultSetUnion<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
else {
return new ResultSetUnionAll<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
}
/**
* @return A {@link StoredSetBasedResultSet} based on a set backed by {@link ConcurrentHashMap}, as created via
* {@link java.util.Collections#newSetFromMap(java.util.Map)}
*/
public StoredResultSet<O> createValueSet() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final SuffixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Look up StoredResultSet for the value...
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
// No StoredResultSet, create and add one...
valueSet = createValueSet();
StoredResultSet<O> existingValueSet = tree.putIfAbsent(attributeValue, valueSet);
if (existingValueSet != null) {
// Another thread won race to add new value set, use that one...
valueSet = existingValueSet;
}
}
// Add the object to the StoredResultSet for this value...
modified |= valueSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final SuffixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
continue;
}
modified |= valueSet.remove(object);
if (valueSet.isEmpty()) {
tree.remove(attributeValue);
}
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.tree = new ConcurrentSuffixTree<StoredResultSet<O>>(new DefaultCharArrayNodeFactory());
}
// ---------- Static factory methods to create SuffixTreeIndexes ----------
/**
* Creates a new {@link SuffixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link SuffixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> SuffixTreeIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return new SuffixTreeIndex<A, O>(attribute);
}
/**
* Creates a new {@link SuffixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param nodeFactory The NodeFactory to be used by the tree
* @param <O> The type of the object containing the attribute
* @return A {@link SuffixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> SuffixTreeIndex<A, O> onAttributeUsingNodeFactory(Attribute<O, A> attribute, NodeFactory nodeFactory) {
return new SuffixTreeIndex<A, O>(attribute, nodeFactory);
}
}
| 18,052 | 39.207127 | 149 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/LazyCloseableIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.concurrenttrees.common.LazyIterator;
/**
* @author niall.gallagher
*/
public abstract class LazyCloseableIterator<T> extends LazyIterator<T> implements CloseableIterator<T> {
}
| 854 | 33.2 | 104 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/KeyStatistics.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.metadata.KeyFrequency;
/**
* Statistics of an index key.
*
* @author niall.gallagher
*/
public class KeyStatistics<A> implements KeyFrequency<A> {
final A key;
final Integer count;
public KeyStatistics(A key, Integer count) {
this.key = key;
this.count = count;
}
public A getKey() {
return key;
}
public Integer getCount() {
return count;
}
/**
* Equivalent to {@link #getCount()}.
*/
@Override
public int getFrequency() {
return getCount();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof KeyStatistics)) {
return false;
}
KeyStatistics<?> that = (KeyStatistics<?>) o;
if (count != that.count) {
return false;
}
return key.equals(that.key);
}
@Override
public int hashCode() {
int result = key.hashCode();
result = 31 * result + count;
return result;
}
@Override
public String toString() {
return key + " " + count;
}
}
| 1,836 | 21.679012 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/CloseableRequestResources.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.io.Closeable;
import java.util.*;
/**
* A QueryOption that allows to keep track of query resources which were opened to process a request and
* which need to be closed when processing of the request is finished.
* <p/>
* The {@link #add(Closeable)} method is used to add {@link Closeable} objects to this object.
* Then when processing the request has finished (often when {@link ResultSet#close()} is called), the engine will
* retrieve this object from the query options and call the {@link #close()} method on this object, which will close
* all resources which had been added.
*
* @author Silvano Riz
*/
public class CloseableRequestResources implements Closeable {
final Collection<Closeable> requestResources = Collections.newSetFromMap(new IdentityHashMap<Closeable, Boolean>());
/**
* Add a new resource that needs to be closed.
*
* @param closeable The resource that needs to be closed
*/
public void add(Closeable closeable) {
requestResources.add(closeable);
}
public CloseableResourceGroup addGroup() {
CloseableResourceGroup group = new CloseableResourceGroup();
add(group);
return group;
}
/**
* Close and removes all resources and resource groups which have been added so far.
*/
@Override
public void close() {
for (Iterator<Closeable> iterator = requestResources.iterator(); iterator.hasNext(); ) {
Closeable closeable = iterator.next();
closeQuietly(closeable);
iterator.remove();
}
}
/**
* Returns an existing {@link CloseableRequestResources} from the QueryOptions, or adds a new
* instance to the query options and returns that.
*
* @param queryOptions The {@link QueryOptions}
* @return The existing QueryOptions's CloseableRequestResources or a new instance.
*/
public static CloseableRequestResources forQueryOptions(final QueryOptions queryOptions) {
CloseableRequestResources closeableRequestResources = queryOptions.get(CloseableRequestResources.class);
if (closeableRequestResources == null) {
closeableRequestResources = new CloseableRequestResources();
queryOptions.put(CloseableRequestResources.class, closeableRequestResources);
}
return closeableRequestResources;
}
/**
* Closes an existing {@link CloseableRequestResources} if one is stored the QueryOptions and then removes
* it from the QueryOptions.
*
* @param queryOptions The {@link QueryOptions}
*/
public static void closeForQueryOptions(QueryOptions queryOptions) {
closeQuietly(queryOptions.get(CloseableRequestResources.class));
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
// Ignore
}
}
}
public class CloseableResourceGroup implements Closeable {
final Set<Closeable> groupResources = Collections.newSetFromMap(new IdentityHashMap<Closeable, Boolean>());
public boolean add(Closeable closeable) {
return groupResources.add(closeable);
}
/**
* Closes all resources in this group, and then removes the group from the request resources.
*/
@Override
public void close() {
for (Iterator<Closeable> iterator = groupResources.iterator(); iterator.hasNext(); ) {
Closeable closeable = iterator.next();
CloseableRequestResources.closeQuietly(closeable);
iterator.remove();
}
requestResources.remove(this);
}
@Override
public String toString() {
return groupResources.toString();
}
}
}
| 4,659 | 35.40625 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/IndexSupport.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.DeduplicationOption;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.connective.ResultSetUnion;
import com.googlecode.cqengine.resultset.connective.ResultSetUnionAll;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
/**
* <p> Index utilities
*
* @author Silvano Riz
*/
public class IndexSupport {
private IndexSupport(){}
/**
* <p> If a query option specifying logical deduplication was supplied, wrap the given result sets in {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
*
* <p> There are two exceptions where a {@link ResultSetUnionAll} is used regardless of the logical deduplication query option:
* <ul>
* <li>
* If the index is built on a SimpleAttribute which means that the same object could not exist in more than one {@link StoredResultSet}.
* </li>
* <li>
* If the query is an {@link In} query and it is marked as disjoint ( {@link In#isDisjoint()} returns true )
* </li>
* </ul>
*
* @param results Provides the result sets to union
* @param query The query for which the union is being constructed
* @param queryOptions Specifies whether or not logical deduplication is required
* @param retrievalCost The resultSet retrieval cost
* @return A union view over the given result sets
*/
public static <O, A> ResultSet<O> deduplicateIfNecessary(final Iterable<? extends ResultSet<O>> results,
final Query<O> query,
final Attribute<O, A> attribute,
final QueryOptions queryOptions,
final int retrievalCost) {
boolean logicalElimination = DeduplicationOption.isLogicalElimination(queryOptions);
boolean attributeHasAtMostOneValue = (attribute instanceof SimpleAttribute || attribute instanceof SimpleNullableAttribute);
boolean queryIsADisjointInQuery = query instanceof In && ((In) query).isDisjoint();
if (!logicalElimination || attributeHasAtMostOneValue || queryIsADisjointInQuery) {
// No need to deduplicate...
return new ResultSetUnionAll<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return retrievalCost;
}
};
} else {
// We need to deduplicate...
return new ResultSetUnion<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return retrievalCost;
}
};
}
}
}
| 3,882 | 44.151163 | 174 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/KeyValue.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
/**
* Provides access to a key-value pair.
* <p/>
* The implementation is free to generate and encapsulate the key and value in this object eagerly,
* or generated it on-demand lazily.
*
* @author niall.gallagher
*/
public interface KeyValue<A, O> {
A getKey();
O getValue();
}
| 947 | 28.625 | 99 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/AbstractAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
/**
* A skeleton implementation of an index which implements the {@link Index#supportsQuery(Query, QueryOptions)} method, based on a set
* of queries supported by a subclass supplied to the constructor.
*
* @author Niall Gallagher
*
* @param <A> The type of the attribute on which this index will be built
* @param <O> The type of the object containing the attribute
*/
public abstract class AbstractAttributeIndex<A, O> implements AttributeIndex<A, O> {
protected final Set<Class<? extends Query>> supportedQueries;
protected final Attribute<O, A> attribute;
/**
* Protected constructor, called by subclasses.
*
* @param attribute The attribute on which the index will be built
* @param supportedQueries The set of {@link Query} types which the subclass implementation supports
*/
protected AbstractAttributeIndex(Attribute<O, A> attribute, Set<Class<? extends Query>> supportedQueries) {
this.attribute = attribute;
// Note: Ideally supportedQueries would be varargs to simplify subclasses, but varargs causes generic array
// creation warnings.
this.supportedQueries = Collections.unmodifiableSet(supportedQueries);
}
/**
* Returns the attribute which was supplied to the constructor.
*
* @return the attribute which was supplied to the constructor
*/
public Attribute<O, A> getAttribute() {
return attribute;
}
/**
* {@inheritDoc}
*/
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return supportedQueries.contains(query.getClass());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractAttributeIndex that = (AbstractAttributeIndex) o;
if (!attribute.equals(that.attribute)) return false;
return true;
}
@Override
public int hashCode() {
int result = getClass().hashCode();
result = 31 * result + attribute.hashCode();
return result;
}
}
| 3,049 | 32.888889 | 133 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/AbstractMapBasedAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
/**
* An abstract implementation of an index backed by a {@link java.util.concurrent.ConcurrentMap}, where the exact map
* implementation is provided by a factory supplied to the constructor.
* <p/>
* This class implements the methods to actually build the index and update it when objects are added or removed.
* Subclasses will implement methods to retrieve from the index, using logic appropriate to the particular
* implementation.
* <p/>
* This class also provides some static utility methods useful to map-based implementations.
*
* @author Niall Gallagher
*/
public abstract class AbstractMapBasedAttributeIndex<A, O, MapType extends ConcurrentMap<A, StoredResultSet<O>>> extends AbstractAttributeIndex<A, O> {
protected final Factory<MapType> indexMapFactory;
protected final Factory<StoredResultSet<O>> valueSetFactory;
protected final MapType indexMap;
/**
* Protected constructor, called by subclasses.
*
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built
* @param supportedQueries The set of {@link Query} types which the subclass implementation supports
*/
protected AbstractMapBasedAttributeIndex(Factory<MapType> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute, Set<Class<? extends Query>> supportedQueries) {
super(attribute, supportedQueries);
this.indexMapFactory = indexMapFactory;
this.valueSetFactory = valueSetFactory;
this.indexMap = indexMapFactory.create();
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
ConcurrentMap<A, StoredResultSet<O>> indexMap = this.indexMap;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Replace attributeValue with quantized value if applicable...
attributeValue = getQuantizedValue(attributeValue);
// Look up StoredResultSet for the value...
StoredResultSet<O> valueSet = indexMap.get(attributeValue);
if (valueSet == null) {
// No StoredResultSet, create and add one...
valueSet = valueSetFactory.create();
StoredResultSet<O> existingValueSet = indexMap.putIfAbsent(attributeValue, valueSet);
if (existingValueSet != null) {
// Another thread won race to add new value set, use that one...
valueSet = existingValueSet;
}
}
// Add the object to the StoredResultSet for this value...
modified |= valueSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
ConcurrentMap<A, StoredResultSet<O>> indexMap = this.indexMap;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Replace attributeValue with quantized value if applicable...
attributeValue = getQuantizedValue(attributeValue);
StoredResultSet<O> valueSet = indexMap.get(attributeValue);
if (valueSet == null) {
continue;
}
modified |= valueSet.remove(object);
if (valueSet.isEmpty()) {
indexMap.remove(attributeValue);
}
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.indexMap.clear();
}
protected CloseableIterable<A> getDistinctKeys() {
return wrapNonCloseable(this.indexMap.keySet());
}
protected CloseableIterable<KeyValue<A, O>> getKeysAndValues() {
return wrapNonCloseable(IteratorUtil.flatten(this.indexMap));
}
protected static <T> CloseableIterable<T> wrapNonCloseable(final Iterable<T> iterable) {
return new CloseableIterable<T>() {
@Override
public CloseableIterator<T> iterator() {
return new CloseableIterator<T>() {
final Iterator<T> iterator = iterable.iterator();
@Override
public void close() {
// No-op.
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
};
}
protected Integer getCountForKey(A key) {
StoredResultSet<O> objectsForKey = this.indexMap.get(key);
return objectsForKey == null ? 0 : objectsForKey.size();
}
protected Integer getCountOfDistinctKeys(QueryOptions queryOptions){
return this.indexMap.keySet().size();
}
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions){
final Iterator<A> distinctKeysIterator = this.indexMap.keySet().iterator();
return wrapNonCloseable(new Iterable<KeyStatistics<A>>() {
@Override
public Iterator<KeyStatistics<A>> iterator() {
return new LazyIterator<KeyStatistics<A>>() {
@Override
protected KeyStatistics<A> computeNext() {
if (distinctKeysIterator.hasNext()) {
A key = distinctKeysIterator.next();
return new KeyStatistics<A>(key, getCountForKey(key));
} else {
return endOfData();
}
}
};
}
});
}
// ---------- Hook methods which can be overridden by indexes using a Quantizer ----------
/**
* {@inheritDoc}
* A method which should be overridden to return true, by subclasses which use a
* {@link com.googlecode.cqengine.quantizer.Quantizer}. This implementation returns false by default.
*/
@Override
public boolean isQuantized() {
return false;
}
/**
* A no-op method which may be overridden by subclasses which use a
* {@link com.googlecode.cqengine.quantizer.Quantizer}.
* <p/>
* <b>This default implementation simply returns the given attribute value unmodified.</b>
*
* @param attributeValue A value returned by an attribute
* @return A quantized version of the attribute value
*/
protected A getQuantizedValue(A attributeValue) {
return attributeValue;
}
}
| 9,495 | 36.832669 | 198 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/UnmodifiableNavigableSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import java.util.*;
/**
* A read-only view of a NavigableSet.
* <p/>
* This is provided for compatibility with Java 6 which lacks a {@code Collections#unmodifiableNavigableSet()} method.
*/
public class UnmodifiableNavigableSet<E> implements NavigableSet<E> {
private final NavigableSet<E> delegate;
public UnmodifiableNavigableSet(NavigableSet<E> delegate) {
this.delegate = delegate;
}
@Override
public E lower(E e) {
return delegate.lower(e);
}
@Override
public E floor(E e) {
return delegate.floor(e);
}
@Override
public E ceiling(E e) {
return delegate.ceiling(e);
}
@Override
public E higher(E e) {
return delegate.higher(e);
}
@Override
public E pollFirst() {
throw new UnsupportedOperationException();
}
@Override
public E pollLast() {
throw new UnsupportedOperationException();
}
private transient UnmodifiableNavigableSet<E> descendingSet;
@Override
public NavigableSet<E> descendingSet() {
UnmodifiableNavigableSet<E> result = descendingSet;
if (result == null) {
result = descendingSet = new UnmodifiableNavigableSet<E>(
delegate.descendingSet());
result.descendingSet = this;
}
return result;
}
@Override
public Iterator<E> descendingIterator() {
return new UnmodifiableIterator<E>() {
Iterator<E> i = delegate.descendingIterator();
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public E next() {
return i.next();
}
};
}
@Override
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return new UnmodifiableNavigableSet<E>(delegate.subSet(
fromElement,
fromInclusive,
toElement,
toInclusive));
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new UnmodifiableNavigableSet<E>(delegate.headSet(toElement, inclusive));
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new UnmodifiableNavigableSet<E>(
delegate.tailSet(fromElement, inclusive));
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
Iterator<E> i = delegate.iterator();
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public E next() {
return i.next();
}
};
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return new UnmodifiableNavigableSet<E>(delegate.subSet(fromElement, true, toElement, false));
}
@Override
public SortedSet<E> headSet(E toElement) {
return new UnmodifiableNavigableSet<E>(delegate.headSet(toElement, false));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return new UnmodifiableNavigableSet<E>(delegate.tailSet(fromElement, true));
}
@Override
public Comparator<? super E> comparator() {
return delegate.comparator();
}
@Override
public E first() {
return delegate.first();
}
@Override
public E last() {
return delegate.last();
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public Object[] toArray() {
return delegate.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return delegate.toArray(a);
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
} | 5,789 | 23.956897 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/KeyStatisticsIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* An index which allows the set of distinct keys to be queried, and which can return statistics on the number of
* objects stored in the buckets for each key.
* <p/>
* Note that this interface reads statistics about keys and NOT about attribute values from the index.
* Often those statistics will be the same, however if a {@link com.googlecode.cqengine.quantizer.Quantizer} is
* configured for an index, then often objects for several attribute values may have the same key and may be stored
* in the same bucket.
*
* Created by niall.gallagher on 09/01/2015.
*/
public interface KeyStatisticsIndex<A, O> extends Index<O> {
/**
* @return The distinct keys in the index
* @param queryOptions Optional parameters for the query
*/
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions);
/**
* @param key A key which may be contained in the index
* @param queryOptions Optional parameters for the query
* @return The number of objects stored in the bucket in the index with the given key
*/
public Integer getCountForKey(A key, QueryOptions queryOptions);
/**
* Returns the count of distinct keys in the index.
*
* @param queryOptions Optional parameters for the query
* @return The count of distinct keys in the index.
*/
public Integer getCountOfDistinctKeys(QueryOptions queryOptions);
/**
* Returns the statistics {@link KeyStatistics} for all distinct keys in the index
*
* @param queryOptions Optional parameters for the query
* @return The statistics {@link KeyStatistics} for all distinct keys in the index
*/
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions);
/**
* Returns the keys and corresponding values for those keys in the index. Note the same key
* will be returned multiple times if more than one object has the same key. Also the same value might be returned
* multiple times, each time for a different key, if the index is built on a multi-value attribute.
*
* @return The keys and corresponding values for those keys in the index
*
* @param queryOptions Optional parameters for the query
*/
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions);
}
| 3,103 | 40.386667 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/SortedKeyStatisticsIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* An index which allows the set of distinct keys to be queried in sorted order, and which can return statistics on the
* number of objects stored for each key.
*
* Created by niall.gallagher on 09/01/2015.
*/
public interface SortedKeyStatisticsIndex<A extends Comparable<A>, O> extends KeyStatisticsIndex<A, O> {
/**
* Returns the distinct keys in the index, in ascending order.
* @return The distinct keys in the index, in ascending order
* @param queryOptions Optional parameters for the query
*/
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions);
/**
* Returns distinct keys within an optional range from the index, in ascending order.
*
* @param lowerBound The lower bound for the keys returned, or null if no lower bound should be applied
* @param lowerInclusive true if the lowerBound is inclusive, false if exclusive
* @param upperBound The upper bound for the keys returned, or null if no upper bound should be applied
* @param upperInclusive true if the lowerBound is inclusive, false if exclusive
* @param queryOptions Optional parameters for the query
* @return The distinct keys in the index within the given bounds, in ascending order
*/
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions);
/**
* Returns the distinct keys in the index, in descending order.
* @return The distinct keys in the index, in descending order
* @param queryOptions Optional parameters for the query
*/
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions);
/**
* Returns distinct keys within an optional range from the index, in descending order.
*
* @param lowerBound The lower bound for the keys returned, or null if no lower bound should be applied
* @param lowerInclusive true if the lowerBound is inclusive, false if exclusive
* @param upperBound The upper bound for the keys returned, or null if no upper bound should be applied
* @param upperInclusive true if the lowerBound is inclusive, false if exclusive
* @param queryOptions Optional parameters for the query
* @return The distinct keys in the index within the given bounds, in descending order
*/
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions);
/**
* Returns the statistics {@link KeyStatistics} for all distinct keys in the index, in descending order
*
* @param queryOptions Optional parameters for the query
* @return The statistics {@link KeyStatistics} for all distinct keys in the index, in descending order
*/
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(QueryOptions queryOptions);
/**
* Returns the keys and corresponding values for those keys in the index. Note the same key
* will be returned multiple times if more than one object has the same key. Also the same value might be returned
* multiple times, each time for a different key, if the index is built on a multi-value attribute.
*
* @return The keys and corresponding values for those keys in the index, in ascending order of key
*
* @param queryOptions Optional parameters for the query
*/
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions);
/**
* Returns the keys within an optional range and corresponding values for those keys in the index. Note the same key
* will be returned multiple times if more than one object has the same key. Also the same value might be returned
* multiple times, each time for a different key, if the index is built on a multi-value attribute.
*
* @param lowerBound The lower bound for the keys returned, or null if no lower bound should be applied
* @param lowerInclusive true if the lowerBound is inclusive, false if exclusive
* @param upperBound The upper bound for the keys returned, or null if no upper bound should be applied
* @param upperInclusive true if the lowerBound is inclusive, false if exclusive
* @param queryOptions Optional parameters for the query
*
* @return The keys and corresponding values for those keys in the index, in ascending order of key
*/
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions);
/**
* Returns the keys and corresponding values for those keys in the index. Note the same key
* will be returned multiple times if more than one object has the same key. Also the same value might be returned
* multiple times, each time for a different key, if the index is built on a multi-value attribute.
*
* @return The keys and corresponding values for those keys in the index, in ascending order of key
*
* @param queryOptions Optional parameters for the query
*/
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions);
/**
* Returns the keys within an optional range and corresponding values for those keys in the index. Note the same key
* will be returned multiple times if more than one object has the same key. Also the same value might be returned
* multiple times, each time for a different key, if the index is built on a multi-value attribute.
*
* @param lowerBound The lower bound for the keys returned, or null if no lower bound should be applied
* @param lowerInclusive true if the lowerBound is inclusive, false if exclusive
* @param upperBound The upper bound for the keys returned, or null if no upper bound should be applied
* @param upperInclusive true if the lowerBound is inclusive, false if exclusive
* @param queryOptions Optional parameters for the query
*
* @return The keys and corresponding values for those keys in the index, in descending order of key
*/
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions);
}
| 7,088 | 53.953488 | 175 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/CloseableIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
/**
* @author niall.gallagher
*/
public interface CloseableIterator<T> extends Iterator<T>, Closeable {
@Override
void close();
}
| 875 | 28.2 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/Factory.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
/**
* A generic factory for an object of type T.
* <p/>
* This is "inspired" by Guava's Supplier or Guice's Provider interface. The purpose of this CQEngine-specific
* interface is allow a degree of dependency injection/decoupling internally in CQEngine, without imposing a
* dependency on a particular dependency injection framework on the application.
*
* @author Niall Gallagher
*/
public interface Factory<T> {
/**
* Creates an object.
* @return a new instance of the object
*/
public T create();
}
| 1,187 | 32.942857 | 110 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/KeyValueMaterialized.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import java.util.Objects;
/**
* Encapsulates a key-value pair.
*
* @author niall.gallagher
*/
public class KeyValueMaterialized<A, O> implements KeyValue<A, O> {
final A key;
final O value;
public KeyValueMaterialized(A key, O value) {
this.key = key;
this.value = value;
}
@Override
public A getKey() {
return key;
}
@Override
public O getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyValueMaterialized<?, ?> that = (KeyValueMaterialized<?, ?>) o;
return key.equals(that.key) &&
value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return key + "=" + value;
}
}
| 1,594 | 23.921875 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/PartialIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.engine.CollectionQueryEngine;
import com.googlecode.cqengine.engine.ModificationListener;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.index.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.persistence.support.FilteredObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.WrappedResultSet;
import java.util.*;
/**
* An index which indexes and can answer queries on a subset of the collection; a kind of hybrid between a
* {@link StandingQueryIndex} and a {@link CompoundIndex}.
* <p/>
* A partial index wraps a backing index and adds only a subset of objects which match a given <i>filter
* query</i> to the backing index. As such, a partial index accelerates queries on an "interesting subset"
* of the collection, without incurring the overhead of indexing the entire collection.
* <p/>
* Partial indexes require less storage space or memory than non-partial indexes, and they can yield better
* query performance as well, because they will contain fewer irrelevant entries not pertaining to the query.
* <p/>
* Partial indexes are also particularly useful when used with index-accelerated ordering. They can store
* results which match a given filter query in pre-sorted order of the given attribute, which means that
* requesting results for that query and ordered by that attribute at runtime, can be answered quickly by
* the partial index without requiring any post-filtering or post-sorting.
* <p/>
* <b>The conditions under which a partial index will be used are as follows.</b><br/>
*
* Two conditions must be satisfied:
* <ol>
* <li>
* The backing index must support the branch of the query being evaluated.<br/>
* For example if a branch of the query is a <code>between()</code> query on a certain attribute,
* the backing index must support <code>between()</code> queries on that attribute.
* </li>
* <li>
* The root query must be compatible with the configured filter query for this partial index.<br/>
* Let <i>f</i> = the configured filter query, and <i>r</i> = the root query.<br/>
* Both of these may be any type of query (for example simple queries or complex
* <i>and()</i>/<i>or()</i>/<i>not()</i> queries).<br/>
* This partial index will indicate it supports the root query, if the root query satisfies <i>any</i> of
* the following conditions:
* <ul>
* <li><i>r</i> equals <i>f</i></li>
* <li><i>r</i> is an <code>And</code> query, which has <i>f</i> as any one of its direct children:
* <i>and(x, y, f, z)</i></li>
* <li><i>r</i> is an <code>And</code> query and <i>f</i> is an <code>And</code> query,
* and the direct children of <i>f</i> are also the
* direct children of <i>r</i>: <i>f</i> = <i>and(a, b)</i>, <i>r</i> = <i>and(x, a, y, b)</i></li>
* </ul>
* </li>
* </ol>
* These conditions are implemented by the {@link #supportsQuery(Query, QueryOptions)} method.
*
* @author niall.gallagher
*/
public abstract class PartialIndex<A, O, I extends AttributeIndex<A, O>> implements AttributeIndex<A, O> {
// An integer to add or subtract to the retrieval cost returned by the backing index,
// so that given a choice between a regular index and a partial index,
// the retrieval cost from the partial index will be lower and so it will be chosen.
// This is because partial indexes contain less data which is irrelevant to the query,
// and so can incur less filtering...
static final int INDEX_RETRIEVAL_COST_DELTA = -5;
protected final Query<O> filterQuery;
protected final Attribute<O, A> attribute;
protected volatile I backingIndex;
/**
* Protected constructor, called by subclasses.
*
* @param attribute The attribute on which the index is built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialIndex(Attribute<O, A> attribute, Query<O> filterQuery) {
this.attribute = attribute;
this.filterQuery = filterQuery;
}
protected I backingIndex() {
if (backingIndex == null) {
synchronized (this) { // Double-checked locking to prevent duplicate index creation
if (backingIndex == null) {
backingIndex = createBackingIndex();
}
}
}
return backingIndex;
}
public Attribute<O, A> getAttribute() {
return backingIndex().getAttribute();
}
public Query<O> getFilterQuery() {
return filterQuery;
}
public AttributeIndex<A, O> getBackingIndex() {
return backingIndex;
}
/**
* Returns true if this partial index can answer this branch of the query.
* <p/>
* See the class JavaDoc for the conditions which must be satisfied for this method to return true.
*
* @param query The query supplied by the query engine, which is typically a branch of the overall query being
* evaluated.
*/
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
// Extract the root query from the query options, and check if it contains the filter query...
@SuppressWarnings("unchecked")
Query<O> rootQuery = (Query<O>) queryOptions.get(CollectionQueryEngine.ROOT_QUERY);
return supportsQueryInternal(backingIndex(), filterQuery, rootQuery, query, queryOptions);
}
static <A, O, I extends AttributeIndex<A, O>> boolean supportsQueryInternal(I backingIndex,
Query<O> filterQuery,
Query<O> rootQuery,
Query<O> branchQuery,
QueryOptions queryOptions) {
if (!backingIndex.supportsQuery(branchQuery, queryOptions)) {
return false;
}
// Check: rootQuery equals filterQuery
if (filterQuery.equals(rootQuery)) {
return true;
}
if (!(rootQuery instanceof And)) {
return false;
}
// Check: rootQuery (r) is an And query, which has filterQuery (f) as any one of its direct children:
// r = and(x, y, f, z)
And<O> rootAndQuery = (And<O>)rootQuery;
if (rootAndQuery.getChildQueries().contains(filterQuery)) {
return true;
}
// Check: rootQuery (r) is an And query and filterQuery (f) is an And query,
// and the direct children of f are also the direct children of r:
// f = and(a, b), r = and(x, a, y, b)
if (!(filterQuery instanceof And)) {
return false;
}
And<O> filterAndQuery = ((And<O>) filterQuery);
return rootAndQuery.getChildQueries().containsAll(filterAndQuery.getChildQueries());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PartialIndex)) {
return false;
}
PartialIndex<?, ?, ?> that = (PartialIndex<?, ?, ?>) o;
if (!filterQuery.equals(that.filterQuery)) {
return false;
}
return backingIndex().equals(that.backingIndex());
}
@Override
public int hashCode() {
int result = filterQuery.hashCode();
result = 31 * result + backingIndex().hashCode();
return result;
}
@Override
public boolean isMutable() {
return backingIndex().isMutable();
}
@Override
public boolean isQuantized() {
return backingIndex().isQuantized();
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
return new WrappedResultSet<O>(backingIndex().retrieve(query, queryOptions)) {
@Override
public int getRetrievalCost() {
return super.getRetrievalCost() + INDEX_RETRIEVAL_COST_DELTA;
}
};
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
backingIndex().init(new FilteredObjectStore<O>(objectStore, filterQuery), queryOptions);
}
/**
* Calls {@link ModificationListener#destroy(QueryOptions)} on the backing index.
*
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
backingIndex().destroy(queryOptions);
}
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
Collection<O> matchingSubset = filter(objectSet, queryOptions);
return backingIndex().addAll(ObjectSet.fromCollection(matchingSubset), queryOptions);
}
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
Collection<O> matchingSubset = filter(objectSet, queryOptions);
return backingIndex().removeAll(ObjectSet.fromCollection(matchingSubset), queryOptions);
}
@Override
public void clear(QueryOptions queryOptions) {
backingIndex().clear(queryOptions);
}
protected Collection<O> filter(ObjectSet<O> objects, QueryOptions queryOptions) {
CloseableIterator<O> objectsIterator = objects.iterator();
try {
Collection<O> matchingSubset = new HashSet<O>();
while (objectsIterator.hasNext()) {
O candidate = objectsIterator.next();
if (filterQuery.matches(candidate, queryOptions)) {
matchingSubset.add(candidate);
}
}
return matchingSubset;
}
finally {
objectsIterator.close();
}
}
protected abstract I createBackingIndex();
}
| 11,345 | 39.091873 | 114 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/DefaultConcurrentSetFactory.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Creates a concurrent implementation of a {@link java.util.Set}, based on {@link ConcurrentHashMap}.
*
* @author Niall Gallagher
*/
public class DefaultConcurrentSetFactory<O> implements Factory<Set<O>> {
final int initialSize;
public DefaultConcurrentSetFactory() {
this.initialSize = 16;
}
public DefaultConcurrentSetFactory(int initialSize) {
this.initialSize = initialSize;
}
@Override
public Set<O> create() {
return Collections.newSetFromMap(new ConcurrentHashMap<O, Boolean>(initialSize));
}
}
| 1,322 | 29.068182 | 102 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/KeyStatisticsAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.index.AttributeIndex;
/**
* Implemented by indexes which support key statistics and are attribute-centric.
* See the extended interfaces for details.
*/
public interface KeyStatisticsAttributeIndex<A, O> extends AttributeIndex<A, O>, KeyStatisticsIndex<A, O> {
}
| 950 | 35.576923 | 107 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/PartialSortedKeyStatisticsAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A {@link PartialIndex} which supports the index statistics interface {@link SortedKeyStatisticsAttributeIndex}.
*
* @author niall.gallagher
*/
public abstract class PartialSortedKeyStatisticsAttributeIndex<A extends Comparable<A>, O> extends PartialIndex<A, O, SortedKeyStatisticsAttributeIndex<A, O>> implements SortedKeyStatisticsAttributeIndex<A, O> {
/**
* Protected constructor, called by subclasses.
*
* @param attribute The attribute on which the index is built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialSortedKeyStatisticsAttributeIndex(Attribute<O, A> attribute, Query<O> filterQuery) {
super(attribute, filterQuery);
}
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeys(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getDistinctKeys(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(QueryOptions queryOptions) {
return backingIndex().getDistinctKeysDescending(queryOptions);
}
@Override
public CloseableIterable<A> getDistinctKeysDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getDistinctKeysDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeysDescending(QueryOptions queryOptions) {
return backingIndex().getStatisticsForDistinctKeysDescending(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions) {
return backingIndex().getKeysAndValues(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getKeysAndValues(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
return backingIndex().getKeysAndValuesDescending(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
return backingIndex().getKeysAndValuesDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return backingIndex().getCountForKey(key, queryOptions);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return backingIndex().getStatisticsForDistinctKeys(queryOptions);
}
}
| 4,251 | 41.949495 | 211 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/CloseableIterable.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
/**
* @author niall.gallagher
*/
public interface CloseableIterable<T> extends Iterable<T> {
@Override
abstract CloseableIterator<T> iterator();
}
| 810 | 30.192308 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/SortedKeyStatisticsAttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.index.AttributeIndex;
/**
* Implemented by indexes which support sorted key statistics and are attribute-centric.
* See the extended interfaces for details.
*/
public interface SortedKeyStatisticsAttributeIndex<A extends Comparable<A>, O> extends SortedKeyStatisticsIndex<A, O>, KeyStatisticsAttributeIndex<A, O>, AttributeIndex<A, O> {
}
| 1,026 | 38.5 | 176 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/indextype/OffHeapTypeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support.indextype;
/**
* A marker interfaces for indexes which are persisted in off-heap memory.
*
* Created by npgall on 29/04/2016.
*/
public interface OffHeapTypeIndex {
}
| 822 | 31.92 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/indextype/NonHeapTypeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support.indextype;
/**
* A marker interfaces for indexes which may be persisted in off-heap memory or on disk.
*
* @author Niall Gallagher
*/
public interface NonHeapTypeIndex {
}
| 827 | 32.12 | 88 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/indextype/OnHeapTypeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support.indextype;
/**
* A marker interfaces for indexes which are persisted on-heap.
* Created by npgall on 29/04/2016.
*/
public interface OnHeapTypeIndex {
}
| 808 | 31.36 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/support/indextype/DiskTypeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support.indextype;
/**
* A marker interfaces for indexes which are persisted on disk.
*
* Created by npgall on 29/04/2016.
*/
public interface DiskTypeIndex {
}
| 808 | 31.36 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/standingquery/StandingQueryIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.standingquery;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
/**
* An index which stores objects matching any type of query, and which can answer arbitrarily complex
* queries in constant time complexity.
* <p/>
* A standing query index must be added ahead of time for the exact query which is to be accelerated.
* <p/>
* Note that it is possible to add a standing query index on any <i>fragment</i> of a query, as well as whole queries.
* CQEngine will accelerate evaluation of query fragments (branches, or nested sub-trees within queries) using any
* standing query indexes which match those fragments.
* <p/>
*
* @author Niall Gallagher
*/
public class StandingQueryIndex<O> implements Index<O>, OnHeapTypeIndex {
private static final int INDEX_RETRIEVAL_COST = 10;
private final Query<O> standingQuery;
private final StoredResultSet<O> storedResultSet = new StoredSetBasedResultSet<O>(
Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()),
INDEX_RETRIEVAL_COST
);
public StandingQueryIndex(Query<O> standingQuery) {
this.standingQuery = standingQuery;
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
*
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
public Query<O> getStandingQuery() {
return standingQuery;
}
/**
* {@inheritDoc}
* <p/>
* <b>This implementation always returns true, as this index supports all types of query.</b>
*
* @return true, this index supports all types of query
*/
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return standingQuery.equals(query);
}
@Override
public boolean isQuantized() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(final Query<O> query, QueryOptions queryOptions) {
if (!supportsQuery(query, queryOptions)) {
// TODO: check necessary?
throw new IllegalArgumentException("Unsupported query: " + query);
}
return storedResultSet;
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
storedResultSet.clear();
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
for (O object : objectSet) {
if (standingQuery.matches(object, queryOptions)) {
modified |= storedResultSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
for (O object : objectSet) {
if (standingQuery.matches(object, queryOptions)) {
modified |= storedResultSet.remove(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
* @param queryOptions
*/
@Override
public void clear(QueryOptions queryOptions) {
storedResultSet.clear();
}
@Override
public String toString() {
return "StandingQueryIndex{" +
"standingQuery=" + standingQuery +
'}';
}
/**
* A static factory method for convenience.
* <p/>
* Equivalent to {@code new StandingQueryIndex<Query<O>, O>(standingQuery)}.
* <p/>
* @param standingQuery The standing query on which the index will be built
* @param <O> The type of the objects in the collection being indexed
* @return A new StandingQueryIndex which will build an index on this standing query
*/
public static <O> StandingQueryIndex<O> onQuery(Query<O> standingQuery) {
return new StandingQueryIndex<O>(standingQuery);
}
}
| 5,836 | 28.933333 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/fallback/FallbackIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.fallback;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.ComparativeQuery;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.All;
import com.googlecode.cqengine.query.simple.None;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
/**
* A special index which when asked to retrieve data simply scans the underlying collection for matching objects.
* This index does not maintain any data structure of its own.
* <p/>
* This index supports <b>all</b> query types, because it it relies on the supplied query object itself
* to determine if objects in the collection match the query, by calling
* {@link Query#matches(Object, com.googlecode.cqengine.query.option.QueryOptions)}.
* <p/>
* The query engine automatically uses this <i>fallback</i> index when an attribute is referenced by a query,
* and no other index has been added for that attribute that supports the query.
* <p/>
* The time complexity of retrievals from this fallback index is usually O(n) - linear, proportional to the number of
* objects in the collection.
*
* @author Niall Gallagher
*/
public class FallbackIndex<O> implements Index<O> {
private static final int INDEX_RETRIEVAL_COST = Integer.MAX_VALUE;
private static final int INDEX_MERGE_COST = Integer.MAX_VALUE;
volatile ObjectStore<O> objectStore = null;
public FallbackIndex() {
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
*
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* {@inheritDoc}
* <p/>
* <b>This implementation always returns true, as this index supports all types of query.</b>
*
* @return true, this index supports all types of query
*/
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final ObjectSet<O> objectSet = ObjectSet.fromObjectStore(objectStore, queryOptions);
return new ResultSet<O>() {
@SuppressWarnings("unchecked")
@Override
public Iterator<O> iterator() {
if (query instanceof All) {
return IteratorUtil.wrapAsUnmodifiable(objectSet.iterator());
}
else if (query instanceof None) {
return Collections.<O>emptyList().iterator();
}
else if (query instanceof ComparativeQuery) {
return ((ComparativeQuery<O, ?>)query).getMatches(objectSet, queryOptions).iterator();
}
else {
return new FilteringIterator<O>(objectSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return query.matches(object, queryOptions);
}
};
}
}
@Override
public boolean contains(O object) {
// Contains is based on objects contained in this *filtered* ResultSet, so delegate to iterator...
return IteratorUtil.iterableContains(this, object);
}
@Override
public int size() {
// Size is based on objects contained in this *filtered* ResultSet, so delegate to iterator...
return IteratorUtil.countElements(this);
}
@Override
public boolean matches(O object) {
return query instanceof ComparativeQuery ? contains(object) : query.matches(object, queryOptions);
}
@Override
public int getRetrievalCost() {
// None is a special case where we know it can't match any objects, and therefore retrieval cost is 0...
return query instanceof None ? 0 : INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// None is a special case where we know it can't match any objects, and therefore merge cost is 0...
return query instanceof None ? 0 : INDEX_MERGE_COST;
}
@Override
public void close() {
objectSet.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* {@inheritDoc}
* <p/>
* <b>In this implementation, does nothing.</b>
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
// No need to take any action
return false;
}
/**
* {@inheritDoc}
* <p/>
* <b>In this implementation, does nothing.</b>
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
// No need to take any action
return false;
}
/**
* {@inheritDoc}
* <p/>
* <b>In this implementation, stores a reference to the supplied collection, which the
* {@link Index#retrieve(com.googlecode.cqengine.query.Query, com.googlecode.cqengine.query.option.QueryOptions)} method can subsequently iterate.</b>
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
// Store the collection...
this.objectStore = objectStore;
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
* @param queryOptions
*/
@Override
public void clear(QueryOptions queryOptions) {
objectStore.clear(queryOptions);
}
}
| 7,289 | 33.549763 | 154 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/radixreversed/ReversedRadixTreeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.radixreversed;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.concurrenttrees.radix.node.NodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radixreversed.ConcurrentReversedRadixTree;
import com.googlecode.concurrenttrees.radixreversed.ReversedRadixTree;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.AbstractAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.DeduplicationOption;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.query.simple.StringEndsWith;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.connective.ResultSetUnion;
import com.googlecode.cqengine.resultset.connective.ResultSetUnionAll;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentReversedRadixTree}.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* <li>
* {@link StringEndsWith}
* </li>
* </ul>
*
* @author Niall Gallagher
*/
public class ReversedRadixTreeIndex<A extends CharSequence, O> extends AbstractAttributeIndex<A, O> implements OnHeapTypeIndex {
private static final int INDEX_RETRIEVAL_COST = 51;
final NodeFactory nodeFactory;
volatile ReversedRadixTree<StoredResultSet<O>> tree;
/**
* Package-private constructor, used by static factory methods.
*/
protected ReversedRadixTreeIndex(Attribute<O, A> attribute) {
this(attribute, new DefaultCharArrayNodeFactory());
}
/**
* Package-private constructor, used by static factory methods.
*/
protected ReversedRadixTreeIndex(Attribute<O, A> attribute, NodeFactory nodeFactory) {
super(attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
add(StringEndsWith.class);
}});
this.nodeFactory = nodeFactory;
this.tree = new ConcurrentReversedRadixTree<StoredResultSet<O>>(nodeFactory);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final ReversedRadixTree<StoredResultSet<O>> tree = this.tree;
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions, tree);
}
else if (queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions, tree);
}
else if (queryClass.equals(StringEndsWith.class)) {
@SuppressWarnings("unchecked")
final StringEndsWith<O, A> stringEndsWith = (StringEndsWith<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.iterator();
}
@Override
public boolean contains(O object) {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysEndingWith(stringEndsWith.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.getMergeCost();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final ReversedRadixTree<StoredResultSet<O>> tree) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions, final ReversedRadixTree<StoredResultSet<O>> tree) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? Collections.<O>emptySet().iterator() : rs.iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs != null && rs.contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* If a query option specifying logical deduplication was supplied, wrap the given result sets in
* {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
* <p/>
* An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
* {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
*
* @param results Provides the result sets to union
* @param query The query for which the union is being constructed
* @param queryOptions Specifies whether or not logical deduplication is required
* @return A union view over the given result sets
*/
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
if (DeduplicationOption.isLogicalElimination(queryOptions)
&& !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
return new ResultSetUnion<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
else {
return new ResultSetUnionAll<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
}
/**
* @return A {@link StoredSetBasedResultSet} based on a set backed by {@link ConcurrentHashMap}, as created via
* {@link java.util.Collections#newSetFromMap(java.util.Map)}
*/
public StoredResultSet<O> createValueSet() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final ReversedRadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Look up StoredResultSet for the value...
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
// No StoredResultSet, create and add one...
valueSet = createValueSet();
StoredResultSet<O> existingValueSet = tree.putIfAbsent(attributeValue, valueSet);
if (existingValueSet != null) {
// Another thread won race to add new value set, use that one...
valueSet = existingValueSet;
}
}
// Add the object to the StoredResultSet for this value...
modified |= valueSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final ReversedRadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
continue;
}
modified |= valueSet.remove(object);
if (valueSet.isEmpty()) {
tree.remove(attributeValue);
}
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.tree = new ConcurrentReversedRadixTree<StoredResultSet<O>>(new DefaultCharArrayNodeFactory());
}
// ---------- Static factory methods to create ReversedRadixTreeIndexes ----------
/**
* Creates a new {@link ReversedRadixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link ReversedRadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> ReversedRadixTreeIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return new ReversedRadixTreeIndex<A, O>(attribute);
}
/**
* Creates a new {@link ReversedRadixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param nodeFactory The NodeFactory to be used by the tree
* @param <O> The type of the object containing the attribute
* @return A {@link ReversedRadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> ReversedRadixTreeIndex<A, O> onAttributeUsingNodeFactory(Attribute<O, A> attribute, NodeFactory nodeFactory) {
return new ReversedRadixTreeIndex<A, O>(attribute, nodeFactory);
}
}
| 15,779 | 38.949367 | 156 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/radix/RadixTreeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.radix;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
import com.googlecode.concurrenttrees.radix.RadixTree;
import com.googlecode.concurrenttrees.radix.node.NodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.AbstractAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.query.simple.StringStartsWith;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentRadixTree}.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* <li>
* {@link StringStartsWith}
* </li>
* </ul>
*
* @author Niall Gallagher
*/
public class RadixTreeIndex<A extends CharSequence, O> extends AbstractAttributeIndex<A, O> implements OnHeapTypeIndex {
private static final int INDEX_RETRIEVAL_COST = 50;
final NodeFactory nodeFactory;
volatile RadixTree<StoredResultSet<O>> tree;
/**
* Package-private constructor, used by static factory methods.
*/
protected RadixTreeIndex(Attribute<O, A> attribute) {
this(attribute, new DefaultCharArrayNodeFactory());
}
/**
* Package-private constructor, used by static factory methods.
*/
protected RadixTreeIndex(Attribute<O, A> attribute, NodeFactory nodeFactory) {
super(attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
add(StringStartsWith.class);
}});
this.nodeFactory = nodeFactory;
this.tree = new ConcurrentRadixTree<StoredResultSet<O>>(nodeFactory);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final RadixTree<StoredResultSet<O>> tree = this.tree;
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions, tree);
}
else if (queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions, tree);
}
else if (queryClass.equals(StringStartsWith.class)) {
@SuppressWarnings("unchecked")
final StringStartsWith<O, A> stringStartsWith = (StringStartsWith<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysStartingWith(stringStartsWith.getValue());
ResultSet<O> rs = deduplicateIfNecessary(resultSets, query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
return rs.iterator();
}
@Override
public boolean contains(O object) {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysStartingWith(stringStartsWith.getValue());
ResultSet<O> rs = deduplicateIfNecessary(resultSets, query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
return rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysStartingWith(stringStartsWith.getValue());
ResultSet<O> rs = deduplicateIfNecessary(resultSets, query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
return rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysStartingWith(stringStartsWith.getValue());
ResultSet<O> rs = deduplicateIfNecessary(resultSets, query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
return rs.getMergeCost();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final RadixTree<StoredResultSet<O>> tree) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions, final RadixTree<StoredResultSet<O>> tree) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? Collections.<O>emptySet().iterator() : rs.iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs != null && rs.contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* @return A {@link StoredSetBasedResultSet} based on a set backed by {@link ConcurrentHashMap}, as created via
* {@link java.util.Collections#newSetFromMap(java.util.Map)}
*/
public StoredResultSet<O> createValueSet() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final RadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Look up StoredResultSet for the value...
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
// No StoredResultSet, create and add one...
valueSet = createValueSet();
StoredResultSet<O> existingValueSet = tree.putIfAbsent(attributeValue, valueSet);
if (existingValueSet != null) {
// Another thread won race to add new value set, use that one...
valueSet = existingValueSet;
}
}
// Add the object to the StoredResultSet for this value...
modified |= valueSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final RadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
continue;
}
modified |= valueSet.remove(object);
if (valueSet.isEmpty()) {
tree.remove(attributeValue);
}
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.tree = new ConcurrentRadixTree<StoredResultSet<O>>(new DefaultCharArrayNodeFactory());
}
// ---------- Static factory methods to create RadixTreeIndexes ----------
/**
* Creates a new {@link RadixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link RadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> RadixTreeIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return new RadixTreeIndex<A, O>(attribute);
}
/**
* Creates a new {@link RadixTreeIndex} on the specified attribute, using the specified NodeFactory.
* <p/>
* @param attribute The attribute on which the index will be built
* @param nodeFactory The NodeFactory to be used by the tree
* @param <O> The type of the object containing the attribute
* @return A {@link RadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> RadixTreeIndex<A, O> onAttributeUsingNodeFactory(Attribute<O, A> attribute, NodeFactory nodeFactory) {
return new RadixTreeIndex<A, O>(attribute, nodeFactory);
}
}
| 13,970 | 38.02514 | 148 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/offheap/PartialOffHeapIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.offheap;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.PartialIndex;
import com.googlecode.cqengine.index.support.PartialSortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OffHeapTypeIndex;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.query.Query;
import static com.googlecode.cqengine.index.sqlite.support.DBUtils.sanitizeForTableName;
/**
* A {@link PartialIndex} which uses {@link OffHeapPersistence}.
*
* @author niall.gallagher
*/
public class PartialOffHeapIndex<A extends Comparable<A>, O> extends PartialSortedKeyStatisticsAttributeIndex<A, O> implements OffHeapTypeIndex {
final String tableNameSuffix;
/**
* Protected constructor, called by subclasses.
*
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
*/
protected PartialOffHeapIndex(Attribute<O, A> attribute, Query<O> filterQuery) {
super(attribute, filterQuery);
this.tableNameSuffix = "_partial_" + sanitizeForTableName(filterQuery.toString());
}
@Override
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
protected SortedKeyStatisticsAttributeIndex<A, O> createBackingIndex() {
return new OffHeapIndex(OffHeapPersistence.class, attribute, tableNameSuffix) {
@Override
public Index getEffectiveIndex() {
return PartialOffHeapIndex.this.getEffectiveIndex();
}
};
}
// ---------- Static factory methods to create PartialOffHeapIndex ----------
/**
* Creates a new {@link PartialOffHeapIndex}. This will obtain details of the {@link OffHeapPersistence} to use from the
* IndexedCollection, throwing an exception if the IndexedCollection has not been configured with a suitable
* OffHeapPersistence.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param filterQuery The filter query which matches the subset of objects to be stored in this index.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return A {@link OffHeapIndex} on the given attribute.
*/
public static <A extends Comparable<A>, O> PartialOffHeapIndex<A, O> onAttributeWithFilterQuery(final Attribute<O, A> attribute, final Query<O> filterQuery) {
return new PartialOffHeapIndex<A, O>(attribute, filterQuery);
}
}
| 3,387 | 43.578947 | 162 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/offheap/OffHeapIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.offheap;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.sqlite.SimplifiedSQLiteIndex;
import com.googlecode.cqengine.index.support.indextype.OffHeapTypeIndex;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.WrappedResultSet;
/**
* An index persisted in native memory within the JVM process but outside the Java heap.
* <p/>
* This index is similar to the on-heap {@link com.googlecode.cqengine.index.navigable.NavigableIndex} and supports
* the same types of queries.
* <p/>
* The current implementation of this index is based on {@link com.googlecode.cqengine.index.sqlite.SQLiteIndex}.
*
* @author niall.gallagher
*/
public class OffHeapIndex<A extends Comparable<A>, O, K extends Comparable<K>> extends SimplifiedSQLiteIndex<A, O, K> implements OffHeapTypeIndex {
// An integer to add or subtract to the retrieval cost returned by SimplifiedSQLiteIndex (which ranges 80-89).
// Therefore the retrieval costs for this index will range from 70-79...
static final int INDEX_RETRIEVAL_COST_DELTA = -10;
OffHeapIndex(Class<? extends OffHeapPersistence<O, A>> persistenceType, Attribute<O, A> attribute, String tableNameSuffix) {
super(persistenceType, attribute, tableNameSuffix);
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
return new WrappedResultSet<O>(super.retrieve(query, queryOptions)) {
@Override
public int getRetrievalCost() {
return super.getRetrievalCost() + INDEX_RETRIEVAL_COST_DELTA;
}
};
}
// ---------- Static factory methods to create OffHeapIndex ----------
/**
* Creates a new {@link OffHeapIndex}.
*
* @param attribute The {@link Attribute} on which the index will be built.
* @param <A> The type of the attribute to be indexed.
* @param <O> The type of the object containing the attribute.
* @return An {@link OffHeapIndex} on the given attribute.
*/
@SuppressWarnings("unchecked") // unchecked, because type K will be provided later via the init() method
public static <A extends Comparable<A>, O> OffHeapIndex<A, O, ? extends Comparable<?>> onAttribute(final Attribute<O, A> attribute) {
return new OffHeapIndex(OffHeapPersistence.class, attribute, "");
}
}
| 3,218 | 43.708333 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/unique/UniqueIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.unique;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.TransactionalIndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.index.support.AbstractAttributeIndex;
import com.googlecode.cqengine.index.support.Factory;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentHashMap}, which can be more efficient than {@link HashIndex} when used with
* (and only with) attributes which uniquely identify objects (primary key-type attributes).
* <p/>
* This type of index does not store a set of objects matching each attribute value, but instead stores only a
* single object for each value. This results in faster query performance, and often lower memory usage, but has some
* trade-offs.
* <p/>
* This index will throw an exception if a duplicate object is detected for an existing attribute value. That condition
* means however that inconsistencies might already have arisen between this and other indexes as a result of the
* application's misuse of this index.
* <p/>
* <b>Trade-offs: {@code UniqueIndex} versus {@code HashIndex}</b>
* <ul>
* <li>
* {@code UniqueIndex} will always use less memory than a <i>non-quantized</i> {@code HashIndex}
* </li>
* <li>
* {@code UniqueIndex} will not necessarily use less memory than a <i>quantized</i> {@code HashIndex}, i.e.
* configured with a {@link com.googlecode.cqengine.quantizer.Quantizer}
* </li>
* <li>
* In all cases, {@code UniqueIndex} will answer queries faster than a {@code HashIndex}
* </li>
* <li>
* It is important that {@code UniqueIndex} only be used with attributes which uniquely identify objects
* </li>
* <li>
* <b>A {@code UniqueIndex} on a primary key-type attribute might not be compatible with the MVCC algorithm
* implemented by {@link TransactionalIndexedCollection}.</b>
* <ul><li>
* However, as an alternative option to reduce memory overhead in those situations see:
* {@link HashIndex#onSemiUniqueAttribute(Attribute)}
* </li></ul>
* </li>
* </ul>
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* </ul>
*
* @author Kinz Liu
* @author Niall Gallagher
*/
public class UniqueIndex<A,O> extends AbstractAttributeIndex<A,O> implements OnHeapTypeIndex {
protected static final int INDEX_RETRIEVAL_COST = 25;
protected final Factory<ConcurrentMap<A,O>> indexMapFactory;
protected final ConcurrentMap<A,O> indexMap;
/**
* Package-private constructor, used by static factory methods. Creates a new UniqueIndex initialized to index the
* supplied attribute.
*
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param attribute The attribute on which the index will be built
*/
protected UniqueIndex(Factory<ConcurrentMap<A,O>> indexMapFactory, Attribute<O, A> attribute) {
super(attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
}});
this.indexMapFactory = indexMapFactory;
this.indexMap = indexMapFactory.create();
}
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
Class<?> queryClass = query.getClass();
return queryClass.equals(Equal.class) || queryClass.equals(In.class);
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
*
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class))
{
final ConcurrentMap<A, O> indexMap = this.indexMap;
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions, indexMap);
}
else if(queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions, indexMap);
}
throw new IllegalArgumentException("Unsupported query: " + query);
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final ConcurrentMap<A, O> indexMap) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, indexMap);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions, final ConcurrentMap<A, O> indexMap) {
final O obj = indexMap.get(equal.getValue());
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
return new UnmodifiableIterator<O>() {
boolean hasNext = (obj != null);
@Override
public boolean hasNext() {
return this.hasNext;
}
@Override
public O next() {
this.hasNext=false;
return obj;
}
};
}
@Override
public boolean contains(O object) {
return (object != null && obj != null && object.equals(obj));
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
return obj == null ? 0 : 1;
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
return obj == null ? 0 : 1;
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
ConcurrentMap<A, O> indexMap = this.indexMap;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
O existingValue = indexMap.put(attributeValue, object);
if (existingValue != null && !existingValue.equals(object)) {
throw new UniqueConstraintViolatedException(
"The application has attempted to add a duplicate object to the UniqueIndex on attribute '"
+ attribute.getAttributeName() +
"', potentially causing inconsistencies between indexes. " +
"UniqueIndex should not be used with attributes which do not uniquely identify objects. " +
"Problematic attribute value: '" + attributeValue + "', " +
"problematic duplicate object: " + object);
}
modified = true;
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
ConcurrentMap<A, O> indexMap = this.indexMap;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
modified |= (indexMap.remove(attributeValue) != null);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.indexMap.clear();
}
public static class UniqueConstraintViolatedException extends RuntimeException {
public UniqueConstraintViolatedException(String message) {
super(message);
}
}
/**
* Creates an index map using default settings.
*/
public static class DefaultIndexMapFactory<A, O> implements Factory<ConcurrentMap<A, O>> {
@Override
public ConcurrentMap<A, O> create() {
return new ConcurrentHashMap<A, O>();
}
}
// ---------- Static factory methods to create UniqueIndexes ----------
/**
* Creates a new {@link UniqueIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link UniqueIndex} on this attribute
*/
public static <A, O> UniqueIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return onAttribute(new DefaultIndexMapFactory<A, O>(), attribute);
}
/**
* Creates a new {@link UniqueIndex} on the specified attribute.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link UniqueIndex} on this attribute
*/
public static <A, O> UniqueIndex<A, O> onAttribute(Factory<ConcurrentMap<A, O>> indexMapFactory, Attribute<O, A> attribute) {
return new UniqueIndex<A, O>(indexMapFactory, attribute);
}
}
| 13,233 | 36.384181 | 136 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/entity/PrimaryKeyedMapEntity.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.entity;
import java.util.Map;
/**
* An extension of {@link MapEntity} in which a particular entry in the map is designated as a primary key,
* and this primary key will then be used to compute hashCode and test for equality. This can avoid computing
* equality over all keys in the maps.
*/
public class PrimaryKeyedMapEntity extends MapEntity {
private final Object primaryKey;
public PrimaryKeyedMapEntity(Map mapToWrap, Object mapPrimaryKey) {
super(mapToWrap, getPrimaryKeyHashCode(mapToWrap, mapPrimaryKey));
primaryKey = mapPrimaryKey;
}
static int getPrimaryKeyHashCode(Map map, Object primaryKey) {
Object value = map.get(primaryKey);
return value.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PrimaryKeyedMapEntity)) {
return false;
}
PrimaryKeyedMapEntity that = (PrimaryKeyedMapEntity) o;
if (cachedHashCode != that.cachedHashCode) {
return false;
}
Object thisPkValue = this.get(primaryKey);
Object thatPkValue = that.get(primaryKey);
return thisPkValue.equals(thatPkValue);
}
@Override
public String toString() {
return "PrimaryKeyedMapEntity{" +
"primaryKey=" + primaryKey +
", cachedHashCode=" + cachedHashCode +
", wrappedMap=" + wrappedMap +
'}';
}
}
| 2,144 | 31.014925 | 109 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/entity/MapEntity.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.entity;
import com.googlecode.cqengine.query.QueryFactory;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Wrapper for Map to allow efficient use in an IndexCollection.
* MapEntities can be created via {@link QueryFactory#mapEntity(Map)}. Attributes can be created to read the entries
* in these maps, using {@link QueryFactory#mapAttribute(Object, Class)}.
* <p/>
* This works by optimizing the performance of the {@link #hashCode()} and {@link #equals(Object)} methods - which
* may be called frequently during query processing. The hashCode of the wrapped Map will be cached to improve the
* performance of repeated invocations of {@link #hashCode()}. The cached hashCode will be used in the
* implementation of the {@link #equals(Object)} method too, to avoid computing equality entirely when the cached
* hashCodes are different.
* <p/>
* Note it is not safe to modify entries in maps which are indexed, although non-indexed entries may be modified
* safely. Alternatively, remove and re-add the Map to the collection.
*/
@SuppressWarnings({"unchecked", "NullableProblems"})
public class MapEntity implements Map {
final Map wrappedMap;
final int cachedHashCode;
public MapEntity(Map mapToWrap) {
this(mapToWrap, mapToWrap.hashCode());
}
protected MapEntity(Map mapToWrap, int hashCode) {
wrappedMap = mapToWrap;
cachedHashCode = hashCode;
}
/**
* Returns the wrapped map.
*/
public Map getWrappedMap() {
return wrappedMap;
}
/**
* Returns the hashcode of the wrapped map which was cached when this MapEntity was created.
* @return the hashcode of the wrapped map which was cached when this MapEntity was created.
*/
@Override
public int hashCode() {
return cachedHashCode;
}
/**
* Returns true if the cached hashcodes of both objects are equal and the wrapped maps are equal.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MapEntity)) {
return false;
}
MapEntity that = (MapEntity) o;
if (cachedHashCode != that.cachedHashCode) {
return false;
}
return this.wrappedMap.equals(that.wrappedMap);
}
@Override
public String toString() {
return "MapEntity{" +
"cachedHashCode=" + cachedHashCode +
", wrappedMap=" + wrappedMap +
'}';
}
public Object get(Object key) {
return wrappedMap.get(key);
}
@Override
public Object put(Object o, Object o2) {
return wrappedMap.put(o, o2);
}
@Override
public Object remove(Object o) {
return wrappedMap.remove(o);
}
@Override
public void putAll(Map map) {
wrappedMap.putAll(map);
}
@Override
public void clear() {
wrappedMap.clear();
}
@Override
public Set keySet() {
return wrappedMap.keySet();
}
@Override
public Collection values() {
return wrappedMap.values();
}
@Override
public Set<Entry> entrySet() {
return wrappedMap.entrySet();
}
@Override
public int size() {
return wrappedMap.size();
}
@Override
public boolean isEmpty() {
return wrappedMap.isEmpty();
}
@Override
public boolean containsKey(Object o) {
return wrappedMap.containsKey(o);
}
@Override
public boolean containsValue(Object o) {
return wrappedMap.containsValue(o);
}
}
| 4,283 | 26.461538 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/ResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.common.NoSuchObjectException;
import com.googlecode.cqengine.resultset.common.NonUniqueObjectException;
import java.io.Closeable;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* @author Niall Gallagher
*/
public abstract class ResultSet<O> implements Iterable<O>, Closeable {
/**
* Returns an {@link Iterator} over objects matching the query for which this {@link ResultSet} was constructed.
*
* @return An {@link Iterator} over objects matching the query for which this {@link ResultSet} was constructed
*/
public abstract Iterator<O> iterator();
/**
* Returns true if this {@link ResultSet} contains the given object, false if it does not.
* <p/>
* Note that the cost of calling this method will most likely be cheaper than iterating all results to check if an
* object is contained. If indexes are available to support the query, this method will query indexes to check if
* the object is contained, instead of actually retrieving any data.
* <p/>
* See also the {@link #matches(Object)} method, which provides a similar function but often with better performance
* than this method.
*
* @param object The object to check for containment in this {@link ResultSet}
* @return True if this {@link ResultSet} contains the given object, false if it does not
*/
public abstract boolean contains(O object);
/**
* Similar to the {@link #contains(Object)} method, but checks for logical containment in the ResultSet as opposed
* to physical containment in the ResultSet. Determines if the given object would be contained in the ResultSet,
* by testing if the given object matches the query for which this ResultSet was generated, instead of actually
* checking if the object is contained in appropriate indexes.
* <p/>
* This method will typically make the determination by evaluating the query on the given object on-the-fly without
* accessing indexes, however in some cases this method might delegate to the {@link #contains(Object)}
* method to make the determination.
* <p/>
* This method will perform better than {@link #contains(Object)} in cases where querying indexes is more expensive
* than querying attributes, which is usually the case.
*
* @param object The object to check for logical containment in this {@link ResultSet}
* @return True if this {@link ResultSet} logically contains the given object, false if it does not
*/
public abstract boolean matches(O object);
/**
* Returns the query for which this ResultSet provides results.
* @return The query for which this ResultSet provides results.
*/
public abstract Query<O> getQuery();
/**
* Returns the query options associated with the query.
* @return The query options associated with the query.
*/
public abstract QueryOptions getQueryOptions();
/**
* Returns the first object returned by the iterator of this {@link ResultSet}, and throws an exception if
* the iterator does not provide exactly one object.
*
* @return The first object returned by the iterator of this {@link ResultSet}
* @throws NoSuchObjectException If the iterator indicates no object is available
* @throws NonUniqueObjectException If the iterator indicates more than one object is available
*/
public O uniqueResult() {
Iterator<O> iterator = iterator();
if (!iterator.hasNext()) {
throw new NoSuchObjectException("ResultSet is empty");
}
O result = iterator.next();
if (iterator.hasNext()) {
throw new NonUniqueObjectException("ResultSet contains more than one object");
}
return result;
}
/**
* Returns an estimate of the cost of looking up objects matching the query
* underlying this {@code ResultSet} in the index.
* <p/>
* The query engine will use this to select the index with the lowest cost,
* when more than one index supporting the query exists for the same attribute.
* <p/>
* An example: a single-level hash index will typically have a lower retrieval cost than a tree-based index. Of
* course a hash index only supports equality-based retrieval whereas a sorted tree-based index might support
* equality/less than/greater than or range based retrieval. But for an equality-based query, supported by
* both indexes, retrieval cost allows the query engine to <i>prefer</i> the hash index.
*
* @return An estimate of the cost of looking up a particular query in the index
*/
public abstract int getRetrievalCost();
/**
* Returns an estimate of the cost of merging (or otherwise processing) objects matching the query.
* <p/>
* This will typically be based on the number of objects matching the query.
* <ul>
* <li>
* If the query specifies a simple retrieval from an index, this might be the number of objects matching
* the query
* </li>
* <li>
* If the query specifies a union between multiple other sub-queries, this might be the sum of their merge
* costs
* </li>
* <li>
* If the query specifies an intersection, this might be the based on the merge cost of the sub-query with
* the lowest merge cost
* </li>
* </ul>
* The query engine will use this to optimize the order of intersections and unions, and to decide between merging
* versus filtering strategies.
*
* @return An estimate of the cost of merging (or otherwise processing) objects matching a query
*/
public abstract int getMergeCost();
/**
* Returns the number of objects which would be returned by this {@code ResultSet} if iterated.
* <p/>
* Note that the cost of calling this method depends on the query for which it was constructed.
* <p/>
* For simple queries where a single query is supplied and a matching index exists, or where several such simple
* queries are supplied and are connected using a simple {@link com.googlecode.cqengine.query.logical.Or}
* query, calculating the size via this method will be cheaper than iterating through the ResultSet and counting
* the number of objects individually.
* <p/>
* For more complex queries, where intersections must be performed or where no suitable indexes exist, calling this
* method can be non-trivial, but it will always be at least as cheap as iterating through the ResultSet and
* counting the number of objects individually.
*
* @return The number of objects which would be returned by this {@code ResultSet} if iterated
*/
public abstract int size();
/**
* Checks if this {@code ResultSet} if iterated would not return any objects (i.e. the query does not match any
* objects).
* <p/>
* This method can be more efficient than calling {@code #size()} to check simply if no objects would be
* returned.
*
* @return True if this {@code ResultSet} if iterated would not return any objects; false if the {@code ResultSet}
* would return objects
*/
public boolean isEmpty() {
return !iterator().hasNext();
}
/**
* Checks if this {@code ResultSet} if iterated would return some objects (i.e. the query matches some
* objects).
* <p/>
* This method can be more efficient than calling {@code #size()} to check simply if some objects would be
* returned.
*
* @return True if this {@code ResultSet} if iterated would return some objects; false if the {@code ResultSet}
* would not return any objects
*/
public boolean isNotEmpty() {
return iterator().hasNext();
}
/**
* Releases any resources or closes the transaction which was opened for this ResultSet.
* <p/>
* Whether or not it is necessary to close the ResultSet depends on which implementation of
* IndexedCollection is in use and the types of indexes added to it.
*/
public abstract void close();
/**
* Creates a {@link Spliterator} over objects matching the query for which this {@link ResultSet} was constructed.
*
* @return a {@link Spliterator} over objects matching the query for which this {@link ResultSet} was constructed
*/
public Spliterator<O> spliterator() {
return Spliterators.spliteratorUnknownSize(this.iterator(), Spliterator.ORDERED);
}
/**
* Returns a {@link Stream} of objects matching the query for which this {@link ResultSet} was constructed.
* <p>
* The stream is configured such that if {@link Stream#close()} is called, {@link ResultSet#close()} will also be
* called automatically to close the {@link ResultSet}.
* </p>
* @return a {@link Stream} of objects matching the query for which this {@link ResultSet} was constructed
*/
public Stream<O> stream() {
return StreamSupport.stream(this.spliterator(), false)
.onClose(this::close);
}
}
| 10,093 | 44.0625 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/iterator/MarkableIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import java.io.InputStream;
import java.util.*;
/**
* An iterator which wraps a backing iterator, and which adds support for {@link #mark(int)} and {@link #reset()},
* similar to an {@link InputStream}.
* <p/>
* When {@link #mark(int)} is called, the iterator will start buffering the objects it serves, up to the given limit.
* When {@link #reset()} is called, the iterator will start to replay the objects it buffered since {@link #mark(int)}
* was called. When the iterator has then finished replaying the buffered objects, it will continue to read from the
* backing iterator and add them to the buffer, until {@link #mark(int)} is called again.
* <p/>
* To repeatedly replay objects from a certain point, call {@link #reset()} immediately followed by {@link #mark(int)}.
* <br/>
* To stop buffering objects, call mark with {@code readLimit} 0.
*
* @author niall.gallagher
*/
public class MarkableIterator<T> implements Iterator<T> {
// A constant, iterator which returns no elements...
final Iterator<T> emptyIterator = Collections.<T>emptyList().iterator();
// The backing iterator supplied to the constructor, which provides objects we will buffer...
final Iterator<T> backingIterator;
// The possible states this MarkableIterator may be in...
enum State { READ, BUFFER, REPLAY }
// The current state...
State state = State.READ;
// List of objects which have been served since mark() was last called...
List<T> replayBuffer = Collections.emptyList();
// An iterator over objects which are now being replayed, since reset() was called...
Iterator<T> replayIterator = emptyIterator;
// The max number of objects to buffer...
int readLimit = 0;
public MarkableIterator(Iterator<T> backingIterator) {
this.backingIterator = backingIterator;
}
@Override
public boolean hasNext() {
switch (state) {
case READ: case BUFFER: {
return backingIterator.hasNext();
}
case REPLAY: {
return replayIterator.hasNext() || backingIterator.hasNext();
}
default: throw new IllegalStateException(String.valueOf(state));
}
}
@Override
public T next() {
switch (state) {
case READ: {
return backingIterator.next();
}
case BUFFER: {
if (replayBuffer.size() >= readLimit) {
// Invalidate the mark...
replayBuffer.clear();
replayIterator = emptyIterator;
state = State.READ;
return next();
}
T next = backingIterator.next();
replayBuffer.add(next);
return next;
}
case REPLAY: {
if (replayIterator.hasNext()) {
return replayIterator.next();
}
replayIterator = emptyIterator;
state = State.BUFFER;
return next();
}
default: throw new IllegalStateException(String.valueOf(state));
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Starts buffering objects from the backing iterator so that they may be replayed when {@link #reset()} is called.
*
* @param readLimit The maximum limit of objects that can be read before the mark position becomes invalid.
* @see InputStream#mark(int)
*/
public void mark(int readLimit) {
this.readLimit = readLimit;
switch (state) {
case READ: {
replayBuffer = new ArrayList<T>(); // we don't supply initialCapacity, because readLimit can be large e.g. Integer.MAX_VALUE
replayIterator = emptyIterator;
state = State.BUFFER;
return;
}
case BUFFER: {
replayBuffer.clear();
replayIterator = emptyIterator;
return;
}
case REPLAY: {
// Replace the buffer so that objects replayed already are removed, but objects not replayed are kept...
replayBuffer = populateFromIterator(new ArrayList<T>(), replayIterator);
replayIterator = replayBuffer.iterator();
return;
}
default: throw new IllegalStateException(String.valueOf(state));
}
}
/**
* Repositions this iterator to the position at the time the mark method was last called.
* <p/>
* If the mark method has not been called since the iterator was created, or the number of objects read from the
* iterator since mark was last called is larger than the argument to mark at that last call,
* then an IllegalStateException will be thrown.
* <p/>
* Otherwise, the iterator is reset to a state such that all the objects read since the most recent call to mark
* will be resupplied to subsequent callers of the next method, followed by any objects that otherwise would have
* been the next input data as of the time of the call to reset.
*
* @throws IllegalStateException If the iterator has not been marked or the mark has been invalidated
* @see InputStream#reset()
*/
public void reset() {
if (state == State.READ) {
throw new IllegalStateException("Iterator has not been marked or the mark has been invalidated");
}
replayIterator = replayBuffer.iterator();
state = State.REPLAY;
}
List<T> populateFromIterator(List<T> collection, Iterator<T> iterator) {
while (iterator.hasNext()) {
collection.add(iterator.next());
}
return collection;
}
}
| 6,526 | 37.394118 | 140 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/iterator/IteratorUtil.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.index.support.KeyValue;
import com.googlecode.cqengine.index.support.KeyValueMaterialized;
import com.googlecode.cqengine.resultset.filter.MaterializedDeduplicatedIterator;
import java.util.*;
/**
* @author Niall Gallagher
*/
public class IteratorUtil {
public static <O> boolean iterableContains(Iterable<O> iterable, O element) {
for (O contained : iterable) {
if (contained.equals(element)) {
return true;
}
}
return false;
}
public static int countElements(Iterable<?> iterable) {
int count = 0;
// UnusedDeclaration warning is due to iterator.next() being invoked but not used.
// Actually we intentionally invoke iterator.next() even though we don't use it,
// in case iterator implementation requires this per typical usage...
//noinspection UnusedDeclaration
for (Object object : iterable) {
count++;
}
return count;
}
/**
* Returns the elements of {@code unfiltered} that are not null.
*/
public static <T> Iterator<T> removeNulls(final Iterator<T> unfiltered) {
return new LazyIterator<T>() {
@Override protected T computeNext() {
while (unfiltered.hasNext()) {
T element = unfiltered.next();
if (element != null) {
return element;
}
}
return endOfData();
}
};
}
/**
* Wraps the given Iterator as an {@link UnmodifiableIterator}.
*/
public static <T> UnmodifiableIterator<T> wrapAsUnmodifiable(final Iterator<T> iterator) {
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
/**
* Transforms a {@code Map<A, Iterable<O>>} into a stream of {@code KeyValue<A, O>} objects.
*
* @param map The map to be transformed
* @param <A> Type of the key in the map
* @param <O> Type of the objects returned by the Iterables in the map
* @return A flattened stream of {@code KeyValue<A, O>} objects
*/
public static <A, O> Iterable<KeyValue<A, O>> flatten(final Map<A, ? extends Iterable<O>> map) {
return new Iterable<KeyValue<A, O>>() {
@Override
public Iterator<KeyValue<A, O>> iterator() {
return new LazyIterator<KeyValue<A, O>>() {
Iterator<? extends Map.Entry<A, ? extends Iterable<O>>> entriesIterator = map.entrySet().iterator();
Iterator<KeyValue<A, O>> valuesIterator = Collections.<KeyValue<A, O>>emptySet().iterator();
@Override
protected KeyValue<A, O> computeNext() {
while (true) {
if (valuesIterator.hasNext()) {
return valuesIterator.next();
}
if (!entriesIterator.hasNext()) {
return endOfData();
}
Map.Entry<A, ? extends Iterable<O>> entry = entriesIterator.next();
valuesIterator = flatten(entry.getKey(), entry.getValue()).iterator();
}
}
};
}
};
}
/**
* Transforms a key of type {@code A} and an {@code Iterable<O>} into a stream of {@code KeyValue<A, O>}
* objects.
*
* @param key The key to be transformed
* @param values The values to be transformed
* @param <A> Type of the key
* @param <O> Type of the objects returned by the Iterable
* @return A flattened stream of {@code KeyValue<A, O>} objects
*/
public static <A, O> Iterable<KeyValue<A, O>> flatten(final A key, final Iterable<O> values) {
return new Iterable<KeyValue<A, O>>() {
@Override
public Iterator<KeyValue<A, O>> iterator() {
return new LazyIterator<KeyValue<A, O>>() {
final Iterator<O> valuesIterator = values.iterator();
@Override
protected KeyValue<A, O> computeNext() {
return valuesIterator.hasNext() ? new KeyValueMaterialized<A, O>(key, valuesIterator.next()) : endOfData();
}
};
}
};
}
public static <O> Iterator<O> concatenate(final Iterator<? extends Iterable<O>> iterables) {
return new ConcatenatingIterator<O>() {
@Override
public Iterator<O> getNextIterator() {
return iterables.hasNext() ? iterables.next().iterator() : null;
}
};
}
public static <O> Iterator<Set<O>> groupAndSort(final Iterator<? extends KeyValue<?, O>> values, final Comparator<O> comparator) {
return new LazyIterator<Set<O>>() {
final Iterator<? extends KeyValue<?, O>> valuesIterator = values;
Set<O> currentGroup = new TreeSet<O>(comparator);
Object currentKey = null;
@Override
protected Set<O> computeNext() {
while (valuesIterator.hasNext()) {
KeyValue<?, O> next = valuesIterator.next();
if (!next.getKey().equals(currentKey)) {
Set<O> result = currentGroup;
currentKey = next.getKey();
currentGroup = new TreeSet<O>(comparator);
currentGroup.add(next.getValue());
return result;
}
currentGroup.add(next.getValue());
}
if (currentGroup.isEmpty()) {
return endOfData();
}
else {
Set<O> result = currentGroup;
currentGroup = new TreeSet<O>(comparator);
return result;
}
}
};
}
/**
* Sorts the results returned by the given iterator, returning the sorted results as a new iterator, by performing
* a merge-sort into an intermediate array in memory.
* <p/>
* The time complexity for copying the objects into the intermediate array is O(n), and then the cost of sorting is
* additionally O(n log(n)). So overall complexity is O(n) + O(n log(n)).
* <p>
* Note this method does not perform any deduplication of objects. It can be combined with
* {@link #materializedDeduplicate(Iterator)} to achieve that.
*
* @param unsortedIterator An iterator which provides unsorted objects
* @param comparator The comparator to use for sorting
* @param <O> The type of the objects to be sorted
* @return An iterator which returns the objects in sorted order
*/
public static <O> Iterator<O> materializedSort(Iterator<O> unsortedIterator, Comparator<O> comparator) {
final List<O> result = new ArrayList<>();
while (unsortedIterator.hasNext()) {
result.add(unsortedIterator.next());
}
result.sort(comparator);
return result.iterator();
}
/**
* De-duplicates the results returned by the given iterator, by wrapping it in a
* {@link MaterializedDeduplicatedIterator}.
*/
public static <O> Iterator<O> materializedDeduplicate(Iterator<O> iterator) {
return new MaterializedDeduplicatedIterator<O>(iterator);
}
}
| 8,555 | 38.611111 | 134 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/iterator/UnmodifiableIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import java.util.Iterator;
/**
* An iterator whose {@link #remove()} method throws {@code UnsupportedOperationException}.
*
* @author Niall Gallagher
*/
public abstract class UnmodifiableIterator<O> implements Iterator<O> {
/**
* Throws {@code UnsupportedOperationException}.
* @throws UnsupportedOperationException Always
*/
@Override
public final void remove() {
throw new UnsupportedOperationException("Modification not supported");
}
}
| 1,142 | 30.75 | 91 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/iterator/ConcatenatingIterable.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import java.util.Iterator;
/**
* @author Niall Gallagher
*/
public class ConcatenatingIterable<O> implements Iterable<O> {
private final Iterable<? extends Iterable<O>> iterables;
public ConcatenatingIterable(Iterable<? extends Iterable<O>> iterables) {
this.iterables = iterables;
}
@Override
public Iterator<O> iterator() {
final Iterator<? extends Iterable<O>> iterator = iterables.iterator();
return new ConcatenatingIterator<O>() {
@Override
public Iterator<O> getNextIterator() {
return iterator.hasNext() ? iterator.next().iterator() : null;
}
};
}
}
| 1,329 | 30.666667 | 78 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/iterator/ConcatenatingIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author Niall Gallagher
*/
public abstract class ConcatenatingIterator<O> extends UnmodifiableIterator<O> {
private Iterator<O> currentIterator = null;
@Override
public boolean hasNext() {
while (currentIterator == null || !currentIterator.hasNext()) {
currentIterator = getNextIterator();
if (currentIterator == null) {
return false;
}
}
return true;
}
@Override
public O next() {
Iterator<O> currentIterator = this.currentIterator;
if (currentIterator == null) {
throw new NoSuchElementException("No more elements");
}
return currentIterator.next();
}
public abstract Iterator<O> getNextIterator();
public static <O> ConcatenatingIterator<O> concatenate(final Iterable<Iterator<O>> iterators) {
return new ConcatenatingIterator<O>() {
final Iterator<Iterator<O>> iteratorIterator = iterators.iterator();
@Override
public Iterator<O> getNextIterator() {
return iteratorIterator.hasNext() ? iteratorIterator.next() : null;
}
};
}
}
| 1,912 | 30.360656 | 99 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/IteratorCachingResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Iterator;
/**
* A {@link ResultSet} which wraps a backing ResultSet, and which caches the iterator returned by
* the backing ResultSet, to enable repeated invocations on {@code IteratorCachingResultSet.iterator().hasNext()},
* to avoid each time requesting a new iterator from the backing ResultSet.
* <p/>
* An effect of this caching is that if the application calls {@link #isEmpty()} or {@link #isNotEmpty()} on
* this ResultSet before it begins iteration, only one iterator will actually be requested from the backing ResultSet
* because the cached iterator will be reused each time.
* <p/>
* On the other hand, whenever the application actually begins to iterate through results, this ResultSet will
* detect it, and if {@link #iterator()} is invoked again, it will avoid returning the same cached iterator
* and will obtain a new iterator instead.
*
* @author niall.gallagher
*/
public class IteratorCachingResultSet<O> extends WrappedResultSet<O> {
public IteratorCachingResultSet(ResultSet<O> backingResultSet) {
super(backingResultSet);
}
Iterator<O> cachedIterator = null;
@Override
public Iterator<O> iterator() {
if (cachedIterator != null) {
return cachedIterator;
}
final Iterator<O> backingIterator = wrappedResultSet.iterator();
Iterator<O> wrappingIterator = new Iterator<O>() {
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public O next() {
cachedIterator = null;
return backingIterator.next();
}
@Override
public void remove() {
cachedIterator = null;
backingIterator.remove();
}
};
this.cachedIterator = wrappingIterator;
return wrappingIterator;
}
}
| 2,746 | 34.675325 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/NonUniqueObjectException.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
/**
* @author Niall Gallagher
*/
public class NonUniqueObjectException extends RuntimeException {
private static final long serialVersionUID = -5928615245205366453L;
public NonUniqueObjectException() {
}
public NonUniqueObjectException(String s) {
super(s);
}
}
| 950 | 28.71875 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/ResultSets.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.*;
/**
* Utility methods for working with {@link com.googlecode.cqengine.resultset.ResultSet} objects.
*
* @author Niall Gallagher
*/
public class ResultSets {
/**
* 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();
}
};
}
/**
* Returns a list of {@link CostCachingResultSet}s, by copying from the result sets given, wrapping them as
* necessary via {@link #wrapWithCostCachingIfNecessary(ResultSet)}.
*
* @param resultSets a list of {@link CostCachingResultSet}s
*/
public static <O> List<ResultSet<O>> wrapWithCostCachingIfNecessary(Iterable<? extends ResultSet<O>> resultSets) {
List<ResultSet<O>> result = new LinkedList<ResultSet<O>>();
for (ResultSet<O> candidate : resultSets) {
result.add(wrapWithCostCachingIfNecessary(candidate));
}
return result;
}
/**
* Returns the given {@link ResultSet} as-is if it is already an instance of {@link CostCachingResultSet}, otherwise
* wraps it accordingly and returns the result.
* @param resultSet A {@link ResultSet} which may or may not be an instance of {@link CostCachingResultSet}
* @return A {@link CostCachingResultSet} as described
*/
public static <O> ResultSet<O> wrapWithCostCachingIfNecessary(final ResultSet<O> resultSet) {
return resultSet instanceof CostCachingResultSet ? resultSet : new CostCachingResultSet<O>(resultSet);
}
/**
* Private constructor, not used.
*/
ResultSets() {
}
}
| 3,403 | 34.831579 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/WrappedResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Iterator;
/**
* A ResultSet which wraps another. Subclasses may extend this, to override some methods.
*
* @author niall.gallagher
*/
public class WrappedResultSet<O> extends ResultSet<O> {
protected final ResultSet<O> wrappedResultSet;
public WrappedResultSet(ResultSet<O> wrappedResultSet) {
this.wrappedResultSet = wrappedResultSet;
}
@Override
public Iterator<O> iterator() {
return wrappedResultSet.iterator();
}
@Override
public boolean contains(O object) {
return wrappedResultSet.contains(object);
}
@Override
public boolean matches(O object) {
return wrappedResultSet.matches(object);
}
@Override
public int size() {
return wrappedResultSet.size();
}
@Override
public int getRetrievalCost() {
return wrappedResultSet.getRetrievalCost();
}
@Override
public int getMergeCost() {
return wrappedResultSet.getMergeCost();
}
@Override
public void close() {
wrappedResultSet.close();
}
@Override
public Query<O> getQuery() {
return wrappedResultSet.getQuery();
}
@Override
public QueryOptions getQueryOptions() {
return wrappedResultSet.getQueryOptions();
}
}
| 2,105 | 24.682927 | 89 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/QueryCostComparators.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Comparator;
/**
* Stateless comparator singletons for {@link ResultSet}s based on {@link ResultSet#getRetrievalCost()} and
* {@link com.googlecode.cqengine.resultset.ResultSet#getMergeCost()}.
* <p/>
*
* @author Niall Gallagher
*/
public class QueryCostComparators {
private static final Comparator<ResultSet> RETRIEVAL_COST_COMPARATOR = new RetrievalCostComparator();
private static final Comparator<ResultSet> MERGE_COST_COMPARATOR = new MergeCostComparator();
public static Comparator<ResultSet> getRetrievalCostComparator() {
return RETRIEVAL_COST_COMPARATOR;
}
public static Comparator<ResultSet> getMergeCostComparator() {
return MERGE_COST_COMPARATOR;
}
static class RetrievalCostComparator implements Comparator<ResultSet> {
@Override
public int compare(ResultSet o1, ResultSet o2) {
final int o1RetrievalCost = o1.getRetrievalCost();
final int o2RetrievalCost = o2.getRetrievalCost();
if (o1RetrievalCost < o2RetrievalCost) {
return -1;
}
else if (o1RetrievalCost > o2RetrievalCost) {
return +1;
}
else {
return 0;
}
}
}
static class MergeCostComparator implements Comparator<ResultSet> {
@Override
public int compare(ResultSet o1, ResultSet o2) {
final int o1MergeCost = o1.getMergeCost();
final int o2MergeCost = o2.getMergeCost();
if (o1MergeCost < o2MergeCost) {
return -1;
}
else if (o1MergeCost > o2MergeCost) {
return +1;
}
else {
return 0;
}
}
}
}
| 2,496 | 31.012821 | 107 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/NoSuchObjectException.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
/**
* @author Niall Gallagher
*/
public class NoSuchObjectException extends RuntimeException {
private static final long serialVersionUID = 7269599398244063814L;
public NoSuchObjectException() {
}
public NoSuchObjectException(String s) {
super(s);
}
}
| 940 | 28.40625 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/common/CostCachingResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* Caches the merge cost and retrieval costs of a wrapped result set.
* <p>
* Specifically this is to prevent
* <code>java.lang.IllegalArgumentException: Comparison method violates its general contract!</code>
* on Java 7 and later, when the collection is modified concurrently (causing merge costs to change)
* while ResultSets are being sorted.
* </p>
* @author niall.gallagher
*/
public class CostCachingResultSet<O> extends WrappedResultSet<O> {
volatile int cachedMergeCost = -1;
volatile int cachedRetrievalCost = -1;
public CostCachingResultSet(ResultSet<O> wrappedResultSet) {
super(wrappedResultSet);
}
@Override
public int getRetrievalCost() {
return cachedRetrievalCost != -1 ? cachedRetrievalCost : (cachedRetrievalCost = super.getRetrievalCost());
}
@Override
public int getMergeCost() {
return cachedMergeCost != -1 ? cachedMergeCost : (cachedMergeCost = super.getMergeCost());
}
}
| 1,684 | 33.387755 | 114 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/order/AttributeOrdersComparator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.order;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.query.option.AttributeOrder;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* A comparator which sorts result objects according to a list of attributes each with an associated preference for
* ascending or descending order.
*
* @author Roberto Socrates
* @author Niall Gallagher
*/
public class AttributeOrdersComparator<O> implements Comparator<O> {
final List<AttributeOrder<O>> attributeSortOrders;
final QueryOptions queryOptions;
public AttributeOrdersComparator(List<AttributeOrder<O>> attributeSortOrders, QueryOptions queryOptions) {
this.attributeSortOrders = attributeSortOrders;
this.queryOptions = queryOptions;
}
@Override
@SuppressWarnings("unchecked")
public int compare(O o1, O o2) {
for (AttributeOrder<O> attributeOrder : attributeSortOrders) {
Attribute<O, ? extends Comparable> attribute = attributeOrder.getAttribute();
int comparison;
if (attribute instanceof OrderControlAttribute) {
OrderControlAttribute<O> orderControl = (OrderControlAttribute<O>)(OrderControlAttribute)(attribute);
comparison = orderControl.getValue(o1, queryOptions).compareTo(orderControl.getValue(o2, queryOptions));
if (comparison != 0) {
// One of the objects has values for the delegate attribute encapsulated in OrderControlAttribute,
// and the other object does not. Return this difference so that they will be ordered relative to
// each other based whether they have values or not...
return comparison;
}
attribute = (Attribute<O, ? extends Comparable>) orderControl.getDelegateAttribute();
}
comparison = compareAttributeValues(attribute, o1, o2);
if (comparison != 0) {
// Found a difference. Invert the sign if order is descending, and return it...
return attributeOrder.isDescending() ? comparison * -1 : comparison;
}
// else continue checking remaining attributes.
}
// No differences found according to ordering specified, but in case this comparator
// will be used for object equality testing, return 0 only if objects really are equal...
if (o1.equals(o2)) {
return 0;
}
// At this point we have run out of attributeSortOrders: they all returned 0, but because the objects are not
// equal, we cannot return 0.
// Example: This might occur when sorting by [color, price] and two or more different items have the same color
// and the same price. Because a third - tie-breaking - sort order was not supplied, the sort order of items
// which have the same color and price, is unspecified.
// However although the sort order is now unspecified, we should try to preserve the stability of the comparison
// as much as possible: such that
// if comparator.compare(o1, o2) == -1, then it should be the case that
// comparator.compare(o2, o1) == +1.
// Thus we cannot simply return the same result in both of those cases. This can be important when objects are
// added to collections such as {@link java.util.TreeSet} which depend on the stability of the comparison.
// As we don't have any other readily available properties of the objects to use as tie-breakers, we will use
// the hashcodes of the objects instead. As the hashcodes of unequal objects are unlikely to be the same *most
// of the time*, using the hashcodes as a tie-breaker will result in a stable comparison *most of the time*.
// In the rare event that the hashcodes of the unequal objects turn out to be the same however, we will return
// 1 because it seems more important that the comparator is consistent with equals() than it is to be stable...
return o1.hashCode() >= o2.hashCode() ? 1 : -1;
}
<A extends Comparable<A>> int compareAttributeValues(Attribute<O, A> attribute, O o1, O o2) {
if (attribute instanceof SimpleAttribute) {
// Fast code path...
SimpleAttribute<O, A> simpleAttribute = (SimpleAttribute<O, A>)attribute;
return simpleAttribute.getValue(o1, queryOptions).compareTo(simpleAttribute.getValue(o2, queryOptions));
}
else {
// Slower code path...
Iterator<A> o1attributeValues = attribute.getValues(o1, queryOptions).iterator();
Iterator<A> o2attributeValues = attribute.getValues(o2, queryOptions).iterator();
while (o1attributeValues.hasNext() && o2attributeValues.hasNext()) {
A o1attributeValue = o1attributeValues.next();
A o2attributeValue = o2attributeValues.next();
int comparison = o1attributeValue.compareTo(o2attributeValue);
if (comparison != 0) {
// If we found a difference, return it...
return comparison;
}
}
// If the number of attribute values differs, return a difference, object with fewest elements first...
if (o2attributeValues.hasNext()) {
return -1;
}
else if (o1attributeValues.hasNext()) {
return +1;
}
// No differences found...
return 0;
}
}
}
| 6,380 | 49.642857 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/order/MaterializedOrderedResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.order;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.WrappedResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
/**
* A {@code ResultSet} which wraps another {@code ResultSet}, providing an {@link #iterator()} method which returns
* objects from the wrapped ResultSet in sorted order according to a comparator supplied to the constructor of this
* {@code ResultSet}.
* <p/>
* This is implemented by copying objects into an intermediate array in memory, and then performing merge-sort
* on that array.
* <p>
* The time complexity for copying the objects into the intermediate array is O(n), and then the cost of sorting is
* additionally O(n log(n)). So overall complexity is O(n) + O(n log(n)). The {@link #getMergeCost()} method computes
* an approximation of that time complexity, in addition to accounting for an additional O(n) to iterate the final
* results.
*
* @author Niall Gallagher
*/
public class MaterializedOrderedResultSet<O> extends WrappedResultSet<O> {
final Comparator<O> comparator;
/**
* @param wrappedResultSet The ResultSet to be ordered.
* @param comparator The comparator to use for ordering
*
*/
public MaterializedOrderedResultSet(ResultSet<O> wrappedResultSet, Comparator<O> comparator) {
super(wrappedResultSet);
this.comparator = comparator;
}
/**
* Builds an insertion-sorted set from the wrapped {@link ResultSet}, and returns an iterator over the sorted set.
* <p/>
* Time complexity for building an insertion sorted set is <code>O(merge_cost * log(merge_cost))</code>, and then
* iterating it makes this <b><code>O(merge_cost^2 * log(merge_cost))</code></b>. (Merge cost is an approximation
* of the cost of iterating all elements in any result set.)
*
* @return An iterator over a new sorted set built from the wrapped {@link ResultSet}
*/
@Override
public Iterator<O> iterator() {
return IteratorUtil.materializedSort(super.iterator(), comparator);
}
/**
* Merge cost is an approximation of the cost of iterating all elements in any result set. Therefore, this
* method attempts to calculate that approximately.
* <p>
* The time complexity for copying the objects into the intermediate array is O(n). The cost of sorting that array
* is O(n log(n)). The cost to iterate that resulting array is then O(n).
* So overall complexity is O(2n) + O(n log(n)).
*
* @return Where merge_cost is the {@link ResultSet#getMergeCost()} of the wrapped result set,
* this will return ((2 * merge_cost) + (merge_cost * log(merge_cost)))
*/
@Override
public int getMergeCost() {
long mergeCost = super.getMergeCost();
mergeCost = (2 * mergeCost) + (mergeCost * (long)Math.log(mergeCost));
mergeCost = mergeCost < 0 ? Long.MAX_VALUE : mergeCost; // in case it overflowed to a negative number
return (int)Math.min(mergeCost, Integer.MAX_VALUE); // in case it is larger than an int
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* @return the result of calling this method on the wrapped ResultSet
*/
@Override
public boolean isEmpty() {
return wrappedResultSet.isEmpty();
}
/**
* @return the result of calling this method on the wrapped ResultSet
*/
@Override
public boolean isNotEmpty() {
return wrappedResultSet.isNotEmpty();
}
}
| 4,285 | 37.963636 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/order/MaterializedDeduplicatedResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.order;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.WrappedResultSet;
import com.googlecode.cqengine.resultset.filter.MaterializedDeduplicatedIterator;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.Iterator;
/**
* Wraps another {@link ResultSet} and ensures that the {@link Iterator} returned by the {@link #iterator()} method
* never returns the same object more than once.
* <p/>
* The implementation delegates to {@link MaterializedDeduplicatedIterator}.
* <p/>
* Note that the {@link #size()} method in this implementation has O(n) time complexity, because it uses the
* deduplicating iterator to count objects.
*
* @author Niall Gallagher
*/
public class MaterializedDeduplicatedResultSet<O> extends WrappedResultSet<O> {
public MaterializedDeduplicatedResultSet(ResultSet<O> wrappedResultSet) {
super(wrappedResultSet);
}
/**
* Returns an {@link Iterator} which does not return the same object more than once.
* <p/>
* See class JavaDocs for more details. This implementation has <code>O(merge_cost)</code> time complexity.
*
* @return An {@link Iterator} which does not return the same object more than once
*/
@Override
public Iterator<O> iterator() {
return IteratorUtil.materializedDeduplicate(super.iterator());
}
/**
* {@inheritDoc}
* <p/>
* This implementation has <code>O(merge_cost)</code> time complexity, because it delegates to
* the {@link #iterator()} method and counts objects returned.
*/
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* @return the result of calling this method on the wrapped ResultSet
*/
@Override
public boolean isEmpty() {
return wrappedResultSet.isEmpty();
}
/**
* @return the result of calling this method on the wrapped ResultSet
*/
@Override
public boolean isNotEmpty() {
return wrappedResultSet.isNotEmpty();
}
}
| 2,733 | 32.753086 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/stored/StoredSetBasedResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.stored;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Iterator;
import java.util.Set;
/**
* A ResultSet which is stored directly in an index, and supports additional methods to add and remove objects.
* <p/>
* This implementation wraps a backing {@link java.util.Set}.
*
* @author Niall Gallagher
*/
public class StoredSetBasedResultSet<O> extends StoredResultSet<O> {
private final Set<O> backingSet;
private final int retrievalCost;
/**
* Constructor. Initialises the object with retrieval cost 0.
*
* @param backingSet A Set to which methods in this wrapper class will delegate
*/
public StoredSetBasedResultSet(Set<O> backingSet) {
this(backingSet, 0);
}
/**
* Constructor.
*
* @param backingSet A Set to which methods in this wrapper class will delegate
* @param retrievalCost The retrieval cost to subsequently return
*/
public StoredSetBasedResultSet(Set<O> backingSet, int retrievalCost) {
this.backingSet = backingSet;
this.retrievalCost = retrievalCost;
}
@Override
public boolean contains(O o) {
return backingSet.contains(o);
}
/**
* {@inheritDoc}
* <p/>
* This implementation delegates to {@link #contains(Object)}.
*/
@Override
public boolean matches(O object) {
return contains(object);
}
@Override
public Iterator<O> iterator() {
return backingSet.iterator();
}
@Override
public boolean add(O o) {
return backingSet.add(o);
}
@Override
public boolean remove(O o) {
return backingSet.remove(o);
}
@Override
public boolean isEmpty() {
return backingSet.isEmpty();
}
@Override
public boolean isNotEmpty() {
return !backingSet.isEmpty();
}
@Override
public void clear() {
backingSet.clear();
}
@Override
public int size() {
return backingSet.size();
}
@Override
public int getRetrievalCost() {
return retrievalCost;
}
/**
* Returns the size of the backing set.
* @return the size of the backing set
*/
@Override
public int getMergeCost() {
return backingSet.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
throw new UnsupportedOperationException();
}
@Override
public QueryOptions getQueryOptions() {
throw new UnsupportedOperationException();
}
}
| 3,274 | 23.259259 | 111 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/stored/StoredResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.stored;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* An abstract ResultSet implemented by subclass ResultSets which are stored directly in indexes.
* <p/>
* Extends {@link ResultSet}, adding additional methods to add and remove objects.
* <p/>
* This implementation is abstract.
*
* @author Niall Gallagher
*/
public abstract class StoredResultSet<O> extends ResultSet<O> {
public abstract boolean add(O o);
public abstract boolean remove(O o);
public abstract void clear();
public abstract boolean isEmpty();
public abstract boolean isNotEmpty();
}
| 1,244 | 29.365854 | 97 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/MaterializedDeduplicatedIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* An iterator which wraps another and prevents duplicate objects from being returned.
* <p/>
* The implementation starts returning objects from the wrapped iterator immediately, and records during iteration the
* objects issued so far in a temporary collection. If the wrapped iterator returns the same object more than once,
* this iterator will transparently skip it and move to the next object.
*
* @author niall.gallagher
*/
public class MaterializedDeduplicatedIterator<O> extends UnmodifiableIterator<O> {
final Iterator<O> backingIterator;
final Set<O> materializedSet = new HashSet<O>();
O nextObject = null;
public MaterializedDeduplicatedIterator(Iterator<O> backingIterator) {
this.backingIterator = backingIterator;
}
@Override
public boolean hasNext() {
if (nextObject != null) {
return true;
}
while(backingIterator.hasNext()) {
O next = backingIterator.next();
if (next == null) {
throw new IllegalStateException("Unexpectedly received null from the backing iterator's iterator.next()");
}
if (!materializedSet.add(next)) {
continue;
}
nextObject = next;
return true;
}
nextObject = null;
materializedSet.clear(); // ..help GC
return false;
}
@Override
public O next() {
O next = nextObject;
if (next == null) {
throw new IllegalStateException("Detected an attempt to call iterator.next() without calling iterator.hasNext() immediately beforehand");
}
nextObject = null;
return next;
}
}
| 2,513 | 32.078947 | 149 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/DeduplicatingResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.Iterator;
/**
* A {@link ResultSet} which wraps another, to suppress duplicate objects, where a duplicate object is one which has
* the same value(s) for the given attribute.
* <p/>
* Say an object had an attribute {@code COLOR}. This result set would return only one object of each color from the
* wrapped result set.
* <p/>
* Only one of the potentially duplicate objects will be returned, but which one is unspecified (the query engine is
* usually free for performance reasons to return objects in any order).
*
* @author Niall Gallagher
*/
public class DeduplicatingResultSet<O, A> extends ResultSet<O> {
// TODO is this class unused?
final ResultSet<O> wrappedResultSet;
final Attribute<O, A> uniqueAttribute;
final Query<O> query;
final QueryOptions queryOptions;
public DeduplicatingResultSet(Attribute<O, A> uniqueAttribute, ResultSet<O> wrappedResultSet, Query<O> query, QueryOptions queryOptions) {
this.uniqueAttribute = uniqueAttribute;
this.wrappedResultSet = wrappedResultSet;
this.query = query;
this.queryOptions = queryOptions;
}
@Override
public Iterator<O> iterator() {
return new DeduplicatingIterator<O, A>(uniqueAttribute, queryOptions, wrappedResultSet.iterator());
}
@Override
public final boolean contains(O object) {
// Check if this ResultSet contains the given object by iterating the ResultSet...
return IteratorUtil.iterableContains(this, object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
return IteratorUtil.countElements(this);
}
@Override
public int getRetrievalCost() {
return wrappedResultSet.getRetrievalCost();
}
@Override
public int getMergeCost() {
return wrappedResultSet.getMergeCost();
}
@Override
public void close() {
wrappedResultSet.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 3,119 | 30.2 | 142 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/FilteringResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.Iterator;
/**
* A {@link ResultSet} which wraps an {@link Iterable} and which calls an abstract {@link #isValid(Object, com.googlecode.cqengine.query.option.QueryOptions)} method
* for each object. Returns the object if the implementation of the method returns true, or skips to the
* next object if the method returns false.
*
* @author Niall Gallagher
*/
public abstract class FilteringResultSet<O> extends ResultSet<O> {
final ResultSet<O> wrappedResultSet;
final Query<O> query;
final QueryOptions queryOptions;
public FilteringResultSet(ResultSet<O> wrappedResultSet, Query<O> query, QueryOptions queryOptions) {
this.wrappedResultSet = wrappedResultSet;
this.query = query;
this.queryOptions = queryOptions;
}
@Override
public Iterator<O> iterator() {
return new FilteringIterator<O>(wrappedResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return FilteringResultSet.this.isValid(object, queryOptions);
}
};
}
@Override
public boolean contains(O object) {
// Check if this ResultSet contains the given object by iterating the ResultSet...
return IteratorUtil.iterableContains(this, object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
public abstract boolean isValid(O object, QueryOptions queryOptions);
@Override
public int size() {
return IteratorUtil.countElements(this);
}
@Override
public int getRetrievalCost() {
return wrappedResultSet.getRetrievalCost();
}
@Override
public int getMergeCost() {
return wrappedResultSet.getMergeCost();
}
@Override
public void close() {
wrappedResultSet.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 2,957 | 29.494845 | 165 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/DeduplicatingIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* An iterator which wraps another, to suppress duplicate objects, where a duplicate object is one which has
* the same value(s) for the given attribute.
* <p/>
* Say an object had an attribute {@code COLOR}. This iterator would return only one object of each color from the
* wrapped iterator.
* <p/>
* Only one of the potentially duplicate objects will be returned, but which one is unspecified (the query engine is
* usually free for performance reasons to return objects in any order).
*
* @author Niall Gallagher
*/
public class DeduplicatingIterator<O, A> extends FilteringIterator<O> {
private final Attribute<O, A> uniqueAttribute;
private final Set<A> attributeValuesProcessed = new HashSet<A>();
public DeduplicatingIterator(Attribute<O, A> uniqueAttribute, QueryOptions queryOptions, Iterator<O> wrappedIterator) {
super(wrappedIterator, queryOptions);
this.uniqueAttribute = uniqueAttribute;
}
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
boolean modified = false;
for (A value : uniqueAttribute.getValues(object, queryOptions)) {
modified = attributeValuesProcessed.add(value) || modified;
}
return modified;
}
}
| 2,101 | 35.877193 | 123 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/FilteringIterator.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An Iterator which wraps another iterator, and for each object returned by the wrapped iterator, calls an
* {@link #isValid(Object, com.googlecode.cqengine.query.option.QueryOptions)} method. If this method returns true, this iterator returns the object, if it returns false
* it skips the object and moves to the next object.
*
* @author ngallagher
* @since 2012-05-03 17:38
*/
public abstract class FilteringIterator<O> extends UnmodifiableIterator<O> {
final Iterator<O> wrappedIterator;
final QueryOptions queryOptions;
public FilteringIterator(Iterator<O> wrappedIterator, QueryOptions queryOptions) {
this.wrappedIterator = wrappedIterator;
this.queryOptions = queryOptions;
}
private O nextObject = null;
private boolean nextObjectIsNull = false;
private boolean finished = false;
@Override
public boolean hasNext() {
if (finished) {
return false;
}
if (nextObjectIsNull || nextObject != null) {
return true;
}
while (wrappedIterator.hasNext()) {
nextObject = wrappedIterator.next();
if (isValid(nextObject, queryOptions)) {
nextObjectIsNull = (nextObject == null);
return true;
} // else object not valid, skip to next object
nextObjectIsNull = false;
}
finished = true;
return false;
}
@Override
public O next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
O objectToReturn = nextObject;
nextObject = null;
nextObjectIsNull = false;
return objectToReturn;
}
public abstract boolean isValid(O object, QueryOptions queryOptions);
}
| 2,625 | 31.825 | 169 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/filter/QuantizedResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* An implementation of {@link FilteringResultSet} which filters objects based on whether they match a given query.
* <p/>
* This can be useful to index which use a {@link com.googlecode.cqengine.quantizer.Quantizer}.
*
* @author Niall Gallagher
*/
public class QuantizedResultSet<O> extends FilteringResultSet<O> {
final Query<O> query;
public QuantizedResultSet(ResultSet<O> wrappedResultSet, Query<O> query, QueryOptions queryOptions) {
super(wrappedResultSet, query, queryOptions);
this.query = query;
}
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return query.matches(object, queryOptions);
}
@Override
public Query<O> getQuery() {
return query;
}
}
| 1,574 | 31.8125 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/connective/ResultSetIntersection.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.connective;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.QueryCostComparators;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
/**
* A ResultSet which provides a view onto the intersection of other ResultSets.
*
* @author Niall Gallagher
*/
public class ResultSetIntersection<O> extends ResultSet<O> {
final Query<O> query;
// ResultSets sorted in ascending order of merge cost...
final List<ResultSet<O>> resultSets;
final QueryOptions queryOptions;
final boolean useIndexMergeStrategy;
public ResultSetIntersection(Iterable<ResultSet<O>> resultSets, Query<O> query, QueryOptions queryOptions, boolean useIndexMergeStrategy) {
this.query = query;
this.queryOptions = queryOptions;
// Sort the supplied result sets in ascending order of merge cost...
List<ResultSet<O>> sortedResultSets = ResultSets.wrapWithCostCachingIfNecessary(resultSets);
Collections.sort(sortedResultSets, QueryCostComparators.getMergeCostComparator());
this.resultSets = sortedResultSets;
this.useIndexMergeStrategy = useIndexMergeStrategy;
}
@Override
public Iterator<O> iterator() {
if (resultSets.isEmpty()) {
return Collections.<O>emptySet().iterator();
}
else if (resultSets.size() == 1) {
return resultSets.get(0).iterator();
}
ResultSet<O> lowestMergeCostResultSet = resultSets.get(0);
final List<ResultSet<O>> moreExpensiveResultSets = resultSets.subList(1, resultSets.size());
if (useIndexMergeStrategy) {
return new FilteringIterator<O>(lowestMergeCostResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
for (ResultSet<O> resultSet : moreExpensiveResultSets) {
if (!resultSet.contains(object)) {
return false;
}
}
return true;
}
};
}
else {
return new FilteringIterator<O>(lowestMergeCostResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
for (ResultSet<O> resultSet : moreExpensiveResultSets) {
if (!resultSet.matches(object)) {
return false;
}
}
return true;
}
};
}
}
/**
* Returns true if the given object is contained in <b><u>all</u></b> underlying ResultSets.
* @param object An object to check if contained
* @return true if the given object is contained in <b><u>all</u></b> underlying ResultSets, false if it is not
* contained in one or more ResultSets or if there are no underlying result sets
*/
@Override
public boolean contains(O object) {
if (this.resultSets.isEmpty()) {
return false;
}
for (ResultSet<O> resultSet : this.resultSets) {
if (!resultSet.contains(object)) {
return false;
}
}
return true;
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* Returns the retrieval cost from the underlying {@code ResultSet} which has the lowest merge cost.
* @return the retrieval cost from the underlying {@code ResultSet} which has the lowest merge cost
*/
@Override
public int getRetrievalCost() {
if (resultSets.isEmpty()) {
return 0;
}
else {
ResultSet<O> lowestMergeCostResultSet = resultSets.get(0);
return lowestMergeCostResultSet.getRetrievalCost();
}
}
/**
* Returns the merge cost from the underlying {@code ResultSet} with the lowest merge cost.
* @return the merge cost from the underlying {@code ResultSet} with the lowest merge cost
*/
@Override
public int getMergeCost() {
if (resultSets.isEmpty()) {
return 0;
}
else {
ResultSet<O> lowestMergeCostResultSet = resultSets.get(0);
return lowestMergeCostResultSet.getMergeCost();
}
}
/**
* Closes all of the underlying {@code ResultSet}s.
*/
@Override
public void close() {
for (ResultSet<O> resultSet : this.resultSets) {
resultSet.close();
}
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 5,836 | 33.744048 | 143 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/connective/ResultSetUnion.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.connective;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.iterator.ConcatenatingIterator;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A ResultSet which provides a view onto the union of other ResultSets, with deduplication.
* <p/>
* This is equivalent to UNION in SQL terminology, i.e. duplicates are eliminated.
*
* @author Niall Gallagher
*/
public class ResultSetUnion<O> extends ResultSet<O> {
final Query<O> query;
// ResultSets (not in any particular order)...
final Iterable<?extends ResultSet<O>> resultSets;
final QueryOptions queryOptions;
final boolean useIndexMergeStrategy;
public ResultSetUnion(Iterable<? extends ResultSet<O>> resultSets, Query<O> query, QueryOptions queryOptions) {
this(resultSets, query, queryOptions, false);
}
public ResultSetUnion(Iterable<? extends ResultSet<O>> resultSets, Query<O> query, QueryOptions queryOptions, boolean useIndexMergeStrategy) {
List<ResultSet<O>> costCachingResultSets = ResultSets.wrapWithCostCachingIfNecessary(resultSets);
this.resultSets = costCachingResultSets;
this.query = query;
this.queryOptions = queryOptions;
this.useIndexMergeStrategy = useIndexMergeStrategy;
}
@Override
public Iterator<O> iterator() {
// Maintain a list of ResultSets which have already been iterated, excluding the one currently being iterated...
final List<ResultSet<O>> resultSetsAlreadyIterated = new ArrayList<ResultSet<O>>();
// An iterator which concatenates all ResultSets together, effectively implementing UNION ALL.
// When moving on to the next ResultSet, this iterator adds the ResultSet it has just iterated
// to the list of resultSetsAlreadyIterated above...
Iterator<O> unionAllIterator = new ConcatenatingIterator<O>() {
private Iterator<? extends ResultSet<O>> resultSetsIterator = resultSets.iterator();
private ResultSet<O> currentResultSet = null;
@Override
public Iterator<O> getNextIterator() {
if (currentResultSet != null ) {
resultSetsAlreadyIterated.add(currentResultSet);
}
if (resultSetsIterator.hasNext()) {
currentResultSet = resultSetsIterator.next();
return currentResultSet.iterator();
}
else {
currentResultSet = null;
return null;
}
}
};
// An iterator which wraps the UNION ALL iterator, filtering out objects which are contained in ResultSets
// iterated earlier - so effectively implementing UNION (with duplicates eliminated)...
if (useIndexMergeStrategy) {
return new FilteringIterator<O>(unionAllIterator, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
for (ResultSet<O> resultSet : resultSetsAlreadyIterated) {
if (resultSet.contains(object)) {
return false;
}
}
return true;
}
};
}
else {
return new FilteringIterator<O>(unionAllIterator, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
for (ResultSet<O> resultSet : resultSetsAlreadyIterated) {
if (resultSet.matches(object)) {
return false;
}
}
return true;
}
};
}
}
/**
* Returns true if the given object is contained in <b><u>any</u></b> underlying ResultSets.
* @param object An object to check if contained
* @return true if the given object is contained in <b><u>any</u></b> underlying ResultSets, false if it is not
* contained in any ResultSets or if there are no underlying result sets
*/
@Override
public boolean contains(O object) {
for (ResultSet<O> resultSet : this.resultSets) {
if (resultSet.contains(object)) {
return true;
}
}
return false;
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
/**
* Returns the number of distinct objects in the the underlying {@code ResultSet}s, with duplicates eliminated.
* @return the number of distinct objects in the the underlying {@code ResultSet}s, with duplicates eliminated
*/
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* Returns the sum of the retrieval costs of the the underlying {@code ResultSet}s.
* @return the sum of the retrieval costs of the the underlying {@code ResultSet}s
*/
@Override
public int getRetrievalCost() {
long retrievalCost = 0;
for (ResultSet<O> resultSet : this.resultSets) {
retrievalCost = retrievalCost + resultSet.getRetrievalCost();
}
return (int)Math.min(retrievalCost, Integer.MAX_VALUE);
}
/**
* Returns the sum of the merge costs of the the underlying {@code ResultSet}s.
* @return the sum of the merge costs of the the underlying {@code ResultSet}s
*/
@Override
public int getMergeCost() {
long mergeCost = 0;
for (ResultSet<O> resultSet : this.resultSets) {
mergeCost = mergeCost + resultSet.getMergeCost();
}
return (int)Math.min(mergeCost, Integer.MAX_VALUE);
}
/**
* Closes all of the underlying {@code ResultSet}s.
*/
@Override
public void close() {
for (ResultSet<O> resultSet : this.resultSets) {
resultSet.close();
}
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 7,180 | 36.794737 | 146 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/connective/ResultSetUnionAll.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.connective;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.iterator.ConcatenatingIterator;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.*;
/**
* A ResultSet which provides a view onto the union of other ResultSets, <b>without</b> deduplication.
* <p/>
* This is equivalent to UNION ALL in SQL terminology, i.e. duplicates are <b>not</b> eliminated.
*
* @author Niall Gallagher
*/
public class ResultSetUnionAll<O> extends ResultSet<O> {
final Query<O> query;
final QueryOptions queryOptions;
// ResultSets (not in any particular order)...
private final Iterable<? extends ResultSet<O>> resultSets;
public ResultSetUnionAll(Iterable<? extends ResultSet<O>> resultSets, Query<O> query, QueryOptions queryOptions) {
this.resultSets = ResultSets.wrapWithCostCachingIfNecessary(resultSets);
this.query = query;
this.queryOptions = queryOptions;
}
@Override
public Iterator<O> iterator() {
return new ConcatenatingIterator<O>() {
Iterator<? extends ResultSet<O>> resultSetsIterator = resultSets.iterator();
@Override
public Iterator<O> getNextIterator() {
return resultSetsIterator.hasNext() ? resultSetsIterator.next().iterator() : null;
}
};
}
/**
* Returns true if the given object is contained in <b><u>any</u></b> underlying ResultSets.
* @param object An object to check if contained
* @return true if the given object is contained in <b><u>any</u></b> underlying ResultSets, false if it is not
* contained in any ResultSets or if there are no underlying result sets
*/
@Override
public boolean contains(O object) {
for (ResultSet<O> resultSet : this.resultSets) {
if (resultSet.contains(object)) {
return true;
}
}
return false;
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
/**
* Returns the sum of the sizes of the the underlying {@code ResultSet}s.
* @return the sum of the sizes of the the underlying {@code ResultSet}s
*/
@Override
public int size() {
int size = 0;
for (ResultSet<O> resultSet : this.resultSets) {
size = size + resultSet.size();
}
return size;
}
/**
* Returns the sum of the retrieval costs of the the underlying {@code ResultSet}s.
* @return the sum of the retrieval costs of the the underlying {@code ResultSet}s
*/
@Override
public int getRetrievalCost() {
long retrievalCost = 0;
for (ResultSet<O> resultSet : this.resultSets) {
retrievalCost = retrievalCost + resultSet.getRetrievalCost();
}
return (int)Math.min(retrievalCost, Integer.MAX_VALUE);
}
/**
* Returns the sum of the merge costs of the the underlying {@code ResultSet}s.
* @return the sum of the merge costs of the the underlying {@code ResultSet}s
*/
@Override
public int getMergeCost() {
long mergeCost = 0;
for (ResultSet<O> resultSet : this.resultSets) {
mergeCost = mergeCost + resultSet.getMergeCost();
}
return (int)Math.min(mergeCost, Integer.MAX_VALUE);
}
/**
* Closes all of the underlying {@code ResultSet}s.
*/
@Override
public void close() {
for (ResultSet<O> resultSet : this.resultSets) {
resultSet.close();
}
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 4,525 | 32.036496 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/connective/ResultSetDifference.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.connective;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
/**
* A ResultSet which provides a view onto the set difference of two ResultSets.
* <p/>
* The set difference is elements contained in the first ResultSet which are NOT contained in the second ResultSet.
*
* @author Niall Gallagher
*/
public class ResultSetDifference<O> extends ResultSet<O> {
final ResultSet<O> firstResultSet;
final ResultSet<O> secondResultSet;
final Query<O> query;
final QueryOptions queryOptions;
final boolean indexMergeStrategyEnabled;
public ResultSetDifference(ResultSet<O> firstResultSet, ResultSet<O> secondResultSet, Query<O> query, QueryOptions queryOptions) {
this(firstResultSet, secondResultSet, query, queryOptions, false);
}
public ResultSetDifference(ResultSet<O> firstResultSet, ResultSet<O> secondResultSet, Query<O> query, QueryOptions queryOptions, boolean indexMergeStrategyEnabled) {
this.firstResultSet = ResultSets.wrapWithCostCachingIfNecessary(firstResultSet);
this.secondResultSet = ResultSets.wrapWithCostCachingIfNecessary(secondResultSet);
this.query = query;
this.queryOptions = queryOptions;
// If index merge strategy is enabled, validate that we can actually use it for this particular negation...
if (indexMergeStrategyEnabled) {
if (this.secondResultSet.getRetrievalCost() == Integer.MAX_VALUE) { //note getRetrievalCost() is on the cost-caching wrapper
// We cannot use index merge strategy for this negation
// because the second ResultSet is not backed by an index...
indexMergeStrategyEnabled = false;
}
}
this.indexMergeStrategyEnabled = indexMergeStrategyEnabled;
}
@Override
public Iterator<O> iterator() {
if (indexMergeStrategyEnabled) {
return new FilteringIterator<O>(firstResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return !secondResultSet.contains(object);
}
};
}
else {
return new FilteringIterator<O>(firstResultSet.iterator(), queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return !secondResultSet.matches(object);
}
};
}
}
/**
* Returns true if the given object is contained in the first ResultSet,
* but is NOT contained in the second ResultSet.
*
* @param object An object to check if contained
* @return true if the given object is contained in the first ResultSet,
* but is NOT contained in the second ResultSet, otherwise false
*/
@Override
public boolean contains(O object) {
return firstResultSet.contains(object) && !secondResultSet.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
return IteratorUtil.countElements(this);
}
/**
* Returns the retrieval cost from the first ResultSet.
* @return the retrieval cost from the first ResultSet
*/
@Override
public int getRetrievalCost() {
return firstResultSet.getRetrievalCost();
}
/**
* Returns the merge cost from the first ResultSet.
* @return the merge cost from the first ResultSet
*/
@Override
public int getMergeCost() {
return firstResultSet.getMergeCost();
}
@Override
public void close() {
firstResultSet.close();
secondResultSet.close();
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 4,909 | 34.323741 | 169 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/closeable/CloseableFilteringResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.closeable;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.FilteringResultSet;
import java.io.Closeable;
import java.util.Iterator;
/**
* A FilteringResultSet which throws exceptions if an attempt to use it is made after its {@link #close} method has
* been called.
*/
public abstract class CloseableFilteringResultSet<O> extends FilteringResultSet<O> implements Closeable {
boolean closed = false;
public CloseableFilteringResultSet(ResultSet<O> wrappedResultSet, Query<O> query, QueryOptions queryOptions) {
super(wrappedResultSet, query, queryOptions);
}
@Override
public Iterator<O> iterator() {
ensureNotClosed();
return super.iterator();
}
@Override
public int size() {
ensureNotClosed();
return super.size();
}
@Override
public int getRetrievalCost() {
ensureNotClosed();
return super.getRetrievalCost();
}
@Override
public int getMergeCost() {
ensureNotClosed();
return super.getMergeCost();
}
@Override
public O uniqueResult() {
ensureNotClosed();
return super.uniqueResult();
}
@Override
public boolean isEmpty() {
ensureNotClosed();
return super.isEmpty();
}
@Override
public boolean isNotEmpty() {
ensureNotClosed();
return super.isNotEmpty();
}
void ensureNotClosed() {
if (closed) {
throw new IllegalStateException("ResultSet is closed");
}
}
@Override
public void close() {
super.close();
closed = true;
}
}
| 2,420 | 25.315217 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/resultset/closeable/CloseableResultSet.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.closeable;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.io.Closeable;
import java.util.Iterator;
/**
* A ResultSet which throws exceptions if an attempt to use it is made after its {@link #close} method has been called.
*/
public class CloseableResultSet<O> extends ResultSet<O> implements Closeable {
final ResultSet<O> wrapped;
final Query<O> query;
final QueryOptions queryOptions;
boolean closed = false;
public CloseableResultSet(ResultSet<O> wrapped, Query<O> query, QueryOptions queryOptions) {
this.wrapped = wrapped;
this.query = query;
this.queryOptions = queryOptions;
}
@Override
public Iterator<O> iterator() {
ensureNotClosed();
return wrapped.iterator();
}
@Override
public boolean contains(O object) {
ensureNotClosed();
return wrapped.contains(object);
}
@Override
public boolean matches(O object) {
ensureNotClosed();
return query.matches(object, queryOptions);
}
@Override
public int size() {
ensureNotClosed();
return wrapped.size();
}
@Override
public int getRetrievalCost() {
ensureNotClosed();
return wrapped.getRetrievalCost();
}
@Override
public int getMergeCost() {
ensureNotClosed();
return wrapped.getMergeCost();
}
@Override
public O uniqueResult() {
ensureNotClosed();
return wrapped.uniqueResult();
}
@Override
public boolean isEmpty() {
ensureNotClosed();
return wrapped.isEmpty();
}
@Override
public boolean isNotEmpty() {
ensureNotClosed();
return wrapped.isNotEmpty();
}
void ensureNotClosed() {
if (closed) {
throw new IllegalStateException("ResultSet is closed");
}
}
@Override
public void close() {
wrapped.close();
closed = true;
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 2,892 | 23.726496 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/OrderMissingLastAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Has;
/**
* An {@link OrderControlAttribute} which orders results such that objects without values for the given delegate
* attribute are always returned <i>after</i> objects with values for the attribute.
*
* @author niall.gallagher
*/
public class OrderMissingLastAttribute<O> extends OrderControlAttribute<O> {
final Has<O, ? extends Comparable> hasQuery;
public <A extends Comparable<A>> OrderMissingLastAttribute(Attribute<O, A> delegateAttribute) {
super(delegateAttribute, "missingLast_" + delegateAttribute.getAttributeName());
this.hasQuery = QueryFactory.has(delegateAttribute);
}
@Override
public Integer getValue(O object, QueryOptions queryOptions) {
return hasQuery.matches(object, queryOptions) ? 0 : 1;
}
@Override
public boolean canEqual(Object other) {
return other instanceof OrderMissingLastAttribute;
}
}
| 1,704 | 35.276596 | 112 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/MultiValueAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.attribute.support.AbstractAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* Represents an attribute in an object which has multiple values (such as a field which is itself a collection),
* where all of the values are known to be non-null.
* <p/>
* Provides a method to read the values from the field given such an object.
* <p/>
* This type of attribute skips null checks on values at runtime, thereby allowing maximum performance.
* If this type of attribute encounters a null, it is likely that a {@code NullPointerException} will be thrown.
* Therefore when it is not possible to know in advance if values might be null, it is recommended to use
* {@link MultiValueNullableAttribute} instead.
*
* @author Niall Gallagher
*/
public abstract class MultiValueAttribute<O, A> extends AbstractAttribute<O, A> {
/**
* Creates an attribute with the given name.
*
* This name is not actually used by the query engine except in providing informative exception and debug messages.
* As such it is recommended, but not required, that a name be provided.
* <p/>
* A suitable name might be the name of the field to which an attribute refers.
*
* @param attributeName The name for this attribute
* @see #MultiValueAttribute()
*/
public MultiValueAttribute(String attributeName) {
super(attributeName);
}
/**
* Creates an attribute with no name. A name for the attribute will be generated automatically from the name of the
* subclass (or anonymous class) which implements the attribute.
*
* @see #MultiValueAttribute(String)
*/
public MultiValueAttribute() {
}
/**
* Creates an attribute with no name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
*/
public MultiValueAttribute(Class<O> objectType, Class<A> attributeType) {
super(objectType, attributeType);
}
/**
* Creates an attribute with the given name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
* @param attributeName The name for this attribute
*/
public MultiValueAttribute(Class<O> objectType, Class<A> attributeType, String attributeName) {
super(objectType, attributeType, attributeName);
}
/**
* Returns the non-null values of the attribute from the object.
* <p/>
* @param object The object from which the values of the attribute are required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The values for the attribute, which should never be null
*/
@Override
public abstract Iterable<A> getValues(O object, QueryOptions queryOptions);
}
| 3,834 | 39.797872 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/OrderControlAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.AttributeOrder;
import com.googlecode.cqengine.query.simple.Has;
/**
* An attribute which wraps another delegate attribute, and can be used in a {@link QueryFactory#orderBy(AttributeOrder)}
* clause to control the placement in results of objects which have and do not have values for the delegate attribute.
* <p/>
* Essentially this attribute allows results to be sorted based on whether a {@link Has} query on the delegate attribute
* returns true or false.
* <p/>
* The default behaviour of CQEngine is as follows:
* <ul>
* <li>
* When the sort order requested for a given query is {@link QueryFactory#ascending(Attribute)}, objects without
* values for the attribute will be returned first, followed by objects which have values for the attribute,
* sorted ascending by their values.
* </li>
* <li>
* When the sort order requested is {@link QueryFactory#descending(Attribute)}, objects with
* values for the attribute will be returned first sorted descending by their values, followed by objects
* without values for the attribute.
* </li>
* </ul>
* The subclass implementations of this class alter that default behaviour, allowing objects without values for the
* attribute to <i>always</i> be returned before or after objects with values.
*
* @author niall.gallagher
*/
public abstract class OrderControlAttribute<O> extends SimpleAttribute<O, Integer> {
protected final Attribute<O, ? extends Comparable> delegateAttribute;
protected OrderControlAttribute(Attribute<O, ? extends Comparable> delegateAttribute, String delegateAttributeName) {
super(delegateAttribute.getObjectType(), Integer.class, delegateAttributeName);
if (delegateAttribute instanceof OrderControlAttribute) {
throw new IllegalArgumentException("Delegate attribute cannot also be an OrderControlAttribute: " + delegateAttribute);
}
this.delegateAttribute = delegateAttribute;
}
public Attribute<O, ?> getDelegateAttribute() {
return delegateAttribute;
}
}
| 2,840 | 44.095238 | 131 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/SimpleAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.attribute.support.AbstractAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
/**
* Represents an attribute in an object (such as a field) which will not be null.
*
* Provides a method to read the value of the field given such an object.
*
* @see SimpleNullableAttribute
* @author Niall Gallagher
*/
public abstract class SimpleAttribute<O, A> extends AbstractAttribute<O, A> {
/**
* Creates an attribute with no name. A name for the attribute will be generated automatically from the name of the
* subclass (or anonymous class) which implements the attribute.
*
* @see #SimpleAttribute(String)
*/
public SimpleAttribute() {
super();
}
/**
* Creates an attribute with the given name.
*
* This name is not actually used by the query engine except in providing informative exception and debug messages.
* As such it is recommended, but not required, that a name be provided.
* <p/>
* A suitable name might be the name of the field to which an attribute refers.
*
* @param attributeName The name for this attribute
* @see #SimpleAttribute()
*/
public SimpleAttribute(String attributeName) {
super(attributeName);
}
/**
* Creates an attribute with no name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
*/
public SimpleAttribute(Class<O> objectType, Class<A> attributeType) {
super(objectType, attributeType);
}
/**
* Creates an attribute with the given name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
* @param attributeName The name for this attribute
*/
public SimpleAttribute(Class<O> objectType, Class<A> attributeType, String attributeName) {
super(objectType, attributeType, attributeName);
}
/**
* {@inheritDoc}
*/
@Override
public Iterable<A> getValues(O object, QueryOptions queryOptions) {
return Collections.singletonList(getValue(object, queryOptions));
}
/**
* Returns the (non-null) value of the attribute from the object.
* <p/>
* @param object The object from which the value of the attribute is required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The value for the attribute, which should never be null
*/
public abstract A getValue(O object, QueryOptions queryOptions);
@Override
public boolean canEqual(Object other) {
return other instanceof SimpleAttribute;
}
}
| 3,697 | 33.886792 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/ReflectiveAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.lang.reflect.Field;
/**
* A type of {@link SimpleAttribute} which is implemented using reflection.
* <p/>
* This type of attribute will not perform as well as an attribute defined in code,
* but this type can sometimes be convenient.
*
* @author Niall Gallagher
*/
public class ReflectiveAttribute<O, A> extends SimpleAttribute<O, A> {
final Field field;
/**
* Creates an attribute which reads values from the field indicated using reflection.
*
* @param objectType The type of the object containing the field
* @param fieldType The type of the field in the object
* @param fieldName The name of the field
*/
public ReflectiveAttribute(Class<O> objectType, Class<A> fieldType, String fieldName) {
super(objectType, fieldType, fieldName);
Field field;
try {
field = getField(objectType, fieldName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
}
catch (Exception e) {
throw new IllegalStateException("Invalid attribute definition: No such field '" + fieldName + "' in object '" + objectType.getName() + "'");
}
if (!fieldType.isAssignableFrom(field.getType())) {
throw new IllegalStateException("Invalid attribute definition: The type of field '" + fieldName + "', type '" + field.getType() + "', in object '" + objectType.getName() + "', is not assignable to the type indicated: " + fieldType.getName());
}
this.field = field;
}
/**
* Searches the given class and its superclasses for the given field. Supports private and non-private fields.
* @param cls The class to search
* @param fieldName The name of the field
* @return The field with the given name
* @throws NoSuchFieldException If no such field can be found
*/
static Field getField(Class<?> cls, String fieldName) throws NoSuchFieldException {
while (cls != null && cls != Object.class) {
try {
return cls.getDeclaredField(fieldName);
}
catch (NoSuchFieldException e) {
cls = cls.getSuperclass();
}
}
throw new NoSuchFieldException("No such field: " + fieldName);
}
@Override
public A getValue(O object, QueryOptions queryOptions) {
try {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
A value = (A) field.get(object);
return value;
}
catch (Exception e) {
throw new IllegalStateException("Failed to read value from field '" + field.getName() + "'", e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReflectiveAttribute)) return false;
if (!super.equals(o)) return false;
ReflectiveAttribute that = (ReflectiveAttribute) o;
if (!that.canEqual(this)) return false;
if (!field.equals(that.field)) return false;
return true;
}
@Override
public boolean canEqual(Object other) {
return (other instanceof ReflectiveAttribute);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + field.hashCode();
return result;
}
/**
* Returns an attribute which reads values from the field indicated using reflection.
*
* @param objectType The type of the object containing the field
* @param fieldType The type of the field in the object
* @param fieldName The name of the field
* @return An attribute which reads values from the field indicated using reflection
*/
public static <O, A> ReflectiveAttribute<O, A> forField(Class<O> objectType, Class<A> fieldType, String fieldName) {
return new ReflectiveAttribute<O, A>(objectType, fieldType, fieldName);
}
}
| 4,663 | 35.4375 | 254 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/SimpleNullableAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.attribute.support.AbstractAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
/**
* Represents an attribute in an object (such as a field) which can be null.
*
* Provides a method to read the value of the field given such an object.
*
* @see SimpleAttribute
* @author Niall Gallagher
*/
public abstract class SimpleNullableAttribute<O, A> extends AbstractAttribute<O, A> {
/**
* Creates an attribute with the given name.
*
* This name is not actually used by the query engine except in providing informative exception and debug messages.
* As such it is recommended, but not required, that a name be provided.
* <p/>
* A suitable name might be the name of the field to which an attribute refers.
*
* @param attributeName The name for this attribute
* @see #SimpleNullableAttribute()
*/
public SimpleNullableAttribute(String attributeName) {
super(attributeName);
}
/**
* Creates an attribute with no name. A name for the attribute will be generated automatically from the name of the
* subclass (or anonymous class) which implements the attribute.
*
* @see #SimpleNullableAttribute(String)
*/
public SimpleNullableAttribute() {
super();
}
/**
* Creates an attribute with no name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
*/
public SimpleNullableAttribute(Class<O> objectType, Class<A> attributeType) {
super(objectType, attributeType);
}
/**
* Creates an attribute with the given name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
* @param attributeName The name for this attribute
*/
public SimpleNullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName) {
super(objectType, attributeType, attributeName);
}
/**
* {@inheritDoc}
*/
@Override
public Iterable<A> getValues(O object, QueryOptions queryOptions) {
A value = getValue(object, queryOptions);
return value == null ? Collections.<A>emptyList() : Collections.singletonList(value);
}
/**
* Returns the (possibly null) value of the attribute from the object.
* <p/>
* @param object The object from which the value of the attribute is required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The value for the attribute, which can be null
*/
public abstract A getValue(O object, QueryOptions queryOptions);
}
| 3,690 | 35.91 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/SimpleNullableMapAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Map;
/**
* An attribute which reads the value from an entry in a map given the map key. This can be used when Map objects
* are stored in the IndexedCollection.
* <p/>
* These attributes can be created via {@link QueryFactory#mapAttribute(Object, Class)}.
* <p/>
* Also see {@link QueryFactory#mapEntity(Map)} as a way to improve the performance when working with collections
* of Maps.
*
* Created by npgall on 23/05/2016.
*/
public class SimpleNullableMapAttribute<K, A> extends SimpleNullableAttribute<Map, A> {
final K mapKey;
public SimpleNullableMapAttribute(K mapKey, Class<A> mapValueType) {
super(Map.class, mapValueType, mapKey.toString());
this.mapKey = mapKey;
}
public SimpleNullableMapAttribute(K mapKey, Class<A> mapValueType, String attributeName) {
super(Map.class, mapValueType, attributeName);
this.mapKey = mapKey;
}
@Override
public A getValue(Map map, QueryOptions queryOptions) {
Object result = map.get(mapKey);
if (result == null || getAttributeType().isAssignableFrom(result.getClass())) {
return getAttributeType().cast(result);
}
throw new ClassCastException("Cannot cast " + result.getClass().getName() + " to " + getAttributeType().getName() + " for map key: " + mapKey);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + mapKey.hashCode();
return result;
}
@Override
public boolean canEqual(Object other) {
return other instanceof SimpleNullableMapAttribute;
}
@Override
public boolean equals(Object other) {
return super.equals(other) && this.mapKey.equals(((SimpleNullableMapAttribute)other).mapKey);
}
}
| 2,555 | 33.540541 | 151 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/MultiValueNullableAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.attribute.support.AbstractAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.Collections;
import java.util.Iterator;
/**
* Represents an attribute in an object which has multiple values (such as a field which is itself a collection),
* where some of the values might be null, or where the collection of values itself might be null.
* <p/>
* Provides a method to read the values from the field given such an object.
* <p/>
* This type of attribute performs runtime validation of values to handle nulls, which can impact performance.
* When it is known that values will not be null, it is recommended to use {@link MultiValueAttribute} instead.
*
* @author Niall Gallagher
*/
public abstract class MultiValueNullableAttribute<O, A> extends AbstractAttribute<O, A> {
final boolean componentValuesNullable;
/**
* Creates an attribute with the given name.
*
* This name is not actually used by the query engine except in providing informative exception and debug messages.
* As such it is recommended, but not required, that a name be provided.
* <p/>
* A suitable name might be the name of the field to which an attribute refers.
*
* @param attributeName The name for this attribute
* @param componentValuesNullable Supply true if some of the multiple values in the list returned might be null,
* supply false if only the collection returned itself might be null
*
* @see #MultiValueNullableAttribute(boolean)
*/
public MultiValueNullableAttribute(String attributeName, boolean componentValuesNullable) {
super(attributeName);
this.componentValuesNullable = componentValuesNullable;
}
/**
* Creates an attribute with no name. A name for the attribute will be generated automatically from the name of the
* subclass (or anonymous class) which implements the attribute.
*
* @param componentValuesNullable Supply true if some of the multiple values in the list returned might be null,
* supply false if only the collection returned itself might be null
*
* @see #MultiValueNullableAttribute(String, boolean)
*/
public MultiValueNullableAttribute(boolean componentValuesNullable) {
this.componentValuesNullable = componentValuesNullable;
}
/**
* Creates an attribute with no name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
* @param componentValuesNullable Supply true if some of the multiple values in the list returned might be null,
* supply false if only the collection returned itself might be null
*/
public MultiValueNullableAttribute(Class<O> objectType, Class<A> attributeType, boolean componentValuesNullable) {
super(objectType, attributeType);
this.componentValuesNullable = componentValuesNullable;
}
/**
* Creates an attribute with the given name, and manually specifies the type of the attribute and its enclosing
* object.
*
* @param objectType The type of the object containing this attribute
* @param attributeType The type of this attribute
* @param attributeName The name for this attribute
* @param componentValuesNullable Supply true if some of the multiple values in the list returned might be null,
* supply false if only the collection returned itself might be null
*/
public MultiValueNullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, boolean componentValuesNullable) {
super(objectType, attributeType, attributeName);
this.componentValuesNullable = componentValuesNullable;
}
/**
* Returns the values of the attribute from the object, omitting any null values.
* <p/>
* @param object The object from which the values of the attribute are required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The values for the attribute
*/
@Override
public Iterable<A> getValues(O object, QueryOptions queryOptions) {
Iterable<A> values = getNullableValues(object, queryOptions);
// Handle the collection of values itself being null...
values = (values == null ? Collections.<A>emptyList() : values);
// Check if we need to check for nulls in the collection of values...
if (!componentValuesNullable) {
// No need to check for nulls in the collection of values...
return values;
}
// Check for and skip any nulls in the collection of values...
final Iterable<A> finalValues = values;
return new Iterable<A>() {
@Override
public Iterator<A> iterator() {
return IteratorUtil.removeNulls(finalValues.iterator());
}
};
}
/**
* Returns the values of the attribute from the object, some of which can be null.
* The actual list returned can also be null.
* <p/>
* @param object The object from which the values of the attribute are required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The values for the attribute, some of which might be null
*/
public abstract Iterable<A> getNullableValues(O object, QueryOptions queryOptions);
}
| 6,483 | 45.314286 | 140 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/SelfAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* An attribute which returns the object itself.
* <p/>
* This can be useful when performing queries on objects in the collection itself (rather than on fields in the
* objects in the collection). Typical use case would be for performing <code>startsWith</code> queries on an
* <code>IndexedCollection<String></code>.
*
* @author Niall Gallagher
*/
public class SelfAttribute<O> extends SimpleAttribute<O, O> {
public SelfAttribute(Class<O> objectType, String attributeName) {
super(objectType, objectType, attributeName);
}
public SelfAttribute(Class<O> objectType) {
super(objectType, objectType, "self");
}
@Override
public O getValue(O object, QueryOptions queryOptions) {
return object;
}
/**
* @deprecated Use the equivalent {@link com.googlecode.cqengine.query.QueryFactory#selfAttribute(Class)} method
* instead. This method will be removed in a future version of CQEngine.
*/
@Deprecated
public static <O> SelfAttribute<O> self(Class<O> type) {
return new SelfAttribute<O>(type);
}
}
| 1,812 | 33.207547 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/OrderMissingFirstAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Has;
/**
* An {@link OrderControlAttribute} which orders results such that objects without values for the given delegate
* attribute are always returned <i>before</i> objects with values for the attribute.
*
* @author niall.gallagher
*/
public class OrderMissingFirstAttribute<O> extends OrderControlAttribute<O> {
final Has<O, ? extends Comparable> hasQuery;
public <A extends Comparable<A>> OrderMissingFirstAttribute(Attribute<O, A> delegateAttribute) {
super(delegateAttribute, "missingFirst_" + delegateAttribute.getAttributeName());
this.hasQuery = QueryFactory.has(delegateAttribute);
}
@Override
public Integer getValue(O object, QueryOptions queryOptions) {
return hasQuery.matches(object, queryOptions) ? 1 : 0;
}
@Override
public boolean canEqual(Object other) {
return other instanceof OrderMissingFirstAttribute;
}
}
| 1,709 | 35.382979 | 112 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/Attribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* @author Niall Gallagher
*/
public interface Attribute<O, A> {
/**
* Returns the type of the object which contains the attribute.
* @return the type of the object which contains the attribute
*/
Class<O> getObjectType();
/**
* Returns the type of the attribute.
* @return the type of the attribute
*/
Class<A> getAttributeType();
/**
* Returns the name of the attribute, as supplied to the constructor.
* <p/>
* @return the name of the attribute, as supplied to the constructor
*/
String getAttributeName();
/**
* Returns the values belonging to the attribute in the given object.
* <p/>
* If the attribute is a {@link SimpleAttribute}, the list returned will contain a single value for the attribute.
* If the attribute is a {@link MultiValueAttribute}, the list returned will contain any number of values for the
* attribute.
* <p/>
* @param object The object from which the values of the attribute are required
* @param queryOptions Optional parameters supplied by the application along with the operation which is causing
* this attribute to be invoked (either a query, or an update to the collection)
* @return The values for the attribute in the given object
*/
Iterable<A> getValues(O object, QueryOptions queryOptions);
} | 2,084 | 35.578947 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/StandingQueryAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collections;
/**
* An attribute which wraps a query or query fragment. Any index built on this attribute, will accelerate the entire
* query or query fragment encapsulated in this attribute, returning results for it in constant time complexity O(1).
* <p/>
* When an index based on a {@code StandingQueryAttribute} is added to the collection, objects added to the collection
* will then be tested to see if they match this query. If and only if they match the query exactly, they will be
* added to the index. Subsequently if CQEngine finds the given query in its entirety, or as a branch or
* fragment of a larger query, then it will use the index to answer it in O(1) time complexity.
*
* @author niall.gallagher
*/
public class StandingQueryAttribute<O> extends MultiValueAttribute<O, Boolean> {
final Query<O> standingQuery;
@SuppressWarnings("unchecked")
public StandingQueryAttribute(Query<O> standingQuery) {
super((Class<O>)Object.class, Boolean.class, "<StandingQueryAttribute: " + standingQuery.toString() + ">");
this.standingQuery = standingQuery;
}
@Override
public Class<O> getObjectType() {
throw new UnsupportedOperationException("Unsupported use of StandingQueryAttribute");
}
public Query<O> getQuery() {
return standingQuery;
}
@Override
public Iterable<Boolean> getValues(O object, QueryOptions queryOptions) {
if (standingQuery.matches(object, queryOptions)) {
return Collections.singleton(Boolean.TRUE);
}
return Collections.emptySet();
}
} | 2,362 | 38.383333 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/FunctionalMultiValueAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.MultiValueAttribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A {@link MultiValueAttribute} which wraps a {@link MultiValueFunction}, for the purpose of allowing
* attributes to be created from lambda expressions.
* <p/>
* These attributes can be created via {@link QueryFactory#attribute(Class, MultiValueFunction)}.
*
* @author npgall
*/
public class FunctionalMultiValueAttribute<O, A, I extends Iterable<A>> extends MultiValueAttribute<O, A> {
final MultiValueFunction<O, A, I> function;
public FunctionalMultiValueAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, MultiValueFunction<O, A, I> function) {
super(objectType, attributeType, attributeName);
this.function = function;
}
@Override
public Iterable<A> getValues(O object, QueryOptions queryOptions) {
return function.apply(object);
}
}
| 1,656 | 36.659091 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/AbstractAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.Attribute;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* @author Niall Gallagher
*/
public abstract class AbstractAttribute<O, A> implements Attribute<O, A> {
private final Class<O> objectType;
private final Class<A> attributeType;
private final String attributeName;
private final int cachedHashCode;
public AbstractAttribute() {
this.attributeName = "<Unnamed attribute, " + getClass() + ">";
this.objectType = readGenericObjectType(getClass(), attributeName);
this.attributeType = readGenericAttributeType(getClass(), attributeName);
this.cachedHashCode = calcHashCode();
}
public AbstractAttribute(String attributeName) {
this.attributeName = attributeName;
this.objectType = readGenericObjectType(getClass(), attributeName);
this.attributeType = readGenericAttributeType(getClass(), attributeName);
this.cachedHashCode = calcHashCode();
}
protected AbstractAttribute(Class<O> objectType, Class<A> attributeType) {
this.attributeName = "<Unnamed attribute, " + getClass() + ">";
this.objectType = objectType;
this.attributeType = attributeType;
this.cachedHashCode = calcHashCode();
}
protected AbstractAttribute(Class<O> objectType, Class<A> attributeType, String attributeName) {
this.attributeName = attributeName;
this.objectType = objectType;
this.attributeType = attributeType;
this.cachedHashCode = calcHashCode();
}
@Override
public Class<O> getObjectType() {
return objectType;
}
@Override
public Class<A> getAttributeType() {
return attributeType;
}
@Override
public String getAttributeName() {
return attributeName;
}
@Override
public String toString() {
return "Attribute{" +
"objectType=" + objectType +
", attributeType=" + attributeType +
", attributeName='" + attributeName + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AbstractAttribute)) return false;
AbstractAttribute that = (AbstractAttribute) o;
// TODO: reinstate this cachedHashCode comparison once EqualsVerifier supports cached hash code "shortcut":
//if (cachedHashCode != that.cachedHashCode) return false;
if (!that.canEqual(this)) return false;
if (!attributeName.equals(that.attributeName)) return false;
if (!attributeType.equals(that.attributeType)) return false;
if (!objectType.equals(that.objectType)) return false;
return true;
}
public boolean canEqual(Object other) {
return other instanceof AbstractAttribute;
}
@Override
public int hashCode() {
return cachedHashCode;
}
protected int calcHashCode() {
int result = objectType.hashCode();
result = 31 * result + attributeType.hashCode();
result = 31 * result + attributeName.hashCode();
return result;
}
static <O> Class<O> readGenericObjectType(Class<?> attributeClass, String attributeName) {
try {
ParameterizedType superclass = (ParameterizedType) attributeClass.getGenericSuperclass();
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
Type actualType = superclass.getActualTypeArguments()[0];
Class<O> cls;
if (actualType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)actualType;
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
Class<O> actualClass = (Class<O>) parameterizedType.getRawType();
cls = actualClass;
}
else {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
Class<O> actualClass = (Class<O>) actualType;
cls = actualClass;
}
return cls;
}
catch (Exception e) {
String attributeClassStr = attributeName.startsWith("<Unnamed attribute, class ") ? "" : " (" + attributeClass + ")";
throw new IllegalStateException("Attribute '" + attributeName + "'" + attributeClassStr + " is invalid, cannot read generic type information from it. Attributes should typically EITHER be declared in code with generic type information as a (possibly anonymous) subclass of one of the provided attribute types, OR you can use a constructor of the attribute which allows the types to be specified manually.");
}
}
static <A> Class<A> readGenericAttributeType(Class<?> attributeClass, String attributeName) {
try {
ParameterizedType superclass = (ParameterizedType) attributeClass.getGenericSuperclass();
Type actualType = superclass.getActualTypeArguments()[1];
Class<A> cls;
if (actualType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)actualType;
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
Class<A> actualClass = (Class<A>) parameterizedType.getRawType();
cls = actualClass;
}
else {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
Class<A> actualClass = (Class<A>) actualType;
cls = actualClass;
}
return cls;
}
catch (Exception e) {
String attributeClassStr = attributeName.startsWith("<Unnamed attribute, class ") ? "" : " (" + attributeClass + ")";
throw new IllegalStateException("Attribute '" + attributeName + "'" + attributeClassStr + " is invalid, cannot read generic type information from it. Attributes should typically EITHER be declared in code with generic type information as a (possibly anonymous) subclass of one of the provided attribute types, OR you can use a constructor of the attribute which allows the types to be specified manually.");
}
}
}
| 6,920 | 40.443114 | 419 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/FunctionalSimpleAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A {@link SimpleAttribute} which wraps a {@link SimpleFunction}, for the purpose of allowing
* attributes to be created from lambda expressions.
* <p/>
* These attributes can be created via {@link QueryFactory#attribute(SimpleFunction)}.
*
* @author npgall
*/
public class FunctionalSimpleAttribute<O, A> extends SimpleAttribute<O, A> {
final SimpleFunction<O, A> function;
public FunctionalSimpleAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, SimpleFunction<O, A> function) {
super(objectType, attributeType, attributeName);
this.function = function;
}
@Override
public A getValue(O object, QueryOptions queryOptions) {
return function.apply(object);
}
}
| 1,573 | 34.772727 | 136 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/SimpleFunction.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
/**
* A functional interface which, when used with Java 8+, allows
* CQEngine attributes {@link SimpleAttribute} and {@link SimpleNullableAttribute}
* to be created from lambda expressions.
*
* @author npgall
*/
public interface SimpleFunction<O, A> {
/**
* Applies this function to the given object.
*
* @param object the function argument
* @return the function result
*/
A apply(O object);
} | 1,215 | 31.864865 | 82 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/FunctionalMultiValueNullableAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.MultiValueNullableAttribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A {@link MultiValueNullableAttribute} which wraps a {@link MultiValueFunction}, for the purpose of allowing
* attributes to be created from lambda expressions.
* <p/>
* These attributes can be created via {@link QueryFactory#nullableAttribute(Class, MultiValueFunction)}.
*
* @author npgall
*/
public class FunctionalMultiValueNullableAttribute<O, A, I extends Iterable<A>> extends MultiValueNullableAttribute<O, A> {
final MultiValueFunction<O, A, I> function;
public FunctionalMultiValueNullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, boolean componentValuesNullable, MultiValueFunction<O, A, I> function) {
super(objectType, attributeType, attributeName, componentValuesNullable);
this.function = function;
}
@Override
public Iterable<A> getNullableValues(O object, QueryOptions queryOptions) {
return function.apply(object);
}
}
| 1,770 | 39.25 | 188 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/attribute/support/FunctionalSimpleNullableAttribute.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A {@link SimpleNullableAttribute} which wraps a {@link SimpleFunction}, for the purpose of allowing
* attributes to be created from lambda expressions.
* <p/>
* These attributes can be created via {@link QueryFactory#nullableAttribute(SimpleFunction)}.
*
* @author npgall
*/
public class FunctionalSimpleNullableAttribute<O, A> extends SimpleNullableAttribute<O, A> {
final SimpleFunction<O, A> function;
public FunctionalSimpleNullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, SimpleFunction<O, A> function) {
super(objectType, attributeType, attributeName);
this.function = function;
}
@Override
public A getValue(O object, QueryOptions queryOptions) {
return function.apply(object);
}
}
| 1,621 | 35.863636 | 144 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.