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/attribute/support/MultiValueFunction.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.attribute.MultiValueNullableAttribute;
/**
* A functional interface which, when used with Java 8+, allows
* CQEngine attributes {@link MultiValueAttribute} and {@link MultiValueNullableAttribute}
* to be created from lambda expressions.
*
* @author npgall
*/
public interface MultiValueFunction<O, A, I extends Iterable<A>> {
/**
* Applies this function to the given object.
*
* @param object the function argument
* @return the function result
*/
I apply(O object);
} | 1,258 | 33.027027 | 90 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/AttributeNameProducers.java | /**
* Copyright 2012-2019 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.codegen;
import com.googlecode.cqengine.codegen.MemberFilters.GetterPrefix;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.function.Function;
/**
* Provides some functions for use alongside {@link MemberFilters} which produce the name of an attribute from
* the name of the member, sometimes transforming the name to a more human-readable form.
*/
public class AttributeNameProducers {
/**
* Returns the name of the member verbatim.
*/
public static Function<Member, String> USE_MEMBER_NAMES_VERBATIM = Member::getName;
/**
* If the member is a method, whose name starts with a getter prefix, converts the name of the getter method
* to a more human readable form, by stripping the getter prefix and converting the first character to lowercase.
* Otherwise, returns the name of the member verbatim.
* <p>
* Examples: ["getFoo" -> "foo"], ["isFoo" -> "foo"], ["hasFoo" -> "foo"]
*/
public static Function<Member, String> USE_HUMAN_READABLE_NAMES_FOR_GETTERS = AttributeNameProducers::getterToHumanReadableName;
private static String getterToHumanReadableName(Member member) {
String memberName = member.getName();
if (member instanceof Method) {
for (GetterPrefix prefix : GetterPrefix.values()) {
if (memberName.startsWith(prefix.name()) && memberName.length() > prefix.name().length()) {
StringBuilder sb = new StringBuilder(memberName);
// Strip the getter prefix...
sb.delete(0, prefix.name().length());
// Convert the first character to lowercase..
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
return sb.toString();
}
}
}
return memberName;
}
}
| 2,512 | 39.532258 | 132 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/MemberFilters.java | package com.googlecode.cqengine.codegen;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/**
* Provides some general purpose {@link MemberFilter}s which can be used with {@link AttributeSourceGenerator} or
* {@link AttributeBytecodeGenerator}.
*/
public class MemberFilters {
enum GetterPrefix { get, is, has }
/**
* A filter which matches all members (both fields and methods).
*/
public static final MemberFilter ALL_MEMBERS = member -> true;
/**
* A filter which matches all fields.
*/
public static final MemberFilter FIELDS_ONLY = member -> member instanceof Field;
/**
* A filter which matches all methods.
*/
public static final MemberFilter METHODS_ONLY = member -> member instanceof Method;
/**
* A filter which matches all methods which start with "get", "is" and "has" and where the following character
* is in uppercase.
*/
public static final MemberFilter GETTER_METHODS_ONLY = member -> {
if (member instanceof Method) {
for (GetterPrefix prefix : GetterPrefix.values()) {
if (hasGetterPrefix(member.getName(), prefix.name())) {
return true;
}
}
}
return false;
};
static boolean hasGetterPrefix(String memberName, String prefix) {
int prefixLength = prefix.length();
return memberName.length() > prefixLength
&& memberName.startsWith(prefix)
&& Character.isUpperCase(memberName.charAt(prefixLength));
}
/**
* Private constructor, not used.
*/
MemberFilters() {
}
}
| 1,705 | 28.413793 | 114 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/MemberFilter.java | package com.googlecode.cqengine.codegen;
import java.lang.reflect.Member;
/**
* A filter which determines the subset of the members of a class (fields and methods) for which
* attributes should be generated.
* <p/>
* This can be supplied to {@link AttributeSourceGenerator} or {@link AttributeBytecodeGenerator}.
*
* @see MemberFilters
*/
public interface MemberFilter {
boolean accept(Member member);
}
| 418 | 23.647059 | 98 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/AttributeBytecodeGenerator.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.codegen;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.codegen.support.GeneratedAttributeSupport;
import com.googlecode.cqengine.query.option.QueryOptions;
import javassist.*;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.SignatureAttribute;
import java.lang.reflect.*;
import java.util.*;
import java.util.function.Function;
import static com.googlecode.cqengine.codegen.AttributeSourceGenerator.*;
import static com.googlecode.cqengine.codegen.MemberFilters.FIELDS_ONLY;
import static java.lang.reflect.Modifier.*;
/**
* Generates Attributes by synthesizing bytecode, avoiding the need to write attributes by hand.
* The synthesized attributes should perform as well at runtime as hand-written ones in most cases.
* <p/>
* Generated attributes are loaded into the ClassLoader of the given POJO classes.
* <p/>
* See {@link MemberFilter} and {@link MemberFilters} for some common filters which can be used with this class
* to determine the subset of fields or methods in a POJO for which attributes should be generated.
*/
public class AttributeBytecodeGenerator {
/**
* Auto-generates and instantiates a set of attributes which read values from the fields in the given POJO class.
* <p>
* This is equivalent to calling {@link #createAttributes(Class, MemberFilter)} with
* {@link MemberFilters#FIELDS_ONLY}.
*
* @param pojoClass The POJO class containing fields for which attributes are to be created
* @return A map of field/attribute names to Attribute objects which read values from the fields in the given POJO
* class
*/
public static <O> Map<String, ? extends Attribute<O, ?>> createAttributes(Class<O> pojoClass) {
return createAttributes(pojoClass, FIELDS_ONLY);
}
/**
* Auto-generates and instantiates a set of attributes which read values from the members (fields or methods)
* in the given POJO class.
* <p>
* This is equivalent to calling {@link #createAttributes(Class, MemberFilter, Function)} with
* {@link MemberFilters#FIELDS_ONLY} and {@link AttributeNameProducers#USE_MEMBER_NAMES_VERBATIM}.
*
* @param pojoClass The POJO class containing fields for which attributes are to be created
* @param memberFilter A filter which determines the subset of the members of a class (fields and methods)
* for which attributes should be generated
* @return A map of field/attribute names to Attribute objects which read values from the members in the given POJO
* class
*/
@SuppressWarnings("unchecked")
public static <O> Map<String, ? extends Attribute<O, ?>> createAttributes(Class<O> pojoClass, MemberFilter memberFilter) {
return createAttributes(pojoClass, memberFilter, AttributeNameProducers.USE_MEMBER_NAMES_VERBATIM);
}
/**
* Auto-generates and instantiates a set of attributes which read values from the members (fields or methods)
* in the given POJO class.
* <p>
* By default, attributes will be generated for all non-private members declared directly in the POJO class,
* and for inherited members as well, as long as the access modifiers on inherited members in their superclass(es)
* allow those members to be accessed from the package of the POJO class. So if the POJO class is in the same
* package as a superclass, then attributes will be generated for package-private, protected, and public members
* in the superclass. If the POJO class is in a different package from the superclass, then attributes will only be
* generated for protected and public members in the superclass.
*
* @param pojoClass The POJO class containing fields for which attributes are to be created
* @param memberFilter A filter which determines the subset of the members of a class (fields and methods)
* for which attributes should be generated
* @param attributeNameProducer A function which generates a name for an attribute, given the {@link Member}
* for which the attribute will be generated
* @return A map of field/attribute names to Attribute objects which read values from the members in the given POJO
* class
*/
@SuppressWarnings("unchecked")
public static <O> Map<String, ? extends Attribute<O, ?>> createAttributes(Class<O> pojoClass, MemberFilter memberFilter, Function<Member, String> attributeNameProducer) {
final Map<String, Attribute<O, ?>> attributes = new TreeMap<String, Attribute<O, ?>>();
Class currentClass = pojoClass;
Set<String> membersEncountered = new HashSet<String>();
while (currentClass != null && currentClass != Object.class) {
for (Member member : getMembers(currentClass)) {
try {
if (!memberFilter.accept(member)) {
continue;
}
if (membersEncountered.contains(member.getName())) {
// We already generated an attribute for a member with this name in a subclass of the current class...
continue;
}
int modifiers = member.getModifiers();
String memberName = member.getName();
String attributeName = attributeNameProducer.apply(member);
Class<?> memberType = getType(member);
Class<? extends Attribute<O, ?>> attributeClass;
if (!isStatic(modifiers) && !isPrivate(modifiers)) {
// If the member is declared in a superclass in a different package,
// only generate an attribute for it, if the member is actually accessible from the subclass;
// that is it is declared public or protected...
if (!member.getDeclaringClass().getPackage().getName().equals(pojoClass.getPackage().getName())
&& !(isProtected(modifiers) || isPublic(modifiers))) {
continue;
}
if (memberType.isPrimitive()) {
Class<?> wrapperType = getWrapperForPrimitive(memberType);
attributeClass = (member instanceof Method)
? generateSimpleAttributeForGetter(pojoClass, wrapperType, memberName, attributeName)
: generateSimpleAttributeForField(pojoClass, wrapperType, memberName, attributeName);
} else if (Iterable.class.isAssignableFrom(memberType)) {
ParameterizedType parameterizedType = getGenericType(member);
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
if (actualTypeArguments.length != 1) {
throw new UnsupportedOperationException();
}
Class<?> genericType = (Class<?>) actualTypeArguments[0];
attributeClass = (member instanceof Method)
? generateMultiValueNullableAttributeForGetter(pojoClass, genericType, memberName, true, attributeName)
: generateMultiValueNullableAttributeForField(pojoClass, genericType, memberName, true, attributeName);
} else if (memberType.isArray()) {
Class<?> componentType = memberType.getComponentType();
if (componentType.isPrimitive()) {
Class<?> wrapperType = getWrapperForPrimitive(componentType);
attributeClass = (member instanceof Method)
? generateMultiValueNullableAttributeForGetter(pojoClass, wrapperType, memberName, false, attributeName)
: generateMultiValueNullableAttributeForField(pojoClass, wrapperType, memberName, false, attributeName);
}
else {
attributeClass = (member instanceof Method)
? generateMultiValueNullableAttributeForGetter(pojoClass, componentType, memberName, true, attributeName)
: generateMultiValueNullableAttributeForField(pojoClass, componentType, memberName, true, attributeName);
}
} else {
attributeClass = (member instanceof Method)
? generateSimpleNullableAttributeForGetter(pojoClass, memberType, memberName, attributeName)
: generateSimpleNullableAttributeForField(pojoClass, memberType, memberName, attributeName);
}
Attribute<O, ?> attribute = attributeClass.newInstance();
attributes.put(attribute.getAttributeName(), attribute);
membersEncountered.add(member.getName());
}
} catch (Throwable e) {
throw new IllegalStateException("Failed to create attribute for member: " + member.toString(), e);
}
}
currentClass = currentClass.getSuperclass();
}
return attributes;
}
/**
* Generates a {@link SimpleAttribute} which reads a non-null value from the given field in a POJO.
* <p>
* The type of value returned by the attribute should match the type of the field. However reading primitive values
* is also supported. In that case, the attribute will box the primitive value to its wrapper type automatically,
* and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the field
* @param attributeValueType The type of value returned by the attribute
* @param fieldName The name of the field
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleAttribute<O, A>> generateSimpleAttributeForField(Class<O> pojoClass, Class<A> attributeValueType, String fieldName, String attributeName) {
ensureFieldExists(pojoClass, attributeValueType, fieldName, attributeName);
return generateSimpleAttribute(SimpleAttribute.class, pojoClass, attributeValueType, attributeName, "object." + fieldName);
}
/**
* Generates a {@link SimpleAttribute} which reads a non-null value from the given getter method in a POJO.
* The getter method should not take any arguments.
* <p>
* The type of value returned by the attribute should match the return type of the getter. However reading from
* getters which return primitive values is also supported. In that case, the attribute will box the primitive value
* to its wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleAttribute<O, A>> generateSimpleAttributeForGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String attributeName) {
ensureGetterExists(pojoClass, attributeValueType, getterMethodName, attributeName);
return generateSimpleAttribute(SimpleAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "()");
}
/**
* Generates a {@link SimpleAttribute} which reads a non-null value from the given <i>parameterized</i> getter
* method in a POJO. The getter method should take a single string argument.
* <p>
* The type of value returned by the attribute should match the return type of the getter. However reading from
* getters which return primitive values is also supported. In that case, the attribute will box the primitive value
* to its wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param getterParameter The string argument to supply to the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleAttribute<O, A>> generateSimpleAttributeForParameterizedGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String getterParameter, String attributeName) {
ensureParameterizedGetterExists(pojoClass, attributeValueType, getterMethodName, getterParameter, attributeName);
return generateSimpleAttribute(SimpleAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "(\"" + getterParameter + "\")");
}
/**
* Generates a {@link SimpleNullableAttribute} which reads a possibly-null value from the given field in a POJO.
* <p>
* The type of value returned by the attribute should match the type of the field. However reading primitive values
* is also supported. In that case, the attribute will box the primitive value to its wrapper type automatically,
* and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the field
* @param attributeValueType The type of value returned by the attribute
* @param fieldName The name of the field
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleNullableAttribute<O, A>> generateSimpleNullableAttributeForField(Class<O> pojoClass, Class<A> attributeValueType, String fieldName, String attributeName) {
ensureFieldExists(pojoClass, attributeValueType, fieldName, attributeName);
return generateSimpleAttribute(SimpleNullableAttribute.class, pojoClass, attributeValueType, attributeName, "object." + fieldName);
}
/**
* Generates a {@link SimpleNullableAttribute} which reads a possibly-null value from the given getter method in a
* POJO. The getter method should not take any arguments.
* <p>
* The type of value returned by the attribute should match the return type of the getter. However reading from
* getters which return primitive values is also supported. In that case, the attribute will box the primitive value
* to its wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleNullableAttribute<O, A>> generateSimpleNullableAttributeForGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String attributeName) {
ensureGetterExists(pojoClass, attributeValueType, getterMethodName, attributeName);
return generateSimpleAttribute(SimpleNullableAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "()");
}
/**
* Generates a {@link SimpleNullableAttribute} which reads a possibly-null value from the given <i>parameterized</i>
* getter method in a POJO. The getter method should take a single string argument.
* <p>
* The type of value returned by the attribute should match the return type of the getter. However reading from
* getters which return primitive values is also supported. In that case, the attribute will box the primitive value
* to its wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param getterParameter The string argument to supply to the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends SimpleNullableAttribute<O, A>> generateSimpleNullableAttributeForParameterizedGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String getterParameter, String attributeName) {
ensureParameterizedGetterExists(pojoClass, attributeValueType, getterMethodName, getterParameter, attributeName);
return generateSimpleAttribute(SimpleNullableAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "(\"" + getterParameter + "\")");
}
/**
* Generates a {@link MultiValueAttribute} which reads non-null values from the given field in a POJO.
* <p>
* The type of values returned by the attribute should match the type of values stored in the field. The field may
* be a List or an array, of objects of the same type as the attribute. However reading from primitive arrays is
* also supported. In that case, the attribute will box the primitive values to their wrapper type automatically,
* and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the field
* @param attributeValueType The type of values returned by the attribute
* @param fieldName The name of the field
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of values returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueAttribute<O, A>> generateMultiValueAttributeForField(Class<O> pojoClass, Class<A> attributeValueType, String fieldName, String attributeName) {
ensureFieldExists(pojoClass, attributeValueType, fieldName, attributeName);
return generateMultiValueAttribute(MultiValueAttribute.class, pojoClass, attributeValueType, attributeName, "object." + fieldName);
}
/**
* Generates a {@link MultiValueAttribute} which reads non-null values from the given getter method in a POJO.
* The getter method should not take any arguments.
* <p>
* The type of values returned by the attribute should match the type of values returned by the getter. The getter
* may return a List or an array, of objects of the same type as the attribute. However reading from getters which
* return primitive arrays is also supported. In that case, the attribute will box the primitive values to their
* wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueAttribute<O, A>> generateMultiValueAttributeForGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String attributeName) {
ensureGetterExists(pojoClass, attributeValueType, getterMethodName, attributeName);
return generateMultiValueAttribute(MultiValueAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "()");
}
/**
* Generates a {@link MultiValueAttribute} which reads non-null values from the given <i>parameterized</i> getter
* method in a POJO. The getter method should take a single string argument.
* <p>
* The type of values returned by the attribute should match the type of values returned by the getter. The getter
* may return a List or an array, of objects of the same type as the attribute. However reading from getters which
* return primitive arrays is also supported. In that case, the attribute will box the primitive values to their
* wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param getterParameter The string argument to supply to the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueAttribute<O, A>> generateMultiValueAttributeForParameterizedGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String getterParameter, String attributeName) {
ensureParameterizedGetterExists(pojoClass, attributeValueType, getterMethodName, getterParameter, attributeName);
return generateMultiValueAttribute(MultiValueAttribute.class, pojoClass, attributeValueType, attributeName, "object." + getterMethodName + "(\"" + getterParameter + "\")");
}
/**
* Generates a {@link MultiValueAttribute} which reads possibly-null values from the given field in a POJO.
* <p>
* The type of values returned by the attribute should match the type of values stored in the field. The field may
* be a List or an array, of objects of the same type as the attribute. However reading from primitive arrays is
* also supported. In that case, the attribute will box the primitive values to their wrapper type automatically,
* and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the field
* @param attributeValueType The type of values returned by the attribute
* @param fieldName The name of the field
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of values returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueNullableAttribute<O, A>> generateMultiValueNullableAttributeForField(Class<O> pojoClass, Class<A> attributeValueType, String fieldName, boolean componentValuesNullable, String attributeName) {
ensureFieldExists(pojoClass, attributeValueType, fieldName, attributeName);
return generateMultiValueNullableAttribute(MultiValueNullableAttribute.class, pojoClass, attributeValueType, attributeName, componentValuesNullable, "object." + fieldName);
}
/**
* Generates a {@link MultiValueAttribute} which reads possibly-null values from the given getter method in a POJO.
* The getter method should not take any arguments.
* <p>
* The type of values returned by the attribute should match the type of values returned by the getter. The getter
* may return a List or an array, of objects of the same type as the attribute. However reading from getters which
* return primitive arrays is also supported. In that case, the attribute will box the primitive values to their
* wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueNullableAttribute<O, A>> generateMultiValueNullableAttributeForGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, boolean componentValuesNullable, String attributeName) {
ensureGetterExists(pojoClass, attributeValueType, getterMethodName, attributeName);
return generateMultiValueNullableAttribute(MultiValueNullableAttribute.class, pojoClass, attributeValueType, attributeName, componentValuesNullable, "object." + getterMethodName + "()");
}
/**
* Generates a {@link MultiValueAttribute} which reads possibly-null values from the given <i>parameterized</i>
* getter method in a POJO. The getter method should take a single string argument.
* <p>
* The type of values returned by the attribute should match the type of values returned by the getter. The getter
* may return a List or an array, of objects of the same type as the attribute. However reading from getters which
* return primitive arrays is also supported. In that case, the attribute will box the primitive values to their
* wrapper type automatically, and so the type of the attribute itself should be the wrapper type.
*
* @param pojoClass The class containing the getter method
* @param attributeValueType The type of value returned by the attribute
* @param getterMethodName The name of the getter method
* @param getterParameter The string argument to supply to the getter method
* @param attributeName The name to give to the attribute
* @param <O> Type of the POJO object
* @param <A> The type of value returned by the attribute
* @return A generated class for an attribute which reads from the POJO as discussed above
*/
@SuppressWarnings("unchecked")
public static <O, A> Class<? extends MultiValueNullableAttribute<O, A>> generateMultiValueNullableAttributeForParameterizedGetter(Class<O> pojoClass, Class<A> attributeValueType, String getterMethodName, String getterParameter, boolean componentValuesNullable, String attributeName) {
ensureParameterizedGetterExists(pojoClass, attributeValueType, getterMethodName, getterParameter, attributeName);
return generateMultiValueNullableAttribute(MultiValueNullableAttribute.class, pojoClass, attributeValueType, attributeName, componentValuesNullable, "object." + getterMethodName + "(\"" + getterParameter + "\")");
}
/**
* Helper method for generating SimpleAttribute AND SimpleNullableAttribute.
*
* @param target Snippet of code which reads the value, such as: <code>object.fieldName</code>, <code>object.getFoo()</code>, or <code>object.getFoo("bar")</code>
*/
private static <O, A, C extends Attribute<O, A>, R extends Class<? extends C>> R generateSimpleAttribute(Class<C> attributeSuperClass, Class<O> pojoClass, Class<A> attributeValueType, String attributeName, String target) {
try {
ClassPool pool = new ClassPool(false);
pool.appendClassPath(new ClassClassPath(pojoClass));
CtClass attributeClass = pool.makeClass(pojoClass.getName() + "$$CQEngine_" + attributeSuperClass.getSimpleName() + "_" + attributeName);
attributeClass.setSuperclass(pool.get(attributeSuperClass.getName()));
SignatureAttribute.ClassType genericTypeOfAttribute = new SignatureAttribute.ClassType(
attributeSuperClass.getName(),
new SignatureAttribute.TypeArgument[]{
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(pojoClass.getName())),
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(attributeValueType.getName()))
}
);
attributeClass.setGenericSignature(genericTypeOfAttribute.encode());
// Add a no-arg constructor which pass the attribute name to the superclass...
CtConstructor constructor = CtNewConstructor.make(
"public " + attributeClass.getSimpleName() + "() { "
+ "super(\"" + attributeName + "\");"
+ " }", attributeClass);
attributeClass.addConstructor(constructor);
// Add the getter method...
CtMethod getterMethod = CtMethod.make(
"public " + attributeValueType.getName() + " getValue(" + pojoClass.getName() + " object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return (" + attributeValueType.getName() + ") " + GeneratedAttributeSupport.class.getName() + ".valueOf(" + target + ");"
+ " }", attributeClass);
attributeClass.addMethod(getterMethod);
// Add a bridge method for the getter method to account for type erasure (see https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html)...
CtMethod getterBridgeMethod = CtMethod.make(
"public java.lang.Object getValue(java.lang.Object object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return getValue((" + pojoClass.getName() + ")object, queryOptions);"
+ " }", attributeClass);
getterBridgeMethod.setModifiers(getterBridgeMethod.getModifiers() | AccessFlag.BRIDGE);
attributeClass.addMethod(getterBridgeMethod);
@SuppressWarnings("unchecked")
R result = (R) attributeClass.toClass(pojoClass.getClassLoader(), pojoClass.getProtectionDomain());
attributeClass.detach();
return result;
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
/**
* Helper method for generating MultiValueAttribute.
*
* @param target Snippet of code which reads the value, such as: <code>object.fieldName</code>, <code>object.getFoo()</code>, or <code>object.getFoo("bar")</code>
*/
private static <O, A, C extends MultiValueAttribute<O, A>, R extends Class<? extends C>> R generateMultiValueAttribute(Class<C> attributeSuperClass, Class<O> pojoClass, Class<A> attributeValueType, String attributeName, String target) {
try {
ClassPool pool = new ClassPool(false);
pool.appendClassPath(new ClassClassPath(pojoClass));
CtClass attributeClass = pool.makeClass(pojoClass.getName() + "$$CQEngine_" + attributeSuperClass.getSimpleName() + "_" + attributeName);
attributeClass.setSuperclass(pool.get(attributeSuperClass.getName()));
SignatureAttribute.ClassType genericTypeOfAttribute = new SignatureAttribute.ClassType(
attributeSuperClass.getName(),
new SignatureAttribute.TypeArgument[]{
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(pojoClass.getName())),
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(attributeValueType.getName()))
}
);
attributeClass.setGenericSignature(genericTypeOfAttribute.encode());
// Add a no-arg constructor which pass the attribute name to the superclass...
CtConstructor constructor = CtNewConstructor.make(
"public " + attributeClass.getSimpleName() + "() { "
+ "super(\"" + attributeName + "\");"
+ " }", attributeClass);
attributeClass.addConstructor(constructor);
// Add the getter method...
CtMethod getterMethod = CtMethod.make(
"public java.lang.Iterable getValues(" + pojoClass.getName() + " object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return " + GeneratedAttributeSupport.class.getName() + ".valueOf(" + target + ");"
+ " }", attributeClass);
getterMethod.setGenericSignature(new SignatureAttribute.MethodSignature(
new SignatureAttribute.TypeParameter[0],
new SignatureAttribute.Type[]{new SignatureAttribute.ClassType(pojoClass.getName())},
new SignatureAttribute.ClassType(
java.lang.Iterable.class.getName(),
new SignatureAttribute.TypeArgument[]{
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(attributeValueType.getName()))
}
),
new SignatureAttribute.ObjectType[0]
).encode());
attributeClass.addMethod(getterMethod);
// Add a bridge method for the getter method to account for type erasure (see https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html)...
CtMethod getterBridgeMethod = CtMethod.make(
"public java.lang.Iterable getValues(java.lang.Object object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return getValues((" + pojoClass.getName() + ")object, queryOptions);"
+ " }", attributeClass);
getterBridgeMethod.setModifiers(getterBridgeMethod.getModifiers() | AccessFlag.BRIDGE);
attributeClass.addMethod(getterBridgeMethod);
@SuppressWarnings("unchecked")
R result = (R) attributeClass.toClass(pojoClass.getClassLoader(), pojoClass.getProtectionDomain());
attributeClass.detach();
return result;
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
/**
* Helper method for generating MultiValueNullableAttribute.
*
* @param target Snippet of code which reads the value, such as: <code>object.fieldName</code>, <code>object.getFoo()</code>, or <code>object.getFoo("bar")</code>
*/
private static <O, A, C extends MultiValueNullableAttribute<O, A>, R extends Class<? extends C>> R generateMultiValueNullableAttribute(Class<C> attributeSuperClass, Class<O> pojoClass, Class<A> attributeValueType, String attributeName, boolean componentValuesNullable, String target) {
try {
ClassPool pool = new ClassPool(false);
pool.appendClassPath(new ClassClassPath(pojoClass));
CtClass attributeClass = pool.makeClass(pojoClass.getName() + "$$CQEngine_" + attributeSuperClass.getSimpleName() + "_" + attributeName);
attributeClass.setSuperclass(pool.get(attributeSuperClass.getName()));
SignatureAttribute.ClassType genericTypeOfAttribute = new SignatureAttribute.ClassType(
attributeSuperClass.getName(),
new SignatureAttribute.TypeArgument[]{
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(pojoClass.getName())),
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(attributeValueType.getName()))
}
);
attributeClass.setGenericSignature(genericTypeOfAttribute.encode());
// Add a no-arg constructor which pass the attribute name to the superclass...
CtConstructor constructor = CtNewConstructor.make(
"public " + attributeClass.getSimpleName() + "() { "
+ "super(\"" + attributeName + "\", " + componentValuesNullable + ");"
+ " }", attributeClass);
attributeClass.addConstructor(constructor);
// Add the getter method...
CtMethod getterMethod = CtMethod.make(
"public java.lang.Iterable getNullableValues(" + pojoClass.getName() + " object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return " + GeneratedAttributeSupport.class.getName() + ".valueOf(" + target + ");"
+ " }", attributeClass);
getterMethod.setGenericSignature(new SignatureAttribute.MethodSignature(
new SignatureAttribute.TypeParameter[0],
new SignatureAttribute.Type[]{new SignatureAttribute.ClassType(pojoClass.getName())},
new SignatureAttribute.ClassType(
java.lang.Iterable.class.getName(),
new SignatureAttribute.TypeArgument[]{
new SignatureAttribute.TypeArgument(new SignatureAttribute.ClassType(attributeValueType.getName()))
}
),
new SignatureAttribute.ObjectType[0]
).encode());
attributeClass.addMethod(getterMethod);
// Add a bridge method for the getter method to account for type erasure (see https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html)...
CtMethod getterBridgeMethod = CtMethod.make(
"public java.lang.Iterable getNullableValues(java.lang.Object object, " + QueryOptions.class.getName() + " queryOptions) { "
+ "return getNullableValues((" + pojoClass.getName() + ")object, queryOptions);"
+ " }", attributeClass);
getterBridgeMethod.setModifiers(getterBridgeMethod.getModifiers() | AccessFlag.BRIDGE);
attributeClass.addMethod(getterBridgeMethod);
@SuppressWarnings("unchecked")
R result = (R) attributeClass.toClass(pojoClass.getClassLoader(), pojoClass.getProtectionDomain());
attributeClass.detach();
return result;
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
static String getClassName(Class<?> cls) {
return cls != null ? cls.getName() : null;
}
static void ensureFieldExists(Class<?> pojoClass, Class<?> attributeValueType, String fieldName, String attributeName) {
try {
// Validate that the field exists...
while (pojoClass != null) {
try {
pojoClass.getDeclaredField(fieldName);
return;
} catch (NoSuchFieldException e) {
pojoClass = pojoClass.getSuperclass();
}
}
throw new NoSuchFieldException(fieldName);
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
static void ensureGetterExists(Class<?> pojoClass, Class<?> attributeValueType, String getterMethodName, String attributeName) {
try {
while (pojoClass != null) {
try {
pojoClass.getDeclaredMethod(getterMethodName);
return;
} catch (NoSuchMethodException e) {
pojoClass = pojoClass.getSuperclass();
}
}
throw new NoSuchMethodException(getterMethodName);
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
static void ensureParameterizedGetterExists(Class<?> pojoClass, Class<?> attributeValueType, String parameterizedGetterMethodName, String getterParameter, String attributeName) {
try {
if (getterParameter.contains("\"") || getterParameter.contains("\\")) {
throw new IllegalArgumentException("Getter parameter contains unsupported characters: " + getterParameter);
}
while (pojoClass != null) {
try {
pojoClass.getDeclaredMethod(parameterizedGetterMethodName, String.class);
return;
} catch (NoSuchMethodException e) {
pojoClass = pojoClass.getSuperclass();
}
}
throw new NoSuchMethodException(parameterizedGetterMethodName + "(String)");
} catch (Exception e) {
throw new IllegalStateException(getExceptionMessage(pojoClass, attributeValueType, attributeName), e);
}
}
static String getExceptionMessage(Class<?> pojoClass, Class<?> attributeValueType, String attributeName) {
return "Failed to generate attribute for class " + getClassName(pojoClass) + ", type " + getClassName(attributeValueType) + ", name '" + attributeName + "'";
}
static Class<?> getWrapperForPrimitive(Class<?> primitiveType) {
Class<?> wrapperType = PRIMITIVES_TO_WRAPPERS.get(primitiveType);
if (wrapperType == null) {
throw new IllegalStateException("No wrapper type for primitive type: " + primitiveType);
}
return wrapperType;
}
static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new LinkedHashMap<Class<?>, Class<?>>() {{
put(boolean.class, Boolean.class);
put(byte.class, Byte.class);
put(char.class, Character.class);
put(double.class, Double.class);
put(float.class, Float.class);
put(int.class, Integer.class);
put(long.class, Long.class);
put(short.class, Short.class);
put(void.class, Void.class);
}};
}
| 45,177 | 63.173295 | 289 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/AttributeSourceGenerator.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.codegen;
import java.lang.reflect.*;
import java.util.*;
import static com.googlecode.cqengine.codegen.MemberFilters.ALL_MEMBERS;
import static com.googlecode.cqengine.codegen.MemberFilters.FIELDS_ONLY;
/**
* Automatically generates source code defining CQEngine attributes for accessing the fields and methods (aka members)
* of a given target class.
* <p/>
* Generates CQEngine {@link com.googlecode.cqengine.attribute.SimpleAttribute}s or
* {@link com.googlecode.cqengine.attribute.SimpleNullableAttribute}s for members which return singular values,
* and generates CQEngine {@link com.googlecode.cqengine.attribute.MultiValueNullableAttribute}s for members
* which return Iterables or arrays.
* <p/>
* Note that by default this code generator is cautious and generates "Nullable" attributes by default, for all members
* except those which return primitive types. Nullable attributes check for and handle nulls automatically, however
* checking for nulls incurs a performance penalty at runtime. So for non-primitive fields and accessor methods which
* will not actually contain or return null, it is recommended to replace those attributes with non-nullable variants
* as discussed in the comments in the generated source code. This is optional but can remove the overhead of
* unnecessary null checks at runtime.
* <p/>
* Methods are provided both to generate source code for attributes which can be copy-pasted into the target class,
* and to generate entirely separate attributes classes. In the latter case, for example if class "Car" is given
* as the target class, source code for a companion class "CQCar" will be generated containing attributes for accessing
* the fields and accessor methods in class "Car".
* <p/>
* @author Niall Gallagher
*/
public class AttributeSourceGenerator {
/**
* Generates source code which defines attributes for accessing all fields in the given target class, for the
* purpose of copy-pasting directly into the target class.
*
* @param targetClass The POJO class containing fields for which attributes are to be generated
* @return Source code defining attributes for accessing each of the fields in the target class
*/
public static String generateAttributesForPastingIntoTargetClass(final Class<?> targetClass) {
return generateAttributesForClass(targetClass, false, "", FIELDS_ONLY);
}
/**
* Generates source code which defines attributes for accessing all members (fields and methods) in the given target
* class which are acceptable to the given filter, for the purpose of copy-pasting directly into the target class.
*
* @param targetClass The POJO class containing members for which attributes are to be generated
* @param memberFilter A filter which determines the subset of the members of a class (fields and accessor methods)
* for which attributes should be generated
* @return Source code defining attributes for accessing each of the members in the target class
*/
public static String generateAttributesForPastingIntoTargetClass(final Class<?> targetClass, MemberFilter memberFilter) {
return generateAttributesForClass(targetClass, false, "", memberFilter);
}
/**
* Generates source code of a complete separate class, containing attributes for accessing all members
* (fields and methods) in the given target class.
*
* @param targetClass The POJO class containing members for which attributes are to be generated
* @param packageOfAttributesClass The desired package name of the attributes class. Note this will be used to
* determine which members will be visible to the generated class, i.e. attributes for package-private members will
* only be generated if the generated class will be in the same package as the target class
* @return Source code of a complete separate class, containing attributes for accessing members in the given target
* class
*/
public static String generateSeparateAttributesClass(final Class<?> targetClass, String packageOfAttributesClass) {
return generateAttributesForClass(targetClass, true, packageOfAttributesClass, ALL_MEMBERS);
}
/**
* Generates source code of a complete separate class, containing attributes for accessing all members
* (fields and methods) in the given target class which are acceptable to the given filter.
*
* @param targetClass The POJO class containing members for which attributes are to be generated
* @param packageOfAttributesClass The desired package name of the attributes class. Note this will be used to
* determine which members will be visible to the generated class, i.e. attributes for package-private members will
* only be generated if the generated class will be in the same package as the target class
* @param memberFilter A filter which determines the subset of the members of a class (fields and accessor methods)
* for which attributes should be generated
* @return Source code of a complete separate class, containing attributes for accessing members in the given target
* class
*/
public static String generateSeparateAttributesClass(final Class<?> targetClass, String packageOfAttributesClass, MemberFilter memberFilter) {
return generateAttributesForClass(targetClass, true, packageOfAttributesClass, memberFilter);
}
/**
* Generates source code of a complete separate class, containing attributes for accessing all members
* (fields and methods) in the given target class.
*
* @param targetClass The POJO class containing members for which attributes are to be generated
* @param packageOfAttributesClass The desired package name of the attributes class. Note this will be used to
* determine which members will be visible to the generated class, i.e. attributes for package-private members will
* only be generated if the generated class will be in the same package as the target class
* @return Source code of a complete separate class, containing attributes for accessing members in the given target class
*/
public static String generateSeparateAttributesClass(final Class<?> targetClass, Package packageOfAttributesClass) {
return generateAttributesForClass(targetClass, true, packageOfAttributesClass.getName(), ALL_MEMBERS);
}
/**
* Generates source code of a complete separate class, containing attributes for accessing all members
* (fields and methods) in the given target class which are acceptable to the given filter.
*
* @param targetClass The POJO class containing members for which attributes are to be generated
* @param packageOfAttributesClass The desired package name of the attributes class. Note this will be used to
* determine which members will be visible to the generated class, i.e. attributes for package-private members will
* only be generated if the generated class will be in the same package as the target class
* @param memberFilter A filter which determines the subset of the members of a class (fields and accessor methods)
* for which attributes should be generated
* @return Source code of a complete separate class, containing attributes for accessing members in the given target
* class
*/
public static String generateSeparateAttributesClass(final Class<?> targetClass, Package packageOfAttributesClass, MemberFilter memberFilter) {
return generateAttributesForClass(targetClass, true, packageOfAttributesClass.getName(), memberFilter);
}
static String generateAttributesForClass(final Class<?> targetClass, boolean separateAttributesClass, String packageOfAttributesClass, MemberFilter memberFilter) {
StringBuilder sb = new StringBuilder();
if (separateAttributesClass) {
sb.append("package ").append(packageOfAttributesClass).append(";\n\n");
sb.append("import com.googlecode.cqengine.attribute.*;\n");
sb.append("import com.googlecode.cqengine.query.option.QueryOptions;\n");
sb.append("import java.util.*;\n");
String targetClassName = targetClass.getName().replace("$", "."); // replacing $ handles nested classes
sb.append("import ").append(targetClassName).append(";\n\n");
sb.append("/**\n");
sb.append(" * CQEngine attributes for accessing the members of class {@code ").append(targetClassName).append("}.\n");
sb.append(" * <p/>.\n");
sb.append(" * Auto-generated by CQEngine's {@code ").append(AttributeSourceGenerator.class.getSimpleName()).append("}.\n");
sb.append(" */\n");
sb.append("public class CQ").append(targetClass.getSimpleName()).append(" {");
}
Class currentClass = targetClass;
Set<String> membersEncountered = new HashSet<String>();
while (currentClass != null && currentClass != Object.class) {
for (Member member : getMembers(currentClass)) {
if (!memberFilter.accept(member)) {
continue;
}
if (membersEncountered.contains(member.getName())) {
// We already generated an attribute for a member with this name in a subclass of the current class...
continue;
}
int modifiers = member.getModifiers();
if (!Modifier.isStatic(modifiers)) {
if (Modifier.isPrivate(modifiers)) {
// Generate attribute for this private member, if the attribute will be pasted into the target
// class and so it can access the private member...
if (!separateAttributesClass && currentClass.equals(targetClass)) {
sb.append("\n\n");
sb.append(generateAttributeForMember(targetClass, member));
membersEncountered.add(member.getName());
}
}
else if (Modifier.isProtected(modifiers)) {
// Generate attribute for this protected member, if the attribute will be pasted into the target
// class (and can access inherited protected member), or if the attribute will be generated
// into a separate attributes class in the same package as the class containing the protected
// member (which may be a superclass of the target class)...
if (!separateAttributesClass
|| member.getDeclaringClass().getPackage().getName().equals(packageOfAttributesClass)) {
sb.append("\n\n");
sb.append(generateAttributeForMember(targetClass, member));
membersEncountered.add(member.getName());
}
}
else if (Modifier.isPublic(modifiers)) {
sb.append("\n\n");
sb.append(generateAttributeForMember(targetClass, member));
membersEncountered.add(member.getName());
}
else {
// Package-private member.
// Generate attribute for this package-private member, if the attribute will be pasted into the target
// class and the member is in that class, or if the attribute will be generated
// into a separate attributes class in the same package as the class containing the package-private
// member (which may be a superclass of the target class)...
if ((!separateAttributesClass && currentClass.equals(targetClass))
|| member.getDeclaringClass().getPackage().getName().equals(packageOfAttributesClass)) {
sb.append("\n\n");
sb.append(generateAttributeForMember(targetClass, member));
membersEncountered.add(member.getName());
}
}
}
}
currentClass = currentClass.getSuperclass();
}
if (separateAttributesClass) {
sb.append("\n}\n");
}
return sb.toString();
}
static String generateAttributeForMember(Class<?> enclosingClass, Member member) {
try {
MemberType memberType = getMemberType(member);
if (getType(member).isPrimitive()) {
return generateSimpleAttribute(enclosingClass.getSimpleName(), PRIMITIVES_TO_WRAPPERS.get(getType(member)).getSimpleName(), member.getName(), memberType);
}
else if (Iterable.class.isAssignableFrom(getType(member))) {
ParameterizedType parameterizedType = getGenericType(member);
if (parameterizedType.getActualTypeArguments().length != 1) {
throw new UnsupportedOperationException();
}
Class<?> genericType = (Class<?>)parameterizedType.getActualTypeArguments()[0];
return generateMultiValueNullableAttributeForIterable(enclosingClass.getSimpleName(), genericType.getSimpleName(), member.getName(), memberType);
}
else if (getType(member).isArray()) {
if (getType(member).getComponentType().isPrimitive()) {
return generateMultiValueNullableAttributeForPrimitiveArray(enclosingClass.getSimpleName(), PRIMITIVES_TO_WRAPPERS.get(getType(member).getComponentType()).getSimpleName(), getType(member).getComponentType().getSimpleName(), member.getName(), memberType);
}
else {
return generateMultiValueNullableAttributeForObjectArray(enclosingClass.getSimpleName(), getType(member).getComponentType().getSimpleName(), member.getName(), memberType);
}
}
else {
return generateSimpleNullableAttribute(enclosingClass.getSimpleName(), getType(member).getSimpleName(), member.getName(), memberType);
}
}
catch (Exception e) {
return " // *** Note: Could not generate CQEngine attribute automatically for member: " + enclosingClass.getSimpleName() + "." + member.getName() + " ***";
}
}
static String generateSimpleAttribute(String objectType, String attributeType, String memberName, MemberType memberType) {
return " /**\n" +
" * CQEngine attribute for accessing " + memberType.description + " {@code " + objectType + "." + memberName + memberType.accessSuffix + "}.\n" +
" */\n" +
" public static final Attribute<" + objectType + ", " + attributeType + "> " + toUpperCaseWithUnderscores(memberName) + " = new SimpleAttribute<" + objectType + ", " + attributeType + ">(\"" + toUpperCaseWithUnderscores(memberName) + "\") {\n" +
" public " + attributeType + " getValue(" + objectType + " " + objectType.toLowerCase() + ", QueryOptions queryOptions) { return " + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + "; }\n" +
" };";
}
static String generateSimpleNullableAttribute(String objectType, String attributeType, String memberName, MemberType memberType) {
return " /**\n" +
" * CQEngine attribute for accessing " + memberType.description + " {@code " + objectType + "." + memberName + memberType.accessSuffix + "}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this " + memberType.description + " cannot " + memberType.produce + " null, replace this SimpleNullableAttribute with a SimpleAttribute\n" +
" public static final Attribute<" + objectType + ", " + attributeType + "> " + toUpperCaseWithUnderscores(memberName) + " = new SimpleNullableAttribute<" + objectType + ", " + attributeType + ">(\"" + toUpperCaseWithUnderscores(memberName) + "\") {\n" +
" public " + attributeType + " getValue(" + objectType + " " + objectType.toLowerCase() + ", QueryOptions queryOptions) { return " + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + "; }\n" +
" };";
}
static String generateMultiValueNullableAttributeForIterable(String objectType, String attributeType, String memberName, MemberType memberType) {
return " /**\n" +
" * CQEngine attribute for accessing " + memberType.description + " {@code " + objectType + "." + memberName + memberType.accessSuffix + "}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if the collection cannot contain null elements change true to false in the following constructor, or\n" +
" // - if the collection cannot contain null elements AND the " + memberType.description + " itself cannot " + memberType.produce + " null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<" + objectType + ", " + attributeType + "> " + toUpperCaseWithUnderscores(memberName) + " = new MultiValueNullableAttribute<" + objectType + ", " + attributeType + ">(\"" + toUpperCaseWithUnderscores(memberName) + "\", true) {\n" +
" public Iterable<" + attributeType + "> getNullableValues(" + objectType + " " + objectType.toLowerCase() + ", QueryOptions queryOptions) { return " + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + "; }\n" +
" };";
}
static String generateMultiValueNullableAttributeForObjectArray(String objectType, String attributeType, String memberName, MemberType memberType) {
return " /**\n" +
" * CQEngine attribute for accessing " + memberType.description + " {@code " + objectType + "." + memberName + memberType.accessSuffix + "}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if the array cannot contain null elements change true to false in the following constructor, or\n" +
" // - if the array cannot contain null elements AND the " + memberType.description + " itself cannot " + memberType.produce + " null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<" + objectType + ", " + attributeType + "> " + toUpperCaseWithUnderscores(memberName) + " = new MultiValueNullableAttribute<" + objectType + ", " + attributeType + ">(\"" + toUpperCaseWithUnderscores(memberName) + "\", true) {\n" +
" public Iterable<" + attributeType + "> getNullableValues(" + objectType + " " + objectType.toLowerCase() + ", QueryOptions queryOptions) { return Arrays.asList(" + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + "); }\n" +
" };";
}
static String generateMultiValueNullableAttributeForPrimitiveArray(String objectType, String attributeType, String primitiveType, String memberName, MemberType memberType) {
return " /**\n" +
" * CQEngine attribute for accessing " + memberType.description + " {@code " + objectType + "." + memberName + memberType.accessSuffix + "}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this " + memberType.description + " cannot " + memberType.produce + " null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<" + objectType + ", " + attributeType + "> " + toUpperCaseWithUnderscores(memberName) + " = new MultiValueNullableAttribute<" + objectType + ", " + attributeType + ">(\"" + toUpperCaseWithUnderscores(memberName) + "\", false) {\n" +
" public Iterable<" + attributeType + "> getNullableValues(final " + objectType + " " + objectType.toLowerCase() + ", QueryOptions queryOptions) {\n" +
" return new AbstractList<" + attributeType + ">() {\n" +
" public " + attributeType + " get(int i) { return " + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + "[i]; }\n" +
" public int size() { return " + objectType.toLowerCase() + "." + memberName + memberType.accessSuffix + ".length; }\n" +
" };\n" +
" }\n" +
" };";
}
enum MemberType {
FIELD("field", "", "be"),
METHOD("method", "()", "return");
public final String description;
public final String accessSuffix;
public final String produce;
MemberType(String description, String accessSuffix, String produce) {
this.description = description;
this.accessSuffix = accessSuffix;
this.produce = produce;
}
}
static String toUpperCaseWithUnderscores(String camelCase) {
String[] words = camelCase.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])");
StringBuilder sb = new StringBuilder();
for (Iterator<String> iterator = Arrays.asList(words).iterator(); iterator.hasNext(); ) {
String word = iterator.next();
sb.append(word.toUpperCase());
if (iterator.hasNext()) {
sb.append("_");
}
}
return sb.toString();
}
static List<Member> getMembers(Class currentClass) {
List<Member> declaredMembers = new ArrayList<Member>();
for (Field member : currentClass.getDeclaredFields()) {
if (!member.isSynthetic()) {
declaredMembers.add(member);
}
}
for (Method member : currentClass.getDeclaredMethods()) {
if (!member.isSynthetic()
&& !member.isBridge()
&& !member.getReturnType().equals(Void.TYPE)
&& member.getParameterTypes().length == 0) {
declaredMembers.add(member);
}
}
return declaredMembers;
}
static MemberType getMemberType(Member member) {
if (member instanceof Field) {
return MemberType.FIELD;
}
else if (member instanceof Method) {
return MemberType.METHOD;
}
else throw new IllegalStateException("Unsupported member type: " + member);
}
static Class<?> getType(Member member) {
if (member instanceof Field) {
return ((Field) member).getType();
}
else if (member instanceof Method) {
return ((Method) member).getReturnType();
}
else throw new IllegalStateException("Unsupported member type: " + member);
}
static ParameterizedType getGenericType(Member member) {
if (member instanceof Field) {
return (ParameterizedType)((Field) member).getGenericType();
}
else if (member instanceof Method) {
return (ParameterizedType)((Method) member).getGenericReturnType();
}
else throw new IllegalStateException("Unsupported member type: " + member);
}
static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new HashMap<Class<?>, Class<?>>(){{
put(boolean.class, Boolean.class);
put(byte.class, Byte.class);
put(short.class, Short.class);
put(char.class, Character.class);
put(int.class, Integer.class);
put(long.class, Long.class);
put(float.class, Float.class);
put(double.class, Double.class);
}};
/**
* Private constructor, not used.
*/
AttributeSourceGenerator() {
}
}
| 25,093 | 61.113861 | 283 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/codegen/support/GeneratedAttributeSupport.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.codegen.support;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.List;
/**
* Methods called by generated attributes to perform common type conversions.
* <p/>
* Attributes will uniformly call {@code GeneratedAttributeSupport.valueOf()}, and during compilation the compiler will
* take care of compiling the attribute to call the most specific {@code valueOf()} method for the type of the
* value read by the attribute automatically.
*
* @author Niall Gallagher
*/
public class GeneratedAttributeSupport {
// ====== Methods for converting primitive types to wrapper types... ======
public static Byte valueOf(byte value) { return value; }
public static Short valueOf(short value) { return value; }
public static Integer valueOf(int value) { return value; }
public static Long valueOf(long value) { return value; }
public static Float valueOf(float value) { return value; }
public static Double valueOf(double value) { return value; }
public static Boolean valueOf(boolean value) { return value; }
public static Character valueOf(char value) { return value; }
// ====== Methods for converting primitive arrays to Lists of wrapper types... ======
public static List<Byte> valueOf(byte[] value) { return wrapArray(value); }
public static List<Short> valueOf(short[] value) { return wrapArray(value); }
public static List<Integer> valueOf(int[] value) { return wrapArray(value); }
public static List<Long> valueOf(long[] value) { return wrapArray(value); }
public static List<Float> valueOf(float[] value) { return wrapArray(value); }
public static List<Double> valueOf(double[] value) { return wrapArray(value); }
public static List<Boolean> valueOf(boolean[] value) { return wrapArray(value); }
public static List<Character> valueOf(char[] value) { return wrapArray(value); }
// ====== Method for converting an object array to a List... ======
public static <T> List<T> valueOf(T[] value) { return wrapArray(value); }
// ====== A no-op method for preserving a List as-is... ======
public static <T> List<T> valueOf(List<T> value) { return value; }
// ====== A no-op method for preserving an object as-is... ======
public static <T> T valueOf(T value) { return value; }
/**
* Returns a modifiable List-based view of an array, which may be an object array or a primitive array.
* If a primitive array is supplied, the List implementation will take care of autoboxing automatically.
* <p/>
* This method does not copy the array: all operations read-through and write-through to the given array.
*
* @param array An array of any type (primitive or object)
* @param <T> The element type in the list returned (wrapper types in the case of primitive arrays)
* @return A modifiable List-based view of the array
*/
static <T> List<T> wrapArray(final Object array) {
return new AbstractList<T>() {
@Override
public T get(int index) {
@SuppressWarnings("unchecked")
T result = (T) Array.get(array, index);
return result;
}
@Override
public int size() {
return Array.getLength(array);
}
@Override
public T set(int index, T element) {
T existing = get(index);
Array.set(array, index, element);
return existing;
}
};
}
/**
* Private constructor, not used.
*/
GeneratedAttributeSupport() {
}
}
| 4,273 | 41.74 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/BigDecimalQuantizer.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.quantizer;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* A static factory for creating {@link Quantizer}s for {@link java.math.BigDecimal} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class BigDecimalQuantizer {
/**
* Private constructor, not used.
*/
BigDecimalQuantizer() {
}
static class TruncatingAndCompressingQuantizer implements Quantizer<BigDecimal> {
private final BigDecimal compressionFactor;
public TruncatingAndCompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = BigDecimal.valueOf(compressionFactor);
}
@Override
public BigDecimal getQuantizedValue(BigDecimal attributeValue) {
return attributeValue
.divideToIntegralValue(compressionFactor)
.multiply(compressionFactor)
.setScale(0, RoundingMode.DOWN);
}
}
static class TruncatingQuantizer implements Quantizer<BigDecimal> {
@Override
public BigDecimal getQuantizedValue(BigDecimal attributeValue) {
return attributeValue.setScale(0, RoundingMode.DOWN);
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0.0 -> 0</li>
* <li>Input value 4.2 -> 0</li>
* <li>Input value 5.0 -> 5</li>
* <li>Input value 9.9 -> 5</li>
* <li>Input value -0.0 -> 0</li>
* <li>Input value -4.2 -> 0</li>
* <li>Input value -5.0 -> -5</li>
* <li>Input value -9.9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers to coalesce to a single key. <b>Supply a
* factor < 2 to disable compression</b> and simply truncate everything after the decimal point
* @return A {@link Quantizer} which converts the input value to the closest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<BigDecimal> withCompressionFactor(int compressionFactor) {
return compressionFactor < 2 ? new TruncatingQuantizer() : new TruncatingAndCompressingQuantizer(compressionFactor);
}
}
| 3,253 | 35.561798 | 124 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/Quantizer.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.quantizer;
/**
* A Quantizer converts a fine-grained or <i>continuous</i> value to a <i>discrete</i> or coarse-grained value.
* <p/>
* This can be used to control the <i>granularity</i> of indexes: the tradeoff between storage space required by
* indexes, and the query processing time in looking up objects. It can also be used to convert <i>continuous</i>
* values to <i>discrete</i> values, given the inherent challenges in indexing continuous values.
* <p/>
* <b>Example uses:</b><br/>
* <ul>
* <li>
* Index adjacent integers to fewer coarse-grained keys with a <i>compression factor</i>.
* <p/>
* Store objects having integer attributes with adjacent integer values to the same key in indexes, to reduce
* the overall number of keys in the index.
* <p/>
* For example, objects with an integer "price" attribute: store objects with price 0-4 against the same key,
* objects with price 5-9 against the the next key etc., potentially reducing the number of keys
* in the index by a factor of five. The <u><i>compression factor</i></u> (5 in this example) can be varied.
* <p/>
* See: {@link IntegerQuantizer}, {@link LongQuantizer}, {@link BigIntegerQuantizer}
* </li>
* <li>
* Index attributes with <i>continuous</i> values, by quantizing to <i>discrete</i> values, and optionally
* apply compression.
* <p/>
* For example, objects with "price" stored with arbitrary precision ({@link Float}, {@link Double},
* {@link java.math.BigDecimal} etc.). If one object has price 5.00, and another has price 5.0000001,
* these objects would by default be stored against different keys, leading to an arbitrarily large number
* of keys for potentially small ranges in price.
* <p/>
* See: {@link FloatQuantizer}, {@link DoubleQuantizer}, {@link BigDecimalQuantizer}
* </li>
* </ul>
* When an index is configured with a {@link Quantizer} and added to a collection, the index will use the function
* implemented by the {@link Quantizer} to generate keys against which it will store objects in the index.
* <p/>
* Subsequently, when an index receives a query, it will use the same quantizer to determine from <i>sought</i> values
* in the query the relevant keys against which it can find matching objects in the index. Given that the set of objects
* stored against a <i>quantized key</i> will be larger than those actually sought in the query, the index will then
* filter objects in the retrieved set on-the-fly to those actually matching the query.
* <p/>
* As such quantization allows the size of indexes to be reduced but trades it for additional CPU overhead in filtering
* retrieved objects.
*
* @author Niall Gallagher
*/
public interface Quantizer<A> {
A getQuantizedValue(A attributeValue);
}
| 3,549 | 51.205882 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/IntegerQuantizer.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.quantizer;
/**
* A static factory for creating {@link Quantizer}s for {@link Integer} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class IntegerQuantizer {
static class CompressingQuantizer implements Quantizer<Integer> {
private final int compressionFactor;
public CompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = compressionFactor;
}
@Override
public Integer getQuantizedValue(Integer attributeValue) {
return (attributeValue / compressionFactor) * compressionFactor;
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0 -> 0</li>
* <li>Input value 4 -> 0</li>
* <li>Input value 5 -> 5</li>
* <li>Input value 9 -> 5</li>
* <li>Input value -4 -> 0</li>
* <li>Input value -5 -> -5</li>
* <li>Input value -9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers (>= 2) to coalesce to a single key
* @return A {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<Integer> withCompressionFactor(int compressionFactor) {
return new CompressingQuantizer(compressionFactor);
}
/**
* Private constructor, not used.
*/
IntegerQuantizer() {
}
}
| 2,513 | 33.438356 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/DoubleQuantizer.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.quantizer;
/**
* A static factory for creating {@link Quantizer}s for {@link Double} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class DoubleQuantizer {
/**
* Private constructor, not used.
*/
DoubleQuantizer() {
}
static class TruncatingAndCompressingQuantizer implements Quantizer<Double> {
private final int compressionFactor;
public TruncatingAndCompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = compressionFactor;
}
@Override
public Double getQuantizedValue(Double attributeValue) {
return (double) ((attributeValue.longValue() / compressionFactor) * compressionFactor);
}
}
static class TruncatingQuantizer implements Quantizer<Double> {
@Override
public Double getQuantizedValue(Double attributeValue) {
return (double) (long) attributeValue.doubleValue();
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0.0 -> 0</li>
* <li>Input value 4.2 -> 0</li>
* <li>Input value 5.0 -> 5</li>
* <li>Input value 9.9 -> 5</li>
* <li>Input value -0.0 -> 0</li>
* <li>Input value -4.2 -> 0</li>
* <li>Input value -5.0 -> -5</li>
* <li>Input value -9.9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers to coalesce to a single key. <b>Supply a
* factor < 2 to disable compression</b> and simply truncate everything after the decimal point
* @return A {@link Quantizer} which converts the input value to the closest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<Double> withCompressionFactor(int compressionFactor) {
return compressionFactor < 2 ? new TruncatingQuantizer() : new TruncatingAndCompressingQuantizer(compressionFactor);
}
}
| 3,015 | 35.780488 | 124 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/FloatQuantizer.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.quantizer;
/**
* A static factory for creating {@link Quantizer}s for {@link Float} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class FloatQuantizer {
/**
* Private constructor, not used.
*/
FloatQuantizer() {
}
static class TruncatingAndCompressingQuantizer implements Quantizer<Float> {
private final int compressionFactor;
public TruncatingAndCompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = compressionFactor;
}
@Override
public Float getQuantizedValue(Float attributeValue) {
return (float) ((attributeValue.longValue() / compressionFactor) * compressionFactor);
}
}
static class TruncatingQuantizer implements Quantizer<Float> {
@Override
public Float getQuantizedValue(Float attributeValue) {
return (float) (long) attributeValue.doubleValue();
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0.0 -> 0</li>
* <li>Input value 4.2 -> 0</li>
* <li>Input value 5.0 -> 5</li>
* <li>Input value 9.9 -> 5</li>
* <li>Input value -0.0 -> 0</li>
* <li>Input value -4.2 -> 0</li>
* <li>Input value -5.0 -> -5</li>
* <li>Input value -9.9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers to coalesce to a single key. <b>Supply a
* factor < 2 to disable compression</b> and simply truncate everything after the decimal point
* @return A {@link Quantizer} which converts the input value to the closest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<Float> withCompressionFactor(int compressionFactor) {
return compressionFactor < 2 ? new TruncatingQuantizer() : new TruncatingAndCompressingQuantizer(compressionFactor);
}
}
| 3,006 | 35.228916 | 124 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/BigIntegerQuantizer.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.quantizer;
import java.math.BigInteger;
/**
* A static factory for creating {@link Quantizer}s for {@link java.math.BigInteger} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class BigIntegerQuantizer {
/**
* Private constructor, not used.
*/
BigIntegerQuantizer() {
}
static class CompressingQuantizer implements Quantizer<BigInteger> {
private final BigInteger compressionFactor;
public CompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = BigInteger.valueOf(compressionFactor);
}
@Override
public BigInteger getQuantizedValue(BigInteger attributeValue) {
return attributeValue
.divide(compressionFactor)
.multiply(compressionFactor);
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0 -> 0</li>
* <li>Input value 4 -> 0</li>
* <li>Input value 5 -> 5</li>
* <li>Input value 9 -> 5</li>
* <li>Input value -4 -> 0</li>
* <li>Input value -5 -> -5</li>
* <li>Input value -9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers (>= 2) to coalesce to a single key
* @return A {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<BigInteger> withCompressionFactor(int compressionFactor) {
return new CompressingQuantizer(compressionFactor);
}
}
| 2,654 | 33.934211 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/quantizer/LongQuantizer.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.quantizer;
/**
* A static factory for creating {@link Quantizer}s for {@link Long} attributes.
* <p/>
* See {@link #withCompressionFactor(int)} for details.
*
* @author Niall Gallagher
*/
public class LongQuantizer {
static class CompressingQuantizer implements Quantizer<Long> {
private final int compressionFactor;
public CompressingQuantizer(int compressionFactor) {
if (compressionFactor < 2) {
throw new IllegalArgumentException("Invalid compression factor, must be >= 2: " + compressionFactor);
}
this.compressionFactor = compressionFactor;
}
@Override
public Long getQuantizedValue(Long attributeValue) {
return (attributeValue / compressionFactor) * compressionFactor;
}
}
/**
* Returns a {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero.
* <p/>
* <b>Examples (compression factor 5):</b><br/>
* <ul>
* <li>Input value 0 -> 0</li>
* <li>Input value 4 -> 0</li>
* <li>Input value 5 -> 5</li>
* <li>Input value 9 -> 5</li>
* <li>Input value -4 -> 0</li>
* <li>Input value -5 -> -5</li>
* <li>Input value -9 -> -5</li>
* </ul>
*
* @param compressionFactor The number of adjacent mathematical integers (>= 2) to coalesce to a single key
* @return A {@link Quantizer} which converts the input value to the nearest multiple of the compression
* factor, in the direction towards zero
*/
public static Quantizer<Long> withCompressionFactor(int compressionFactor) {
return new CompressingQuantizer(compressionFactor);
}
/**
* Private constructor, not used.
*/
LongQuantizer() {
}
}
| 2,493 | 33.164384 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/engine/QueryEngineInternal.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.engine;
/**
* @author Niall Gallagher
*/
public interface QueryEngineInternal<O> extends QueryEngine<O>, ModificationListener<O> {
/**
* Indicates if all indexes maintained by the query engine are mutable.
* Returns true in the edge case that there are no indexes.
*
* @return True if all indexes are mutable, false if any indexes are not mutable
*/
public boolean isMutable();
}
| 1,054 | 31.96875 | 89 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/engine/ModificationListener.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.engine;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* @author Niall Gallagher
*/
public interface ModificationListener<O> {
/**
* Notifies the listener that the specified objects are being added to the collection, and so it can take action
* and update its internal data structures.
* @param objectSet The objects being added
* @param queryOptions Optional parameters for the update
*/
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions);
/**
* Notifies the listener that the specified objects are being removed from the collection, and so it can take action
* and update its internal data structures.
* @param objectSet The objects being removed
* @param queryOptions Optional parameters for the update
*/
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions);
/**
* Notifies the listener that all objects have been removed from the collection, and so it can take action
* and update its internal data structures.
*
* @param queryOptions Optional parameters for the update
*/
public void clear(QueryOptions queryOptions);
/**
* Notifies the listener that the given ObjectStore has just been created.
*
* @param objectStore The ObjectStore which persists objects
* @param queryOptions Optional parameters for the update
*/
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions);
/**
* Notifies the listener that it has been removed from the collection, so that it can take action
* to delete internal data structures.
* @param queryOptions Optional parameters for the update
*/
public void destroy(QueryOptions queryOptions);
}
| 2,539 | 37.484848 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/engine/QueryEngine.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.engine;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* The main component of {@code CQEngine} - maintains a set of indexes on a collection and accepts queries which
* it performs and optimizes for those indexes.
*
* @author Niall Gallagher
*/
public interface QueryEngine<O> {
/**
* Retrieves a {@link ResultSet} which provides objects matching the given query, additionally accepting
* {@link QueryOptions} which can specify ordering of results, deduplication strategy etc.
*
* @param query A query representing some assertions which sought objects must match
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} which provides objects matching the given query
*/
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions);
/**
* Adds the given index to the collection.
* <p/>
* Subsequently queries passed to the {@link #retrieve(com.googlecode.cqengine.query.Query, QueryOptions)} method
* will use these indexes if suitable for the particular queries, to speed up retrievals.
* @param index The index to add
* @param queryOptions Optional parameters for the index
*/
public void addIndex(Index<O> index, QueryOptions queryOptions);
/**
* Removes the given index from the collection.
*
* @param index The index to remove
* @param queryOptions Optional parameters for the index
*/
public void removeIndex(Index<O> index, QueryOptions queryOptions);
/**
* Returns the set of indexes which were previously added to the collection via the
* {@link #addIndex(com.googlecode.cqengine.index.Index, QueryOptions)} method.
*
* @return The set of which were previously added to the collection via the
* {@link #addIndex(com.googlecode.cqengine.index.Index, QueryOptions)} method
*/
public Iterable<Index<O>> getIndexes();
}
| 2,724 | 39.073529 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/engine/CollectionQueryEngine.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.engine;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.IdentityAttributeIndex;
import com.googlecode.cqengine.index.sqlite.SQLiteIdentityIndex;
import com.googlecode.cqengine.index.sqlite.SimplifiedSQLiteIndex;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.index.compound.support.CompoundAttribute;
import com.googlecode.cqengine.index.compound.support.CompoundQuery;
import com.googlecode.cqengine.index.fallback.FallbackIndex;
import com.googlecode.cqengine.index.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.index.unique.UniqueIndex;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStoreResultSet;
import com.googlecode.cqengine.persistence.support.sqlite.SQLiteObjectStore;
import com.googlecode.cqengine.query.ComparativeQuery;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.LogicalQuery;
import com.googlecode.cqengine.query.logical.Not;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.query.option.*;
import com.googlecode.cqengine.query.simple.*;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.closeable.CloseableResultSet;
import com.googlecode.cqengine.resultset.common.CostCachingResultSet;
import com.googlecode.cqengine.resultset.connective.ResultSetDifference;
import com.googlecode.cqengine.resultset.connective.ResultSetIntersection;
import com.googlecode.cqengine.resultset.connective.ResultSetUnion;
import com.googlecode.cqengine.resultset.connective.ResultSetUnionAll;
import com.googlecode.cqengine.resultset.filter.MaterializedDeduplicatedIterator;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import com.googlecode.cqengine.resultset.filter.FilteringResultSet;
import com.googlecode.cqengine.resultset.iterator.ConcatenatingIterable;
import com.googlecode.cqengine.resultset.iterator.ConcatenatingIterator;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import com.googlecode.cqengine.resultset.order.AttributeOrdersComparator;
import com.googlecode.cqengine.resultset.order.MaterializedDeduplicatedResultSet;
import com.googlecode.cqengine.resultset.order.MaterializedOrderedResultSet;
import com.googlecode.cqengine.index.support.CloseableRequestResources.CloseableResourceGroup;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.option.EngineFlags.INDEX_ORDERING_ALLOW_FAST_ORDERING_OF_MULTI_VALUED_ATTRIBUTES;
import static com.googlecode.cqengine.query.option.EngineFlags.PREFER_INDEX_MERGE_STRATEGY;
import static com.googlecode.cqengine.query.option.FlagsEnabled.isFlagEnabled;
import static com.googlecode.cqengine.resultset.iterator.IteratorUtil.concatenate;
import static com.googlecode.cqengine.resultset.iterator.IteratorUtil.groupAndSort;
/**
* The main component of {@code CQEngine} - maintains a set of indexes on a collection and accepts queries which
* it performs and optimizes for those indexes.
*
* @author Niall Gallagher
*/
public class CollectionQueryEngine<O> implements QueryEngineInternal<O> {
// A key used to store the root query in the QueryOptions, so it may be accessed by partial indexes...
public static final String ROOT_QUERY = "ROOT_QUERY";
private volatile Persistence<O, ? extends Comparable> persistence;
private volatile ObjectStore<O> objectStore;
// Map of attributes to set of indexes on that attribute...
private final ConcurrentMap<Attribute<O, ?>, Set<Index<O>>> attributeIndexes = new ConcurrentHashMap<Attribute<O, ?>, Set<Index<O>>>();
private final ConcurrentMap<Attribute<O, ?>, Index<O>> uniqueIndexes = new ConcurrentHashMap<Attribute<O, ?>, Index<O>>();
// Map of CompoundAttributes to compound index on that compound attribute...
private final ConcurrentMap<CompoundAttribute<O>, CompoundIndex<O>> compoundIndexes = new ConcurrentHashMap<CompoundAttribute<O>, CompoundIndex<O>>();
// Map of queries to standing query index on that query...
private final ConcurrentMap<Query<O>, Index<O>> standingQueryIndexes = new ConcurrentHashMap<Query<O>, Index<O>>();
// Fallback index (handles queries which other indexes don't support)...
private final FallbackIndex<O> fallbackIndex = new FallbackIndex<O>();
// Updated as indexes are added or removed, this is used by the isMutable() method...
private final Set<Index<O>> immutableIndexes = Collections.newSetFromMap(new ConcurrentHashMap<>());
public CollectionQueryEngine() {
}
@Override
public void init(final ObjectStore<O> objectStore, final QueryOptions queryOptions) {
this.objectStore = objectStore;
@SuppressWarnings("unchecked")
Persistence<O, ? extends Comparable> persistenceFromQueryOptions = getPersistenceFromQueryOptions(queryOptions);
this.persistence = persistenceFromQueryOptions;
if (objectStore instanceof SQLiteObjectStore) {
// If the collection is backed by a SQLiteObjectStore, add the backing index of the SQLiteObjectStore
// so that it can also be used as a regular index to accelerate queries...
SQLiteObjectStore<O, ? extends Comparable<?>> sqLiteObjectStore = (SQLiteObjectStore<O, ? extends Comparable<?>>)objectStore;
SQLiteIdentityIndex<? extends Comparable<?>, O> backingIndex = sqLiteObjectStore.getBackingIndex();
addIndex(backingIndex, queryOptions);
}
forEachIndexDo(new IndexOperation<O>() {
@Override
public boolean perform(Index<O> index) {
queryOptions.put(QueryEngine.class, this);
queryOptions.put(Persistence.class, persistence);
index.init(objectStore, queryOptions);
return true;
}
});
}
/**
* This is a no-op here, as currently the {@link ModificationListener#destroy(QueryOptions)} method
* is only used by indexes.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
// -------------------- Methods for adding indexes --------------------
/**
* {@inheritDoc}
*/
@Override
public void addIndex(Index<O> index, QueryOptions queryOptions) {
if (index instanceof StandingQueryIndex) {
@SuppressWarnings({"unchecked"})
StandingQueryIndex<O> standingQueryIndex = (StandingQueryIndex<O>) index;
addStandingQueryIndex(standingQueryIndex, standingQueryIndex.getStandingQuery(), queryOptions);
}
else if (index instanceof CompoundIndex) {
@SuppressWarnings({"unchecked"})
CompoundIndex<O> compoundIndex = (CompoundIndex<O>) index;
CompoundAttribute<O> compoundAttribute = compoundIndex.getAttribute();
addCompoundIndex(compoundIndex, compoundAttribute, queryOptions);
}
else if (index instanceof AttributeIndex) {
@SuppressWarnings({"unchecked"})
AttributeIndex<?, O> attributeIndex = (AttributeIndex<?, O>) index;
Attribute<O, ?> indexedAttribute = attributeIndex.getAttribute();
if (indexedAttribute instanceof StandingQueryAttribute) {
@SuppressWarnings("unchecked")
StandingQueryAttribute<O> standingQueryAttribute = (StandingQueryAttribute<O>) indexedAttribute;
Query<O> standingQuery = standingQueryAttribute.getQuery();
addStandingQueryIndex(index, standingQuery, queryOptions);
}
else {
addAttributeIndex(attributeIndex, queryOptions);
}
}
else {
throw new IllegalStateException("Unexpected type of index: " + (index == null ? null : index.getClass().getName()));
}
if (!index.isMutable()) {
immutableIndexes.add(index);
}
}
/**
* Adds an {@link AttributeIndex}.
* @param attributeIndex The index to add
* @param <A> The type of objects indexed
*/
<A> void addAttributeIndex(AttributeIndex<A, O> attributeIndex, QueryOptions queryOptions) {
Attribute<O, A> attribute = attributeIndex.getAttribute();
Set<Index<O>> indexesOnThisAttribute = attributeIndexes.get(attribute);
if (indexesOnThisAttribute == null) {
indexesOnThisAttribute = Collections.newSetFromMap(new ConcurrentHashMap<Index<O>, Boolean>());
attributeIndexes.put(attribute, indexesOnThisAttribute);
}
if (attributeIndex instanceof SimplifiedSQLiteIndex) {
// Ensure there is not already an identity index added for this attribute...
for (Index<O> existingIndex : indexesOnThisAttribute) {
if (existingIndex instanceof IdentityAttributeIndex) {
throw new IllegalStateException("An index has already been added on the primary key attribute used for persistence, and no additional non-heap indexes are allowed on that attribute: " + attribute);
}
}
}
// Add the index...
if (!indexesOnThisAttribute.add(attributeIndex)) {
throw new IllegalStateException("An equivalent index has already been added for attribute: " + attribute);
}
if (attributeIndex instanceof UniqueIndex) {
// We put UniqueIndexes in a separate map too, to access directly...
uniqueIndexes.put(attribute, attributeIndex);
}
queryOptions.put(QueryEngine.class, this);
queryOptions.put(Persistence.class, persistence);
attributeIndex.init(objectStore, queryOptions);
}
/**
* Adds either a {@link StandingQueryIndex} or a regular index build on a {@link StandingQueryAttribute}.
* @param standingQueryIndex The index to add
* @param standingQuery The query on which the index is based
*/
void addStandingQueryIndex(Index<O> standingQueryIndex, Query<O> standingQuery, QueryOptions queryOptions) {
Index<O> existingIndex = standingQueryIndexes.putIfAbsent(standingQuery, standingQueryIndex);
if (existingIndex != null) {
throw new IllegalStateException("An index has already been added for standing query: " + standingQuery);
}
queryOptions.put(QueryEngine.class, this);
queryOptions.put(Persistence.class, persistence);
standingQueryIndex.init(objectStore, queryOptions);
}
/**
* Adds a {@link CompoundIndex}.
* @param compoundIndex The index to add
* @param compoundAttribute The compound attribute on which the index is based
*/
void addCompoundIndex(CompoundIndex<O> compoundIndex, CompoundAttribute<O> compoundAttribute, QueryOptions queryOptions) {
CompoundIndex<O> existingIndex = compoundIndexes.putIfAbsent(compoundAttribute, compoundIndex);
if (existingIndex != null) {
throw new IllegalStateException("An index has already been added for compound attribute: " + compoundAttribute);
}
queryOptions.put(QueryEngine.class, this);
queryOptions.put(Persistence.class, persistence);
compoundIndex.init(objectStore, queryOptions);
}
// -------------------- Methods for removing indexes --------------------
/**
* {@inheritDoc}
*/
@Override
public void removeIndex(Index<O> index, QueryOptions queryOptions) {
boolean removed;
if (index instanceof StandingQueryIndex) {
@SuppressWarnings({"unchecked"})
StandingQueryIndex<O> standingQueryIndex = (StandingQueryIndex<O>) index;
removed = standingQueryIndexes.remove(standingQueryIndex.getStandingQuery(), standingQueryIndex);
}
else if (index instanceof CompoundIndex) {
@SuppressWarnings({"unchecked"})
CompoundIndex<O> compoundIndex = (CompoundIndex<O>) index;
CompoundAttribute<O> compoundAttribute = compoundIndex.getAttribute();
removed = compoundIndexes.remove(compoundAttribute, compoundIndex);
}
else if (index instanceof AttributeIndex) {
@SuppressWarnings({"unchecked"})
AttributeIndex<?, O> attributeIndex = (AttributeIndex<?, O>) index;
Attribute<O, ?> indexedAttribute = attributeIndex.getAttribute();
if (indexedAttribute instanceof StandingQueryAttribute) {
@SuppressWarnings("unchecked")
StandingQueryAttribute<O> standingQueryAttribute = (StandingQueryAttribute<O>) indexedAttribute;
Query<O> standingQuery = standingQueryAttribute.getQuery();
removed = standingQueryIndexes.remove(standingQuery, index);
}
else {
Set<Index<O>> indexesOnThisAttribute = attributeIndexes.get(indexedAttribute);
removed = indexesOnThisAttribute.remove(attributeIndex);
if (attributeIndex instanceof UniqueIndex) {
// Remove from UniqueIndexes as well...
removed = uniqueIndexes.remove(indexedAttribute, attributeIndex) || removed;
}
if (indexesOnThisAttribute.isEmpty()) {
// If there are no more indexes left on this attribute,
// remove the Set which was used to store indexes on the attribute also...
attributeIndexes.remove(indexedAttribute);
}
}
}
else {
throw new IllegalStateException("Unexpected type of index: " + (index == null ? null : index.getClass().getName()));
}
if (removed && !index.isMutable()) {
// Remove from the set of immutable indexes; this is used by ensureMutable() and the isMutable() method...
immutableIndexes.remove(index);
}
// Notify the index that it has been removed, so that it can delete underlying storage used if necessary...
index.destroy(queryOptions);
}
// -------------------- Method for accessing indexes --------------------
/**
* {@inheritDoc}
*/
@Override
public Iterable<Index<O>> getIndexes() {
List<Index<O>> indexes = new ArrayList<Index<O>>();
for (Set<Index<O>> attributeIndexes : this.attributeIndexes.values()) {
indexes.addAll(attributeIndexes);
}
indexes.addAll(this.compoundIndexes.values());
indexes.addAll(this.standingQueryIndexes.values());
return indexes;
}
/**
* Returns an {@link Iterable} over all indexes which have been added on the given attribute, including the
* {@link FallbackIndex} which is implicitly available on all attributes.
*
* @param attribute The relevant attribute
* @return All indexes which have been added on the given attribute, including the {@link FallbackIndex}
*/
Iterable<Index<O>> getIndexesOnAttribute(Attribute<O, ?> attribute) {
final Set<Index<O>> indexesOnAttribute = attributeIndexes.get(attribute);
if (indexesOnAttribute == null || indexesOnAttribute.isEmpty()) {
// If no index is registered for this attribute, return the fallback index...
return Collections.<Index<O>>singleton(this.fallbackIndex);
}
// Return an Iterable over the registered indexes and the fallback index...
List<Iterable<Index<O>>> iterables = new ArrayList<Iterable<Index<O>>>(2);
iterables.add(indexesOnAttribute);
iterables.add(Collections.<Index<O>>singleton(fallbackIndex));
return new ConcatenatingIterable<Index<O>>(iterables);
}
/**
* Returns the entire collection wrapped as a {@link ResultSet}, with retrieval cost {@link Integer#MAX_VALUE}.
* <p/>
* Merge cost is the size of the collection.
*
* @return The entire collection wrapped as a {@link ResultSet}, with retrieval cost {@link Integer#MAX_VALUE}
*/
ResultSet<O> getEntireCollectionAsResultSet(final Query<O> query, final QueryOptions queryOptions) {
return new ObjectStoreResultSet<O>(objectStore, query, queryOptions, Integer.MAX_VALUE) {
// Override getMergeCost() to avoid calling size(),
// which may be expensive for custom implementations of lazy backing sets...
@Override
public int getMergeCost() {
return Integer.MAX_VALUE;
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* Returns a {@link ResultSet} from the index with the lowest retrieval cost which supports the given query.
* <p/>
* For a definition of retrieval cost see {@link ResultSet#getRetrievalCost()}.
*
* @param query The query which refers to an attribute
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} from the index with the lowest retrieval cost which supports the given query
*/
<A> ResultSet<O> retrieveSimpleQuery(SimpleQuery<O, A> query, QueryOptions queryOptions) {
// First, check if a standing query index is available for the query...
ResultSet<O> lowestCostResultSet = retrieveFromStandingQueryIndexIfAvailable(query, queryOptions);
if (lowestCostResultSet != null) {
// A standing query index is available for this query.
// Results from standing query indexes are considered to have the lowest cost, so we simply return these results...
return lowestCostResultSet;
}
// At this point, no standing query indexes were available,
// so we proceed to check for other indexes on the attribute...
// Check if a UniqueIndex is available, as this will have the lowest cost of attribute-based indexes...
Index<O> uniqueIndex = uniqueIndexes.get(query.getAttribute());
if (uniqueIndex!= null && uniqueIndex.supportsQuery(query, queryOptions)){
return uniqueIndex.retrieve(query, queryOptions);
}
// At this point, we did not find any UniqueIndex, so we now check for other attribute-based indexes
// and we determine which one has the lowest retrieval cost...
int lowestRetrievalCost = 0;
// Examine other (non-unique) indexes...
Iterable<Index<O>> indexesOnAttribute = getIndexesOnAttribute(query.getAttribute());
// Choose the index with the lowest retrieval cost for this query...
for (Index<O> index : indexesOnAttribute) {
if (index.supportsQuery(query, queryOptions)) {
ResultSet<O> thisIndexResultSet = index.retrieve(query, queryOptions);
int thisIndexRetrievalCost = thisIndexResultSet.getRetrievalCost();
if (lowestCostResultSet == null || thisIndexRetrievalCost < lowestRetrievalCost) {
lowestCostResultSet = thisIndexResultSet;
lowestRetrievalCost = thisIndexRetrievalCost;
}
}
}
if (lowestCostResultSet == null) {
// This should never happen (would indicate a bug);
// the fallback index should have been selected in worst case...
throw new IllegalStateException("Failed to locate an index supporting query: " + query);
}
return new CostCachingResultSet<O>(lowestCostResultSet);
}
/**
* Returns a {@link ResultSet} from the index with the lowest retrieval cost which supports the given query.
* <p/>
* For a definition of retrieval cost see {@link ResultSet#getRetrievalCost()}.
*
* @param query The query which refers to an attribute
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} from the index with the lowest retrieval cost which supports the given query
*/
<A> ResultSet<O> retrieveComparativeQuery(ComparativeQuery<O, A> query, QueryOptions queryOptions) {
// Determine which of the indexes on the query's attribute have the lowest retrieval cost...
int lowestRetrievalCost = 0;
ResultSet<O> lowestCostResultSet = null;
Iterable<Index<O>> indexesOnAttribute = getIndexesOnAttribute(query.getAttribute());
// Choose the index with the lowest retrieval cost for this query...
for (Index<O> index : indexesOnAttribute) {
if (index.supportsQuery(query, queryOptions)) {
ResultSet<O> thisIndexResultSet = index.retrieve(query, queryOptions);
int thisIndexRetrievalCost = thisIndexResultSet.getRetrievalCost();
if (lowestCostResultSet == null || thisIndexRetrievalCost < lowestRetrievalCost) {
lowestCostResultSet = thisIndexResultSet;
lowestRetrievalCost = thisIndexRetrievalCost;
}
}
}
if (lowestCostResultSet == null) {
// This should never happen (would indicate a bug);
// the fallback index should have been selected in worst case...
throw new IllegalStateException("Failed to locate an index supporting query: " + query);
}
return new CostCachingResultSet<O>(lowestCostResultSet);
}
// -------------------- Methods for query processing --------------------
/**
* {@inheritDoc}
*/
// Implementation note: this methods actually just pre-processes QueryOption arguments and then delegates
// to the #retrieveRecursive() method.
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
OrderByOption<O> orderByOption = (OrderByOption<O>) queryOptions.get(OrderByOption.class);
// Store the root query in the queryOptions, so that when retrieveRecursive() examines child branches, that
// both the branch query and the root query will be available to PartialIndexes so they may determine if they
// can be used to accelerate the overall query...
queryOptions.put(ROOT_QUERY, query);
// Log decisions made to the query log, if provided...
final QueryLog queryLog = queryOptions.get(QueryLog.class); // might be null
SortedKeyStatisticsAttributeIndex<?, O> indexForOrdering = null;
if (orderByOption != null) {
// Results must be ordered. Determine the ordering strategy to use: i.e. if we should use an index to order
// results, or if we should retrieve results and sort them afterwards instead.
Double selectivityThreshold = Thresholds.getThreshold(queryOptions, EngineThresholds.INDEX_ORDERING_SELECTIVITY);
if (selectivityThreshold == null) {
selectivityThreshold = EngineThresholds.INDEX_ORDERING_SELECTIVITY.getThresholdDefault();
}
final List<AttributeOrder<O>> allSortOrders = orderByOption.getAttributeOrders();
if (selectivityThreshold != 0.0) {
// Index ordering can be used.
// Check if an index is actually available to support it...
AttributeOrder<O> firstOrder = allSortOrders.iterator().next();
@SuppressWarnings("unchecked")
Attribute<O, Comparable> firstAttribute = (Attribute<O, Comparable>)firstOrder.getAttribute();
if (firstAttribute instanceof OrderControlAttribute) {
@SuppressWarnings("unchecked")
Attribute<O, Comparable> firstAttributeDelegate = ((OrderControlAttribute)firstAttribute).getDelegateAttribute();
firstAttribute = firstAttributeDelegate;
}
// Before we check if an index is available to support index ordering, we need to account for the fact
// that even if such an index is available, it might not contain all objects in the collection.
//
// An index built on a SimpleAttribute, is guaranteed to contain all objects in the collection, because
// SimpleAttribute is guaranteed to return a value for every object.
// OTOH an index built on a non-SimpleAttribute, is not guaranteed to contain all objects in the
// collection, because non-SimpleAttributes are permitted to return *zero* or more values for any
// object. Objects for which non-SimpleAttributes return zero values, will be omitted from the index.
//
// Therefore, if we will use an index to order results, we must ensure that the collection also has a
// suitable index to allow the objects which are not in the index to be retrieved as well. When
// ordering results, we must return those objects either before or after the objects which are found in
// the index. Here we proceed to locate a suitable index to use for ordering results, only if we will
// also be able to retrieve the objects missing from that index efficiently as well...
if (firstAttribute instanceof SimpleAttribute || standingQueryIndexes.get(not(has(firstAttribute))) != null) {
// Either we are sorting by a SimpleAttribute, or we are sorting by a non-SimpleAttribute and we
// also will be able to retrieve objects which do not have values for the non-SimpleAttribute
// efficiently. Now check if an index exists which would allow index ordering...
for (Index<O> index : this.getIndexesOnAttribute(firstAttribute)) {
if (index instanceof SortedKeyStatisticsAttributeIndex && !index.isQuantized()) {
indexForOrdering = (SortedKeyStatisticsAttributeIndex<?, O>)index;
break;
}
}
}
if (queryLog != null) {
queryLog.log("indexForOrdering: " + (indexForOrdering == null ? null : indexForOrdering.getClass().getSimpleName()));
}
// At this point we might have found an appropriate indexForOrdering, or it might still be null.
if (indexForOrdering != null) {
// We found an appropriate index.
// Determine if the selectivity of the query is below the selectivity threshold to use index ordering...
final double querySelectivity;
if (selectivityThreshold == 1.0) {
// Index ordering has been requested explicitly.
// Don't bother calculating query selectivity, assign low selectivity so we will use the index...
querySelectivity = 0.0;
}
else if (!indexForOrdering.supportsQuery(has(firstAttribute), queryOptions)) {
// Index ordering was not requested explicitly, and we cannot calculate the selectivity.
// In this case even though we have an index which supports index ordering,
// we don't have enough information to say that it would be beneficial.
// Assign high selectivity so that the materialize strategy will be used instead...
querySelectivity = 1.0;
}
else {
// The index supports has() queries, which allows us to calculate selectivity.
// Calculate query selectivity, based on the query cardinality and index cardinality...
final int queryCardinality = retrieveRecursive(query, queryOptions).getMergeCost();
final int indexCardinality = indexForOrdering.retrieve(has(firstAttribute), queryOptions).getMergeCost();
if (queryLog != null) {
queryLog.log("queryCardinality: " + queryCardinality);
queryLog.log("indexCardinality: " + indexCardinality);
}
if (indexCardinality == 0) {
// Handle edge case where the index is empty.
querySelectivity = 1.0; // treat is as if the query has high selectivity (tend to use materialize).
}
else if (queryCardinality > indexCardinality) {
// Handle edge case where query cardinality is greater than index cardinality.
querySelectivity = 0.0; // treat is as if the query has low selectivity (tend to use index ordering).
}
else {
querySelectivity = 1.0 - queryCardinality / (double)indexCardinality;
}
}
if (queryLog != null) {
queryLog.log("querySelectivity: " + querySelectivity);
queryLog.log("selectivityThreshold: " + selectivityThreshold);
}
if (querySelectivity > selectivityThreshold) {
// Selectivity is too high for index ordering strategy.
// Use the materialize ordering strategy instead.
indexForOrdering = null;
}
// else: querySelectivity <= selectivityThreshold, so we use the index ordering strategy.
}
}
}
ResultSet<O> resultSet;
if (indexForOrdering != null) {
// Retrieve results, using an index to accelerate ordering...
resultSet = retrieveWithIndexOrdering(query, queryOptions, orderByOption, indexForOrdering);
if (queryLog != null) {
queryLog.log("orderingStrategy: index");
}
}
else {
// Retrieve results, without using an index to accelerate ordering...
resultSet = retrieveWithoutIndexOrdering(query, queryOptions, orderByOption);
if (queryLog != null) {
queryLog.log("orderingStrategy: materialize");
}
}
// Return the results, ensuring that the close() method will close any resources which were opened...
// TODO: possibly not necessary to wrap here, as the IndexedCollections also ensure close() is called...
return new CloseableResultSet<O>(resultSet, query, queryOptions) {
@Override
public void close() {
super.close();
CloseableRequestResources.closeForQueryOptions(queryOptions);
}
};
}
/**
* Retrieve results and then sort them afterwards (if sorting is required).
*/
ResultSet<O> retrieveWithoutIndexOrdering(Query<O> query, QueryOptions queryOptions, OrderByOption<O> orderByOption) {
ResultSet<O> resultSet;
resultSet = retrieveRecursive(query, queryOptions);
// Check if we need to order results...
if (orderByOption != null) {
// Wrap the results in an MaterializedOrderedResultSet.
Comparator<O> comparator = new AttributeOrdersComparator<O>(orderByOption.getAttributeOrders(), queryOptions);
resultSet = new MaterializedOrderedResultSet<O>(resultSet, comparator);
}
// Check if we need to deduplicate results (deduplicate using MATERIALIZE rather than LOGICAL_ELIMINATION strategy)...
if (DeduplicationOption.isMaterialize(queryOptions)) {
// Wrap the results in an MaterializedDeduplicatedResultSet.
resultSet = new MaterializedDeduplicatedResultSet<O>(resultSet);
}
return resultSet;
}
/**
* Use an index to order results.
*/
ResultSet<O> retrieveWithIndexOrdering(final Query<O> query, final QueryOptions queryOptions, final OrderByOption<O> orderByOption, final SortedKeyStatisticsIndex<?, O> indexForOrdering) {
final List<AttributeOrder<O>> allSortOrders = orderByOption.getAttributeOrders();
final AttributeOrder<O> primarySortOrder = allSortOrders.get(0);
// If the client wrapped the first attribute by which results should be ordered in an OrderControlAttribute,
// assign it here...
@SuppressWarnings("unchecked")
final OrderControlAttribute<O> orderControlAttribute =
(primarySortOrder.getAttribute() instanceof OrderControlAttribute)
? (OrderControlAttribute<O>)primarySortOrder.getAttribute() : null;
// If the first attribute by which results should be ordered was wrapped, unwrap it, and assign it here...
@SuppressWarnings("unchecked")
final Attribute<O, Comparable> primarySortAttribute =
(orderControlAttribute == null)
? (Attribute<O, Comparable>) primarySortOrder.getAttribute()
: (Attribute<O, Comparable>) orderControlAttribute.getDelegateAttribute();
final boolean primarySortDescending = primarySortOrder.isDescending();
final boolean attributeCanHaveZeroValues = !(primarySortAttribute instanceof SimpleAttribute);
final boolean attributeCanHaveMoreThanOneValue = !(primarySortAttribute instanceof SimpleAttribute || primarySortAttribute instanceof SimpleNullableAttribute);
@SuppressWarnings("unchecked")
final RangeBounds<?> rangeBoundsFromQuery = getBoundsFromQuery(query, primarySortAttribute);
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterator<O> mainResults = retrieveWithIndexOrderingMainResults(query, queryOptions, indexForOrdering, allSortOrders, rangeBoundsFromQuery, attributeCanHaveMoreThanOneValue, primarySortDescending);
// Combine the results from the index ordered search, with objects which would be missing from that
// index, which is possible in the case that the primary sort attribute is nullable or multi-valued...
Iterator<O> combinedResults;
if (attributeCanHaveZeroValues) {
Iterator<O> missingResults = retrieveWithIndexOrderingMissingResults(query, queryOptions, primarySortAttribute, allSortOrders, attributeCanHaveMoreThanOneValue);
// Concatenate the main results and the missing objects, accounting for which batch should come first...
if (orderControlAttribute instanceof OrderMissingFirstAttribute) {
combinedResults = ConcatenatingIterator.concatenate(Arrays.asList(missingResults, mainResults));
}
else if (orderControlAttribute instanceof OrderMissingLastAttribute) {
combinedResults = ConcatenatingIterator.concatenate(Arrays.asList(mainResults, missingResults));
}
else if (primarySortOrder.isDescending()) {
combinedResults = ConcatenatingIterator.concatenate(Arrays.asList(mainResults, missingResults));
}
else {
combinedResults = ConcatenatingIterator.concatenate(Arrays.asList(missingResults, mainResults));
}
}
else {
combinedResults = mainResults;
}
if (attributeCanHaveMoreThanOneValue) {
// Deduplicate results in case the same object could appear in more than one bucket
// and so otherwise could be returned more than once...
combinedResults = new MaterializedDeduplicatedIterator<O>(combinedResults);
}
return combinedResults;
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = retrieveWithoutIndexOrdering(query, queryOptions, null);
try {
return rs.contains(object);
}
finally {
rs.close();
}
}
@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() {
ResultSet<O> rs = retrieveWithoutIndexOrdering(query, queryOptions, null);
try {
return rs.getRetrievalCost();
}
finally {
rs.close();
}
}
@Override
public int getMergeCost() {
ResultSet<O> rs = retrieveWithoutIndexOrdering(query, queryOptions, null);
try {
return rs.getMergeCost();
}
finally {
rs.close();
}
}
@Override
public int size() {
ResultSet<O> rs = retrieveWithoutIndexOrdering(query, queryOptions, null);
try {
return rs.size();
}
finally {
rs.close();
}
}
@Override
public void close() {
}
};
}
Iterator<O> retrieveWithIndexOrderingMainResults(final Query<O> query, QueryOptions queryOptions, SortedKeyStatisticsIndex<?, O> indexForOrdering, List<AttributeOrder<O>> allSortOrders, RangeBounds<?> rangeBoundsFromQuery, boolean attributeCanHaveMoreThanOneValue, boolean primarySortDescending) {
// Ensure that at the end of processing the request, that we close any resources we opened...
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
final List<AttributeOrder<O>> sortOrdersForBucket = determineAdditionalSortOrdersForIndexOrdering(allSortOrders, attributeCanHaveMoreThanOneValue, indexForOrdering, queryOptions);
final CloseableIterator<? extends KeyValue<? extends Comparable<?>, O>> keysAndValuesInRange = getKeysAndValuesInRange(indexForOrdering, rangeBoundsFromQuery, primarySortDescending, queryOptions);
// Ensure this CloseableIterator gets closed...
closeableResourceGroup.add(keysAndValuesInRange);
final Iterator<O> sorted;
if (sortOrdersForBucket.isEmpty()) {
sorted = new LazyIterator<O>() {
@Override
protected O computeNext() {
return keysAndValuesInRange.hasNext() ? keysAndValuesInRange.next().getValue() : endOfData();
}
};
}
else {
sorted = concatenate(groupAndSort(keysAndValuesInRange, new AttributeOrdersComparator<O>(sortOrdersForBucket, queryOptions)));
}
return filterIndexOrderingCandidateResults(sorted, query, queryOptions);
}
Iterator<O> retrieveWithIndexOrderingMissingResults(final Query<O> query, QueryOptions queryOptions, Attribute<O, Comparable> primarySortAttribute, List<AttributeOrder<O>> allSortOrders, boolean attributeCanHaveMoreThanOneValue) {
// Ensure that at the end of processing the request, that we close any resources we opened...
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
// Retrieve missing objects from the secondary index on objects which don't have a value for the primary sort attribute...
Not<O> missingValuesQuery = not(has(primarySortAttribute));
ResultSet<O> missingResults = retrieveRecursive(missingValuesQuery, queryOptions);
// Ensure that this is closed...
closeableResourceGroup.add(missingResults);
Iterator<O> missingResultsIterator = missingResults.iterator();
// Filter the objects from the secondary index, to ensure they match the query...
missingResultsIterator = filterIndexOrderingCandidateResults(missingResultsIterator, query, queryOptions);
// Determine if we need to sort the missing objects...
Index<O> indexForMissingObjects = standingQueryIndexes.get(missingValuesQuery);
final List<AttributeOrder<O>> sortOrdersForBucket = determineAdditionalSortOrdersForIndexOrdering(allSortOrders, attributeCanHaveMoreThanOneValue, indexForMissingObjects, queryOptions);
if (!sortOrdersForBucket.isEmpty()) {
// We do need to sort the missing objects...
Comparator<O> comparator = new AttributeOrdersComparator<O>(sortOrdersForBucket, queryOptions);
missingResultsIterator = IteratorUtil.materializedSort(missingResultsIterator, comparator);
}
return missingResultsIterator;
}
/**
* Filters the given sorted candidate results to ensure they match the query, using either the default merge
* strategy or the index merge strategy as appropriate.
* <p/>
* This method will add any resources which need to be closed to {@link CloseableRequestResources} in the query options.
*
* @param sortedCandidateResults The candidate results to be filtered
* @param query The query
* @param queryOptions The query options
* @return A filtered iterator which returns the subset of candidate objects which match the query
*/
Iterator<O> filterIndexOrderingCandidateResults(final Iterator<O> sortedCandidateResults, final Query<O> query, final QueryOptions queryOptions) {
final boolean indexMergeStrategyEnabled = isFlagEnabled(queryOptions, PREFER_INDEX_MERGE_STRATEGY);
if (indexMergeStrategyEnabled) {
final ResultSet<O> indexAcceleratedQueryResults = retrieveWithoutIndexOrdering(query, queryOptions, null);
if (indexAcceleratedQueryResults.getRetrievalCost() == Integer.MAX_VALUE) {
// No index is available to accelerate the index merge strategy...
indexAcceleratedQueryResults.close();
// We fall back to filtering via query.matches() below.
}
else {
// Ensure that indexAcceleratedQueryResults is closed at the end of processing the request...
final CloseableResourceGroup closeableResourceGroup = CloseableRequestResources.forQueryOptions(queryOptions).addGroup();
closeableResourceGroup.add(indexAcceleratedQueryResults);
// This is the index merge strategy where indexes are used to filter the sorted results...
return new FilteringIterator<O>(sortedCandidateResults, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return indexAcceleratedQueryResults.contains(object);
}
};
}
}
// Either index merge strategy is not enabled, or no suitable indexes are available for it.
// We filter results by examining values returned by attributes referenced in the query instead...
return new FilteringIterator<O>(sortedCandidateResults, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return query.matches(object, queryOptions);
}
};
}
static <O, A extends Comparable<A>> Persistence<O, A> getPersistenceFromQueryOptions(QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
Persistence<O, A> persistence = (Persistence<O, A>) queryOptions.get(Persistence.class);
if (persistence == null) {
throw new IllegalStateException("A required Persistence object was not supplied in query options");
}
return persistence;
}
/**
* Called when using an index to order results, to determine if or how results within each bucket
* in that index should be sorted.
* <p/>
*
* We must sort results within each bucket, when:
* <ol>
* <li>
* The index is quantized.
* </li>
* <li>
* The attribute can have multiple values (if object 1 values ["a"] and object 2 has values
* ["a", "b"] then objects 1 & 2 will both be in the same bucket, but object 1 should sort first ascending).
* However this case can be suppressed with
* {@link EngineFlags#INDEX_ORDERING_ALLOW_FAST_ORDERING_OF_MULTI_VALUED_ATTRIBUTES}.
* </li>
* <li>
* There are additional sort orders after the first one.
* </li>
* </ol>
*
* @param allSortOrders The user-specified sort orders
* @param attributeCanHaveMoreThanOneValue If the primary attribute used for sorting can return more than one value
* @param index The index from which the bucket is accessed
* @return A list of AttributeOrder objects representing the sort order to apply to objects in the bucket
*/
static <O> List<AttributeOrder<O>> determineAdditionalSortOrdersForIndexOrdering(List<AttributeOrder<O>> allSortOrders, boolean attributeCanHaveMoreThanOneValue, Index<O> index, QueryOptions queryOptions) {
return (index.isQuantized() || (attributeCanHaveMoreThanOneValue && !isFlagEnabled(queryOptions, INDEX_ORDERING_ALLOW_FAST_ORDERING_OF_MULTI_VALUED_ATTRIBUTES)))
? allSortOrders // We must re-sort on all sort orders within each bucket.
: allSortOrders.subList(1, allSortOrders.size());
}
static <A extends Comparable<A>, O> CloseableIterator<KeyValue<A, O>> getKeysAndValuesInRange(SortedKeyStatisticsIndex<A, O> index, RangeBounds<?> queryBounds, boolean descending, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
RangeBounds<A> typedBounds = (RangeBounds<A>) queryBounds;
if (!descending) {
return index.getKeysAndValues(
typedBounds.lowerBound, typedBounds.lowerInclusive,
typedBounds.upperBound, typedBounds.upperInclusive,
queryOptions
).iterator();
}
else {
return index.getKeysAndValuesDescending(
typedBounds.lowerBound, typedBounds.lowerInclusive,
typedBounds.upperBound, typedBounds.upperInclusive,
queryOptions
).iterator();
}
}
static class RangeBounds<A extends Comparable<A>> {
final A lowerBound;
final boolean lowerInclusive;
final A upperBound;
final Boolean upperInclusive;
public RangeBounds(A lowerBound, boolean lowerInclusive, A upperBound, Boolean upperInclusive) {
this.lowerBound = lowerBound;
this.lowerInclusive = lowerInclusive;
this.upperBound = upperBound;
this.upperInclusive = upperInclusive;
}
}
static <A extends Comparable<A>, O> RangeBounds getBoundsFromQuery(Query<O> query, Attribute<O, A> attribute) {
A lowerBound = null, upperBound = null;
boolean lowerInclusive = false, upperInclusive = false;
List<SimpleQuery<O, ?>> candidateRangeQueries = Collections.emptyList();
if (query instanceof SimpleQuery) {
candidateRangeQueries = Collections.<SimpleQuery<O, ?>>singletonList((SimpleQuery<O, ?>) query);
}
else if (query instanceof And) {
And<O> and = (And<O>)query;
if (and.hasSimpleQueries()) {
candidateRangeQueries = and.getSimpleQueries();
}
}
for (SimpleQuery<O, ?> candidate : candidateRangeQueries) {
if (attribute.equals(candidate.getAttribute())) {
if (candidate instanceof GreaterThan) {
@SuppressWarnings("unchecked")
GreaterThan<O, A> bound = (GreaterThan<O, A>) candidate;
lowerBound = bound.getValue();
lowerInclusive = bound.isValueInclusive();
}
else if (candidate instanceof LessThan) {
@SuppressWarnings("unchecked")
LessThan<O, A> bound = (LessThan<O, A>) candidate;
upperBound = bound.getValue();
upperInclusive = bound.isValueInclusive();
}
else if (candidate instanceof Between) {
@SuppressWarnings("unchecked")
Between<O, A> bound = (Between<O, A>) candidate;
lowerBound = bound.getLowerValue();
lowerInclusive = bound.isLowerInclusive();
upperBound = bound.getUpperValue();
upperInclusive = bound.isUpperInclusive();
}
}
}
return new RangeBounds<A>(lowerBound, lowerInclusive, upperBound, upperInclusive);
}
/**
* Implements the bulk of query processing.
* <p/>
* This method is recursive.
* <p/>
* When processing a {@link SimpleQuery}, the method will simply delegate to the helper methods
* {@link #retrieveIntersectionOfSimpleQueries(Collection, QueryOptions, boolean)} and
* {@link #retrieveUnionOfSimpleQueries(Collection, QueryOptions)}
* and will return their results.
* <p/>
* When processing a descendant of {@link CompoundQuery} ({@link And}, {@link Or}, {@link Not}), the method
* will extract separately from those objects the child queries which are {@link SimpleQuery}s and the child
* queries which are {@link CompoundQuery}s. It will call the helper methods above to process the child
* {@link SimpleQuery}s, and the method will call itself recursively to process the child {@link CompoundQuery}s.
* Once the method has results for both the child {@link SimpleQuery}s and the child {@link CompoundQuery}s, it
* will return them in a {@link ResultSetIntersection}, {@link ResultSetUnion} or {@link ResultSetDifference}
* object as appropriate for {@link And}, {@link Or}, {@link Not} respectively. These {@link ResultSet} objects
* will take care of performing intersections or unions etc. on the child {@link ResultSet}s.
*
* @param query A query representing some assertions which sought objects must match
* @param queryOptions Optional parameters for the query
* supplied specifying strategy {@link DeduplicationStrategy#LOGICAL_ELIMINATION}
* @return A {@link ResultSet} which provides objects matching the given query
*/
ResultSet<O> retrieveRecursive(Query<O> query, final QueryOptions queryOptions) {
final boolean indexMergeStrategyEnabled = isFlagEnabled(queryOptions, PREFER_INDEX_MERGE_STRATEGY);
// Check if we can process this query from a standing query index...
ResultSet<O> resultSetFromStandingQueryIndex = retrieveFromStandingQueryIndexIfAvailable(query, queryOptions);
if (resultSetFromStandingQueryIndex != null) {
// A standing query index was available, return its results...
return resultSetFromStandingQueryIndex;
}
// ..else no standing query index was available, process the query normally...
if (query instanceof SimpleQuery) {
// No deduplication required for a single SimpleQuery.
// Return the ResultSet from the index with the lowest retrieval cost which supports
// this query and the attribute on which it is based...
return retrieveSimpleQuery((SimpleQuery<O, ?>) query, queryOptions);
}
else if (query instanceof ComparativeQuery) {
// Return the ResultSet from the index with the lowest retrieval cost which supports
// this query and the attribute on which it is based...
return retrieveComparativeQuery((ComparativeQuery<O, ?>) query, queryOptions);
}
else if (query instanceof And) {
final And<O> and = (And<O>) query;
// Check if we can process this And query from a compound index...
if (!compoundIndexes.isEmpty()) {
// Compound indexes exist. Check if any can be used for this And query...
CompoundQuery<O> compoundQuery = CompoundQuery.fromAndQueryIfSuitable(and);
if (compoundQuery != null) {
CompoundIndex<O> compoundIndex = compoundIndexes.get(compoundQuery.getCompoundAttribute());
if (compoundIndex != null && compoundIndex.supportsQuery(compoundQuery, queryOptions)) {
// No deduplication required for retrievals from compound indexes.
return compoundIndex.retrieve(compoundQuery, queryOptions);
}
}
} // else no suitable compound index exists, process the And query normally...
// No deduplication required for intersections.
Iterable<ResultSet<O>> resultSetsToMerge = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new UnmodifiableIterator<ResultSet<O>>() {
boolean needToProcessSimpleQueries = and.hasSimpleQueries();
boolean needToProcessComparativeQueries = and.hasComparativeQueries();
Iterator<LogicalQuery<O>> logicalQueriesIterator = and.getLogicalQueries().iterator();
@Override
public boolean hasNext() {
return needToProcessSimpleQueries || needToProcessComparativeQueries || logicalQueriesIterator.hasNext();
}
@Override
public ResultSet<O> next() {
if (needToProcessSimpleQueries) {
needToProcessSimpleQueries = false;
// Retrieve results for simple queries from indexes...
return retrieveIntersectionOfSimpleQueries(and.getSimpleQueries(), queryOptions, indexMergeStrategyEnabled);
}
if (needToProcessComparativeQueries) {
needToProcessComparativeQueries = false;
// Retrieve results for comparative queries from indexes...
return retrieveIntersectionOfComparativeQueries(and.getComparativeQueries(), queryOptions);
}
// Recursively call this method for logical queries...
return retrieveRecursive(logicalQueriesIterator.next(), queryOptions);
}
};
}
};
boolean useIndexMergeStrategy = shouldUseIndexMergeStrategy(indexMergeStrategyEnabled, and.hasComparativeQueries(), resultSetsToMerge);
return new ResultSetIntersection<O>(resultSetsToMerge, query, queryOptions, useIndexMergeStrategy);
}
else if (query instanceof Or) {
final Or<O> or = (Or<O>) query;
// If the Or query indicates child queries are disjoint,
// ignore any instruction to perform deduplication in the queryOptions supplied...
final QueryOptions queryOptionsForOrUnion;
if (or.isDisjoint()) {
// The Or query is disjoint, so there is no need to perform deduplication on its results.
// Wrap the QueryOptions object in another which omits the DeduplicationOption if it is requested
// when evaluating this Or statement...
queryOptionsForOrUnion = new QueryOptions(queryOptions.getOptions()) {
@Override
public Object get(Object key) {
return DeduplicationOption.class.equals(key) ? null : super.get(key);
}
};
}
else {
// Use the supplied queryOptions...
queryOptionsForOrUnion = queryOptions;
}
Iterable<ResultSet<O>> resultSetsToUnion = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new UnmodifiableIterator<ResultSet<O>>() {
boolean needToProcessSimpleQueries = or.hasSimpleQueries();
boolean needToProcessComparativeQueries = or.hasComparativeQueries();
Iterator<LogicalQuery<O>> logicalQueriesIterator = or.getLogicalQueries().iterator();
@Override
public boolean hasNext() {
return needToProcessSimpleQueries || needToProcessComparativeQueries || logicalQueriesIterator.hasNext();
}
@Override
public ResultSet<O> next() {
if (needToProcessSimpleQueries) {
needToProcessSimpleQueries = false;
// Retrieve results for simple queries from indexes...
return retrieveUnionOfSimpleQueries(or.getSimpleQueries(), queryOptionsForOrUnion);
}
if (needToProcessComparativeQueries) {
needToProcessComparativeQueries = false;
// Retrieve results for comparative queries from indexes...
return retrieveUnionOfComparativeQueries(or.getComparativeQueries(), queryOptionsForOrUnion);
}
// Recursively call this method for logical queries.
// Note we supply the original queryOptions for recursive calls...
return retrieveRecursive(logicalQueriesIterator.next(), queryOptions);
}
};
}
};
ResultSet<O> union;
// *** Deduplication can be required for unions... ***
if (DeduplicationOption.isLogicalElimination(queryOptionsForOrUnion)) {
boolean useIndexMergeStrategy = shouldUseIndexMergeStrategy(indexMergeStrategyEnabled, or.hasComparativeQueries(), resultSetsToUnion);
union = new ResultSetUnion<O>(resultSetsToUnion, query, queryOptions, useIndexMergeStrategy);
}
else {
union = new ResultSetUnionAll<O>(resultSetsToUnion, query, queryOptions);
}
if (union.getRetrievalCost() == Integer.MAX_VALUE && !or.hasComparativeQueries()) {
// Either no indexes are available for any branches of the or() query, or indexes are only available
// for some of the branches.
// If we were to delegate to the FallbackIndex to retrieve results for any of the branches which
// don't have indexes, then the FallbackIndex would scan the entire collection to locate results.
// This would happen for *each* of the branches which don't have indexes - so the entire collection
// could be scanned multiple times.
// So to avoid that, here we will scan the entire collection once, to find all objects which match
// all of the child branches in a single scan.
// Note: there is no need to deduplicate results which were fetched this way.
union = new FilteringResultSet<O>(getEntireCollectionAsResultSet(query, queryOptions), or, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return or.matches(object, queryOptions);
}
};
}
return union;
}
else if (query instanceof Not) {
final Not<O> not = (Not<O>) query;
// No deduplication required for negation (the entire collection is a Set, contains no duplicates).
// Retrieve the ResultSet for the negated query, by calling this method recursively...
ResultSet<O> resultSetToNegate = retrieveRecursive(not.getNegatedQuery(), queryOptions);
// Return the negation of this result set, by subtracting it from the entire collection of objects...
return new ResultSetDifference<O>(getEntireCollectionAsResultSet(query, queryOptions), resultSetToNegate, query, queryOptions, indexMergeStrategyEnabled);
}
else {
throw new IllegalStateException("Unexpected type of query object: " + getClassNameNullSafe(query));
}
}
/**
* Retrieves an intersection of the objects matching {@link SimpleQuery}s.
* <p/>
* <i>Definitions:
* For a definition of <u>retrieval cost</u> see {@link ResultSet#getRetrievalCost()}.
* For a definition of <u>merge cost</u> see {@link ResultSet#getMergeCost()}.
* </i>
* <p/>
* The algorithm employed by this method is as follows.
* <p/>
* For each {@link SimpleQuery} supplied, retrieves a {@link ResultSet} for that {@link SimpleQuery}
* from the index with the lowest <u>retrieval cost</u> which supports that {@link SimpleQuery}.
* <p/>
* The algorithm then determines the {@link ResultSet} with the <i>lowest</i> <u>merge cost</u>, and the
* {@link SimpleQuery} which was associated with that {@link ResultSet}. It also assembles a list of the
* <i>other</i> {@link SimpleQuery}s which had <i>more expensive</i> <u>merge costs</u>.
* <p/>
* The algorithm then returns a {@link FilteringResultSet} which iterates the {@link ResultSet} with the
* <i>lowest</i> <u>merge cost</u>. During iteration, this {@link FilteringResultSet} calls a
* {@link FilteringResultSet#isValid(Object, QueryOptions)} method for each object. This algorithm implements that method to
* return true if the object matches all of the {@link SimpleQuery}s which had the <i>more expensive</i>
* <u>merge costs</u>.
* <p/>
* As such the {@link ResultSet} which had the lowest merge cost drives the iteration. Note therefore that this
* method <i>does <u>not</u> perform set intersections in the conventional sense</i> (i.e. using
* {@link Set#contains(Object)}). It has been tested empirically that it is usually cheaper to invoke
* {@link Query#matches(Object, QueryOptions)} to test each object in the smallest set against queries which would match the
* more expensive sets, rather than perform several hash lookups and equality tests between multiple sets.
*
* @param queries A collection of {@link SimpleQuery} objects to be retrieved and intersected
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} which provides objects matching the intersection of results for each of the
* {@link SimpleQuery}s
*/
<A> ResultSet<O> retrieveIntersectionOfSimpleQueries(Collection<SimpleQuery<O, ?>> queries, QueryOptions queryOptions, boolean indexMergeStrategyEnabled) {
List<ResultSet<O>> resultSets = new ArrayList<ResultSet<O>>(queries.size());
for (SimpleQuery query : queries) {
// Work around type erasure...
@SuppressWarnings({"unchecked"})
SimpleQuery<O, A> queryTyped = (SimpleQuery<O, A>) query;
ResultSet<O> resultSet = retrieveSimpleQuery(queryTyped, queryOptions);
resultSets.add(resultSet);
}
@SuppressWarnings("unchecked")
Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new And<O>(queriesTyped);
boolean useIndexMergeStrategy = indexMergeStrategyEnabled && indexesAvailableForAllResultSets(resultSets);
return new ResultSetIntersection<O>(resultSets, query, queryOptions, useIndexMergeStrategy);
}
/**
* Same as {@link #retrieveIntersectionOfSimpleQueries(Collection, QueryOptions, boolean)}
* except for {@link ComparativeQuery}.
*/
<A> ResultSet<O> retrieveIntersectionOfComparativeQueries(Collection<ComparativeQuery<O, ?>> queries, QueryOptions queryOptions) {
List<ResultSet<O>> resultSets = new ArrayList<ResultSet<O>>(queries.size());
for (ComparativeQuery query : queries) {
// Work around type erasure...
@SuppressWarnings({"unchecked"})
ComparativeQuery<O, A> queryTyped = (ComparativeQuery<O, A>) query;
ResultSet<O> resultSet = retrieveComparativeQuery(queryTyped, queryOptions);
resultSets.add(resultSet);
}
@SuppressWarnings("unchecked")
Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new And<O>(queriesTyped);
// We always use index merge strategy to merge results for comparative queries...
return new ResultSetIntersection<O>(resultSets, query, queryOptions, true);
}
/**
* Retrieves a union of the objects matching {@link SimpleQuery}s.
* <p/>
* <i>Definitions:
* For a definition of <u>retrieval cost</u> see {@link ResultSet#getRetrievalCost()}.
* For a definition of <u>merge cost</u> see {@link ResultSet#getMergeCost()}.
* </i>
* <p/>
* The algorithm employed by this method is as follows.
* <p/>
* For each {@link SimpleQuery} supplied, retrieves a {@link ResultSet} for that {@link SimpleQuery}
* from the index with the lowest <u>retrieval cost</u> which supports that {@link SimpleQuery}.
* <p/>
* The method then returns these {@link ResultSet}s in either a {@link ResultSetUnion} or a
* {@link ResultSetUnionAll} object, depending on whether {@code logicalDuplicateElimination} was specified
* or not. These concatenate the wrapped {@link ResultSet}s when iterated. In the case of {@link ResultSetUnion},
* this also ensures that duplicate objects are not returned more than once, by means of logical elimination via
* set theory rather than maintaining a record of all objects iterated.
*
* @param queries A collection of {@link SimpleQuery} objects to be retrieved and unioned
* @param queryOptions Optional parameters for the query
* supplied specifying strategy {@link DeduplicationStrategy#LOGICAL_ELIMINATION}
* @return A {@link ResultSet} which provides objects matching the union of results for each of the
* {@link SimpleQuery}s
*/
ResultSet<O> retrieveUnionOfSimpleQueries(final Collection<SimpleQuery<O, ?>> queries, final QueryOptions queryOptions) {
Iterable<ResultSet<O>> resultSetsToUnion = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new UnmodifiableIterator<ResultSet<O>>() {
Iterator<SimpleQuery<O, ?>> queriesIterator = queries.iterator();
@Override
public boolean hasNext() {
return queriesIterator.hasNext();
}
@Override
public ResultSet<O> next() {
return retrieveSimpleQuery(queriesIterator.next(), queryOptions);
}
};
}
};
@SuppressWarnings("unchecked")
Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new Or<O>(queriesTyped);
// Perform deduplication as necessary...
if (DeduplicationOption.isLogicalElimination(queryOptions)) {
// Use the index merge strategy if it was requested and indexes are available for all result sets...
boolean indexMergeStrategyEnabled = isFlagEnabled(queryOptions, PREFER_INDEX_MERGE_STRATEGY);
boolean useIndexMergeStrategy = indexMergeStrategyEnabled && indexesAvailableForAllResultSets(resultSetsToUnion);
return new ResultSetUnion<O>(resultSetsToUnion, query, queryOptions, useIndexMergeStrategy);
}
else {
return new ResultSetUnionAll<O>(resultSetsToUnion, query, queryOptions);
}
}
/**
* Same as {@link #retrieveUnionOfSimpleQueries(Collection, QueryOptions)}
* except for {@link ComparativeQuery}.
*/
ResultSet<O> retrieveUnionOfComparativeQueries(final Collection<ComparativeQuery<O, ?>> queries, final QueryOptions queryOptions) {
Iterable<ResultSet<O>> resultSetsToUnion = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new UnmodifiableIterator<ResultSet<O>>() {
Iterator<ComparativeQuery<O, ?>> queriesIterator = queries.iterator();
@Override
public boolean hasNext() {
return queriesIterator.hasNext();
}
@Override
public ResultSet<O> next() {
return retrieveComparativeQuery(queriesIterator.next(), queryOptions);
}
};
}
};
@SuppressWarnings("unchecked")
Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new Or<O>(queriesTyped);
// Perform deduplication as necessary...
if (DeduplicationOption.isLogicalElimination(queryOptions)) {
// Note: we always use the index merge strategy to merge results for comparative queries...
return new ResultSetUnion<O>(resultSetsToUnion, query, queryOptions, true);
}
else {
return new ResultSetUnionAll<O>(resultSetsToUnion, query, queryOptions);
}
}
/**
* Checks if the given query can be answered from a standing query index, and if so returns
* a {@link ResultSet} which does so.
* If the query cannot be answered from a standing query index, returns null.
*
* @param query The query to evaluate
* @param queryOptions Query options supplied for the query
* @return A {@link ResultSet} which answers the query from a standing query index, or null if no such index
* is available
*/
ResultSet<O> retrieveFromStandingQueryIndexIfAvailable(Query<O> query, final QueryOptions queryOptions) {
// Check if we can process this query from a standing query index...
Index<O> standingQueryIndex = standingQueryIndexes.get(query);
if (standingQueryIndex != null) {
// No deduplication required for standing queries.
if (standingQueryIndex instanceof StandingQueryIndex) {
return standingQueryIndex.retrieve(query, queryOptions);
}
else {
return standingQueryIndex.retrieve(equal(forStandingQuery(query), Boolean.TRUE), queryOptions);
}
} // else no suitable standing query index exists, process the query normally...
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(final ObjectSet<O> objectSet, final QueryOptions queryOptions) {
ensureMutable();
final FlagHolder modified = new FlagHolder();
forEachIndexDo(new IndexOperation<O>() {
@Override
public boolean perform(Index<O> index) {
modified.value |= index.addAll(objectSet, queryOptions);
return true;
}
});
return modified.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(final ObjectSet<O> objectSet, final QueryOptions queryOptions) {
ensureMutable();
final FlagHolder modified = new FlagHolder();
forEachIndexDo(new IndexOperation<O>() {
@Override
public boolean perform(Index<O> index) {
modified.value |= index.removeAll(objectSet, queryOptions);
return true;
}
});
return modified.value;
}
/**
* {@inheritDoc}
* @param queryOptions
*/
@Override
public void clear(final QueryOptions queryOptions) {
ensureMutable();
forEachIndexDo(new IndexOperation<O>() {
@Override
public boolean perform(Index<O> index) {
index.clear(queryOptions);
return true;
}
});
}
/**
* {@inheritDoc}
*/
@Override
public boolean isMutable() {
return immutableIndexes.isEmpty();
}
/**
* Throws an {@link IllegalStateException} if all indexes are not mutable.
*/
void ensureMutable() {
if (!immutableIndexes.isEmpty()) {
throw new IllegalStateException("Cannot modify indexes, an immutable index has been added.");
}
}
/**
* A closure/callback object invoked for each index in turn by method
* {@link CollectionQueryEngine#forEachIndexDo(IndexOperation)}.
*/
interface IndexOperation<O> {
/**
* @param index The index to be processed
* @return Operation can return true to continue iterating through all indexes, false to stop iterating
*/
boolean perform(Index<O> index);
}
/**
* Iterates through all indexes and for each index invokes the given index operation. If the operation returns
* false for any index, stops iterating and returns false. If the operation returns true for every index,
* returns true after all indexes have been iterated.
* @param indexOperation The operation to perform on each index.
* @return true if the operation returned true for all indexes and so all indexes were iterated, false if the
* operation returned false for any index and so iteration was stopped
*/
boolean forEachIndexDo(IndexOperation<O> indexOperation) {
// Perform the operation on attribute indexes...
Iterable<Index<O>> attributeIndexes = new ConcatenatingIterable<Index<O>>(this.attributeIndexes.values());
for (Index<O> index : attributeIndexes) {
boolean continueIterating = indexOperation.perform(index);
if (!continueIterating) {
return false;
}
}
// Perform the operation on compound indexes...
Iterable<? extends Index<O>> compoundIndexes = this.compoundIndexes.values();
for (Index<O> index : compoundIndexes) {
boolean continueIterating = indexOperation.perform(index);
if (!continueIterating) {
return false;
}
}
// Perform the operation on standing query indexes...
Iterable<? extends Index<O>> standingQueryIndexes = this.standingQueryIndexes.values();
for (Index<O> index : standingQueryIndexes) {
boolean continueIterating = indexOperation.perform(index);
if (!continueIterating) {
return false;
}
}
// Perform the operation on the fallback index...
return indexOperation.perform(fallbackIndex);
}
static class FlagHolder {
boolean value = false;
}
static String getClassNameNullSafe(Object object) {
return object == null ? null : object.getClass().getName();
}
/**
* Indicates if the engine should use the index merge strategy.
* <p>
* This will return true if comparativeQueriesPresent is true, because it is necessary to use
* the index merge strategy with comparative queries, because comparative queries do not support filtering.
* <p>
* Otherwise, if there are no comparative queries involved, this will return true if indexes are available for all
* of the given result sets AND the index merge strategy was requested.
*/
static <O> boolean shouldUseIndexMergeStrategy(boolean strategyRequested, boolean comparativeQueriesPresent, Iterable<ResultSet<O>> resultSetsToMerge) {
if (comparativeQueriesPresent) {
return true;
}
return strategyRequested && indexesAvailableForAllResultSets(resultSetsToMerge);
}
static <O> boolean indexesAvailableForAllResultSets(Iterable<ResultSet<O>> resultSetsToMerge) {
for (ResultSet<O> resultSet : resultSetsToMerge) {
if (resultSet.getRetrievalCost() == Integer.MAX_VALUE) {
return false;
}
}
return true;
}
}
| 79,216 | 51.288449 | 301 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/Persistence.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.persistence;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Set;
/**
* An interface with multiple implementations, which provide details on how a collection or indexes should be persisted
* (for example on-heap, off-heap, or disk).
*
* @author niall.gallagher
*/
public interface Persistence<O, A extends Comparable<A>> {
/**
* Creates an ObjectStore which can store the objects added to the collection, either on-heap off-heap or on disk,
* depending on the persistence implementation.
*
* @return An ObjectStore which persists objects added to the collection.
*/
ObjectStore<O> createObjectStore();
/**
* Checks if this persistence manages the given index.
* @param index The {@link Index} to check.
* @return true if this persistence manages the given index. False otherwise.
*/
boolean supportsIndex(Index<O> index);
/**
* Called at the start of every request into CQEngine, to prepare any resources needed by the request in order
* to access the persistence.
* <p/>
* The implementation of this method may be a no-op in some persistence implementations, such as those exclusively
* on-heap. However the implementation of this method in other persistence implementations, such as off-heap or
* on-disk, may open files or connections to the persistence for use by the ObjectStore and indexes during the
* request.
* <p/>
* This method does not modify the state of the Persistence object; instead it will add any resources it opens to
* the given QueryOptions object. The related {@link #closeRequestScopeResources(QueryOptions)} method will then
* be called at the end of every request into CQEngine, to close any resources in the QueryOptions which this method
* opened.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
void openRequestScopeResources(QueryOptions queryOptions);
/**
* Called at the end of every request into CQEngine, to close any resources which were opened by the
* {@link #openRequestScopeResources(QueryOptions)} method and stored in the given query options.
*
* @param queryOptions The query options supplied with the request into CQEngine, and which has earlier been
* supplied to the {@link #openRequestScopeResources(QueryOptions)} method.
*/
void closeRequestScopeResources(QueryOptions queryOptions);
/**
* @return the primary key attribute, if configured. This may be null for some persistence implementations
* especially on-heap persistence.
*/
SimpleAttribute<O, A> getPrimaryKeyAttribute();
}
| 3,534 | 42.641975 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/composite/CompositePersistence.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.persistence.composite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.ConnectionManager;
import com.googlecode.cqengine.index.sqlite.RequestScopeConnectionManager;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A Persistence object which wraps two or more backing Persistence objects.
* <p/>
* The collection itself will be persisted to the primary persistence object supplied to the constructor.
*
* @author niall.gallagher
*/
public class CompositePersistence<O, A extends Comparable<A>> implements Persistence<O, A> {
final Persistence<O, A> primaryPersistence;
final Persistence<O, A> secondaryPersistence;
final List<? extends Persistence<O, A>> additionalPersistences;
// Cache of the Persistence object associated with each index.
// Tuned for very little concurrency because this is caching static config.
final ConcurrentMap<Index<O>, Persistence<O, A>> indexPersistences = new ConcurrentHashMap<Index<O>, Persistence<O, A>>(1, 1.0F, 1);
/**
* Creates a CompositePersistence wrapping two or more backing persistences.
* <b>The collection itself will be persisted to the primary persistence.</b>
*
* @param primaryPersistence The first backing persistence to wrap, and to use to persist the collection itself.
* @param secondaryPersistence The second backing persistence to wrap.
* @param additionalPersistences Zero or more additional backing persistences to wrap.
* @throws NullPointerException If any argument is null.
* @throws IllegalArgumentException If any of the Persistence objects are not on the same primary key.
*/
public CompositePersistence(Persistence<O, A> primaryPersistence, Persistence<O, A> secondaryPersistence, List<? extends Persistence<O, A>> additionalPersistences) {
validatePersistenceArguments(primaryPersistence, secondaryPersistence, additionalPersistences);
this.primaryPersistence = primaryPersistence;
this.secondaryPersistence = secondaryPersistence;
this.additionalPersistences = additionalPersistences;
}
@Override
public SimpleAttribute<O, A> getPrimaryKeyAttribute() {
return primaryPersistence.getPrimaryKeyAttribute();
}
@Override
public boolean supportsIndex(Index<O> index) {
Persistence<O, A> persistence = getPersistenceForIndexOrNullWithCaching(index);
return persistence != null;
}
public Persistence<O, A> getPersistenceForIndex(Index<O> index) {
Persistence<O, A> persistence = getPersistenceForIndexOrNullWithCaching(index);
if (persistence == null) {
throw new IllegalStateException("No persistence is configured for index: " + index);
}
return persistence;
}
@Override
public ObjectStore<O> createObjectStore() {
return primaryPersistence.createObjectStore();
}
Persistence<O, A> getPersistenceForIndexOrNullWithCaching(Index<O> index) {
Persistence<O, A> persistence = indexPersistences.get(index);
if (persistence == null) {
persistence = getPersistenceForIndexOrNull(index);
if (persistence != null) {
Persistence<O, A> existing = indexPersistences.putIfAbsent(index, persistence);
if (existing != null) {
persistence = existing;
}
}
}
return persistence;
}
Persistence<O, A> getPersistenceForIndexOrNull(Index<O> index) {
if (primaryPersistence.supportsIndex(index)) {
return primaryPersistence;
}
if (secondaryPersistence.supportsIndex(index)) {
return secondaryPersistence;
}
for (Persistence<O, A> additionalPersistence : additionalPersistences) {
if (additionalPersistence.supportsIndex(index)) {
return additionalPersistence;
}
}
return null;
}
public Persistence<O, A> getPrimaryPersistence() {
return primaryPersistence;
}
public Persistence<O, A> getSecondaryPersistence() {
return secondaryPersistence;
}
public List<? extends Persistence<O, A>> getAdditionalPersistences() {
return additionalPersistences;
}
/**
* Validates that all of the given Persistence objects are non-null, and validates that all Persistence objects
* which have primary keys have the same primary keys.
*
* @param primaryPersistence A Persistence object to be validated
* @param secondaryPersistence A Persistence object to be validated
* @param additionalPersistences Zero or more Persistence objects to be validated
*/
static <O, A extends Comparable<A>> void validatePersistenceArguments(Persistence<O, A> primaryPersistence, Persistence<O, A> secondaryPersistence, List<? extends Persistence<O, A>> additionalPersistences) {
SimpleAttribute<O, A> primaryKeyAttribute;
primaryKeyAttribute = validatePersistenceArgument(primaryPersistence, null);
primaryKeyAttribute = validatePersistenceArgument(secondaryPersistence, primaryKeyAttribute);
for (Persistence<O, A> additionalPersistence : additionalPersistences) {
validatePersistenceArgument(additionalPersistence, primaryKeyAttribute);
}
}
/**
* Helper method for {@link #validatePersistenceArguments(Persistence, Persistence, List)}. See documentation of
* that method for details.
*/
static <O, A extends Comparable<A>> SimpleAttribute<O, A> validatePersistenceArgument(Persistence<O, A> persistence, SimpleAttribute<O, A> primaryKeyAttribute) {
if (persistence == null) {
throw new NullPointerException("The Persistence argument cannot be null.");
}
if (persistence.getPrimaryKeyAttribute() == null) {
throw new IllegalArgumentException("All Persistence implementations in a CompositePersistence must have a primary key.");
}
if (primaryKeyAttribute == null) {
primaryKeyAttribute = persistence.getPrimaryKeyAttribute();
}
else if (!primaryKeyAttribute.equals(persistence.getPrimaryKeyAttribute())) {
throw new IllegalArgumentException("All Persistence implementations must be on the same primary key.");
}
return primaryKeyAttribute;
}
/**
* Creates a new {@link RequestScopeConnectionManager} and adds it to the given query options with key
* {@link ConnectionManager}, if an only if no object with that key is already in the query options.
* This allows the application to supply its own implementation of {@link ConnectionManager} to override the default
* if necessary.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void openRequestScopeResources(QueryOptions queryOptions) {
if (queryOptions.get(ConnectionManager.class) == null) {
queryOptions.put(ConnectionManager.class, new RequestScopeConnectionManager(this));
}
}
/**
* Closes a {@link RequestScopeConnectionManager} if it is present in the given query options with key
* {@link ConnectionManager}.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
ConnectionManager connectionManager = queryOptions.get(ConnectionManager.class);
if (connectionManager instanceof RequestScopeConnectionManager) {
((RequestScopeConnectionManager) connectionManager).close();
queryOptions.remove(ConnectionManager.class);
}
}
/**
* Creates a CompositePersistence wrapping two or more backing persistences.
* <b>The collection itself will be persisted to the primary persistence.</b>
*
* @param primaryPersistence The first backing persistence to wrap, and to use to persist the collection itself.
* @param secondaryPersistence The second backing persistence to wrap.
* @param additionalPersistences Zero or more additional backing persistences to wrap.
* @throws NullPointerException If any argument is null.
* @throws IllegalArgumentException If any of the Persistence objects are not on the same primary key.
*/
public static <O, A extends Comparable<A>> CompositePersistence<O, A> of(Persistence<O, A> primaryPersistence, Persistence<O, A> secondaryPersistence, List<? extends Persistence<O, A>> additionalPersistences) {
return new CompositePersistence<O, A>(primaryPersistence, secondaryPersistence, additionalPersistences);
}
/**
* Creates a CompositePersistence wrapping two backing persistences.
* <b>The collection itself will be persisted to the primary persistence.</b>
*
* @param primaryPersistence The first backing persistence to wrap, and to use to persist the collection itself.
* @param secondaryPersistence The second backing persistence to wrap.
* @throws NullPointerException If any argument is null.
* @throws IllegalArgumentException If any of the Persistence objects are not on the same primary key.
*/
public static <O, A extends Comparable<A>> CompositePersistence<O, A> of(Persistence<O, A> primaryPersistence, Persistence<O, A> secondaryPersistence) {
return new CompositePersistence<O, A>(primaryPersistence, secondaryPersistence, Collections.<Persistence<O, A>>emptyList());
}
}
| 10,526 | 46.206278 | 214 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/wrapping/WrappingPersistence.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.persistence.wrapping;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.CollectionWrappingObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Collection;
/**
* Specifies to wrap and use a given collection for persistence.
* <p/>
* Note that, as the implementation of the given collection is outside of CQEngine's control,
* the following points should be considered with respect to performance and query processing.
* <p/>
* <b>Collection.contains() method</b><br/>
* As CQEngine evaluates queries using set theory, it relies heavily on the performance of the
* {@link Collection#contains(Object)} method.
* If the implementation of this method in the given collection is slow, then it may slow down some queries on the
* {@link IndexedCollection}.
* <p/>
* As such, it is recommended, although not required, that the wrapped collection is a {@link java.util.Set}.
* The time complexity of the {@link java.util.Set#contains(Object)} method is usually <i>O(1)</i>.
* <p/>
* <b>Duplicate objects</b><br/>
* CQEngine does not expect the given collection to contain duplicate objects. If the given collection does
* contain duplicates, then it is possible that duplicate objects may be returned in {@link ResultSet}s
* even if deduplication was requested.
* <p/>
* <b>Thread-safety</b><br/>
* CQEngine will depend on the wrapped collection to be thread-safe, if an {@link IndexedCollection} is
* configured with this persistence, and it will be accessed concurrently.
* <p/>
* If the application needs to access the the {@link IndexedCollection} concurrently but it cannot supply
* a thread-safe collection to wrap, then it is recommended to use the {@link OnHeapPersistence} instead.
*
* @author niall.gallagher
*/
public class WrappingPersistence<O, A extends Comparable<A>> implements Persistence<O, A> {
final Collection<O> backingCollection;
final SimpleAttribute<O, A> primaryKeyAttribute;
public WrappingPersistence(Collection<O> backingCollection) {
this(backingCollection, null);
}
public WrappingPersistence(Collection<O> backingCollection, SimpleAttribute<O, A> primaryKeyAttribute) {
this.backingCollection = backingCollection;
this.primaryKeyAttribute = primaryKeyAttribute;
}
/**
* Returns true if the given index implements the {@link OnHeapTypeIndex} marker interface.
*/
@Override
public boolean supportsIndex(Index<O> index) {
return index instanceof OnHeapTypeIndex;
}
@Override
public ObjectStore<O> createObjectStore() {
return new CollectionWrappingObjectStore<O>(backingCollection);
}
/**
* Currently does nothing in this implementation of {@link Persistence}.
*/
@Override
public void openRequestScopeResources(QueryOptions queryOptions) {
// No op
}
/**
* Currently does nothing in this implementation of {@link Persistence}.
*/
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
// No op
}
@Override
public SimpleAttribute<O, A> getPrimaryKeyAttribute() {
return primaryKeyAttribute;
}
/**
* Creates a {@link WrappingPersistence} object which persists to the given collection.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @return A {@link WrappingPersistence} object which persists to the given collection.
*/
public static <O, A extends Comparable<A>> WrappingPersistence<O, A> aroundCollectionOnPrimaryKey(Collection<O> collection, SimpleAttribute<O, A> primaryKeyAttribute) {
return new WrappingPersistence<O, A>(collection, primaryKeyAttribute);
}
/**
* Creates a {@link WrappingPersistence} object which persists to the given collection, without specifying a primary
* key. As such, this persistence implementation will be compatible with on-heap indexes only.
* <p/>
* This persistence will not work with composite persistence configurations, where some indexes are located on heap,
* and some off-heap etc. To use this persistence in those configurations, it is necessary to specify a primary
* key - see: {@link #aroundCollectionOnPrimaryKey(Collection, SimpleAttribute)}.
*
* @return A {@link WrappingPersistence} object which persists to the given collection, and which is not configured
* with a primary key.
*/
@SuppressWarnings("unchecked")
public static <O> WrappingPersistence<O, ? extends Comparable> aroundCollection(Collection<O> collection) {
return withoutPrimaryKey_Internal(collection);
}
static <O, A extends Comparable<A>> WrappingPersistence<O, A> withoutPrimaryKey_Internal(Collection<O> collection) {
return new WrappingPersistence<O, A>(collection);
}
}
| 5,996 | 42.456522 | 172 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/disk/DiskPersistence.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.persistence.disk;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.ConnectionManager;
import com.googlecode.cqengine.index.sqlite.RequestScopeConnectionManager;
import com.googlecode.cqengine.index.sqlite.SQLitePersistence;
import com.googlecode.cqengine.index.sqlite.support.DBQueries;
import com.googlecode.cqengine.index.sqlite.support.DBUtils;
import com.googlecode.cqengine.index.support.indextype.DiskTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.persistence.support.sqlite.LockReleasingConnection;
import com.googlecode.cqengine.persistence.support.sqlite.SQLiteDiskIdentityIndex;
import com.googlecode.cqengine.persistence.support.sqlite.SQLiteObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import java.io.Closeable;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.googlecode.cqengine.persistence.support.PersistenceFlags.READ_REQUEST;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.query.option.FlagsEnabled.isFlagEnabled;
/**
* Specifies that a collection or indexes should be persisted to a particular file on disk.
* <p/>
* <b>Note on Concurrency</b><br/>
* Note this disk persistence implementation supports fully concurrent reads and writes by default. This is because
* it enables <i><a href="https://www.sqlite.org/wal.html">Write-Ahead Logging</a></i> ("WAL") journal mode in the
* underlying SQLite database file by default (see that link for more details).
* <p/>
* Optionally, this class allows the application to override the journal mode or other settings in SQLite by
* supplying <i>"override properties"</i> to the {@link #onPrimaryKeyInFileWithProperties(SimpleAttribute, File, Properties)}
* method. As WAL mode is suitable for most applications, most applications should work best with the default settings;
* the override support is intended for advanced or custom use cases.
* <p>
* Two other CQEngine-specific properties are also supported:
* <ul>
* <li>
* {@code shared_cache} = true|false (default is false)<br/>
* This enables <a href="https://www.sqlite.org/sharedcache.html">SQLite Shared-Cache Mode</a>,
* which can improve transaction throughput and reduce IO,
* at the expense of supporting less write concurrency.
* </li>
* <li>
* {@code persistent_connection} = true|false (default is false)<br/>
* This causes the DiskPersistence to keep open an otherwise unused persistent connection
* to the database file on disk. This prevents the file from being closed between
* transactions, which can improve performance.<br/>
* This will be enabled automatically if {@code shared_cache} is enabled
* because it is a requirement for that feature to work.
* This might be beneficial to enable on its own even without {@code shared_cache} in some
* applications, but the benefit without {@code shared_cache} could to be quite marginal.<br/>
* When {@code persistent_connection} = true, it is recommended (although not mandatory)
* to call {@link #close()} when the application is finished using the collection;
* in order to close the persistent connection. Otherwise the persistent connection will only
* be closed when this object is garbage collected.
* </li>
* <li>
* {@code use_read_write_lock} = true|false (default is true)<br/>
* This is enabled by default but used only when {@code shared_cache} is enabled.
* This causes a read-write lock to be used to guard access to the shared cache.
* The shared-cache mode supports less concurrency than the non-shared cache mode,
* and leaving this enabled can prevent exceptions being thrown due to attempts to
* write concurrently.
* </li>
* </ul>
* </p>
*
* @author niall.gallagher
*/
public class DiskPersistence<O, A extends Comparable<A>> implements SQLitePersistence<O, A>, Closeable {
final SimpleAttribute<O, A> primaryKeyAttribute;
final File file;
final SQLiteDataSource sqLiteDataSource;
final boolean useReadWriteLock;
// Read-write lock is only used in shared-cache mode...
final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
static final Properties DEFAULT_PROPERTIES = new Properties();
static {
DEFAULT_PROPERTIES.setProperty("busy_timeout", String.valueOf(Integer.MAX_VALUE)); // Wait indefinitely to acquire locks (technically 68 years)
DEFAULT_PROPERTIES.setProperty("journal_mode", "WAL"); // Use Write-Ahead-Logging which supports concurrent reads and writes
DEFAULT_PROPERTIES.setProperty("synchronous", "NORMAL"); // Setting synchronous to normal is safe and faster when using WAL
DEFAULT_PROPERTIES.setProperty("shared_cache", "false"); // Improves transaction throughput and reduces IO, at the expense of supporting less write concurrency
DEFAULT_PROPERTIES.setProperty("persistent_connection", "false"); // Prevents the database file from being closed between transactions
}
// If persistent_connection=true, this will be a connection which we keep open to prevent SQLite
// from closing the database file until this object is garbage-collected,
// or close() is called explicitly on this object...
volatile Connection persistentConnection;
volatile boolean closed = false;
protected DiskPersistence(SimpleAttribute<O, A> primaryKeyAttribute, File file, Properties overrideProperties) {
Properties effectiveProperties = new Properties();
effectiveProperties.putAll(DEFAULT_PROPERTIES);
effectiveProperties.putAll(overrideProperties);
SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);
this.primaryKeyAttribute = primaryKeyAttribute;
this.file = file.getAbsoluteFile();
this.sqLiteDataSource = sqLiteDataSource;
boolean openPersistentConnection = "true".equals(effectiveProperties.getProperty("persistent_connection")); //default false
boolean useSharedCache = "true".equals(effectiveProperties.getProperty("shared_cache")); // default false
boolean useReadWriteLock = !"false".equals(effectiveProperties.getProperty("use_read_write_lock")); // default true
if (useSharedCache) {
// If shared_cache mode is enabled, by default we also use a read-write lock,
// unless using the read-write lock has been explicitly disabled...
sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file + "?cache=shared");
this.useReadWriteLock = useReadWriteLock;
}
else {
// If we are not using shared_cache mode, we never use a read-write lock...
sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);
this.useReadWriteLock = false;
}
if (useSharedCache || openPersistentConnection) {
// If shared_cache is enabled, we always open a persistent connection regardless...
this.persistentConnection = getConnectionWithoutRWLock(null, noQueryOptions());
}
}
@Override
public SimpleAttribute<O, A> getPrimaryKeyAttribute() {
return primaryKeyAttribute;
}
public File getFile() {
return file;
}
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
return useReadWriteLock
? getConnectionWithRWLock(index, queryOptions)
: getConnectionWithoutRWLock(index, queryOptions);
}
protected Connection getConnectionWithRWLock(Index<?> index, QueryOptions queryOptions) {
// Acquire a read lock IFF the READ_REQUEST flag has been set, otherwise acquire a write lock by default...
final Lock connectionLock = isFlagEnabled(queryOptions, READ_REQUEST)
? readWriteLock.readLock() : readWriteLock.writeLock();
connectionLock.lock();
Connection connection;
try {
connection = getConnectionWithoutRWLock(index, queryOptions);
}
catch (RuntimeException e) {
connectionLock.unlock();
throw e;
}
return LockReleasingConnection.wrap(connection, connectionLock);
}
protected Connection getConnectionWithoutRWLock(Index<?> index, QueryOptions queryOptions) {
if (closed) {
throw new IllegalStateException("DiskPersistence has been closed: " + this.toString());
}
try {
return sqLiteDataSource.getConnection();
}
catch (SQLException e) {
throw new IllegalStateException("Failed to open SQLite connection for file: " + file, e);
}
}
/**
* @param index The {@link Index} for which a connection is required.
* @return True if the given index is a {@link DiskTypeIndex}. Otherwise false.
*/
@Override
public boolean supportsIndex(Index<O> index) {
return index instanceof DiskTypeIndex;
}
/**
* Closes the persistent connection, if there is an open persistent connection.
* After calling this, the DiskPersistence can no longer be used, and attempts to do
* so will result in {@link IllegalStateException}s being thrown.
*/
@Override
public void close() {
DBUtils.closeQuietly(persistentConnection);
this.persistentConnection = null;
this.closed = true;
}
/**
* Finalizer which automatically calls {@link #close()} when this object is garbage collected.
] */
@Override
protected void finalize() throws Throwable {
super.finalize();
close();
}
@Override
public long getBytesUsed() {
Connection connection = null;
try {
connection = getConnection(null, noQueryOptions());
return DBQueries.getDatabaseSize(connection);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
public void compact() {
Connection connection = null;
try {
connection = getConnection(null, noQueryOptions());
DBQueries.compactDatabase(connection);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
public void expand(long numBytes) {
Connection connection = null;
try {
connection = getConnection(null, noQueryOptions());
DBQueries.expandDatabase(connection, numBytes);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DiskPersistence)) {
return false;
}
DiskPersistence<?, ?> that = (DiskPersistence<?, ?>) o;
return primaryKeyAttribute.equals(that.primaryKeyAttribute) && file.equals(that.file);
}
@Override
public int hashCode() {
int result = primaryKeyAttribute.hashCode();
result = 31 * result + file.hashCode();
return result;
}
@Override
public String toString() {
return "DiskPersistence{" +
"primaryKeyAttribute=" + primaryKeyAttribute +
", file=" + file +
'}';
}
@Override
public ObjectStore<O> createObjectStore() {
return new SQLiteObjectStore<O, A>(this);
}
@Override
public SQLiteDiskIdentityIndex<A, O> createIdentityIndex() {
return SQLiteDiskIdentityIndex.onAttribute(primaryKeyAttribute);
}
/**
* Creates a new {@link RequestScopeConnectionManager} and adds it to the given query options with key
* {@link ConnectionManager}, if an only if no object with that key is already in the query options.
* This allows the application to supply its own implementation of {@link ConnectionManager} to override the default
* if necessary.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void openRequestScopeResources(QueryOptions queryOptions) {
if (queryOptions.get(ConnectionManager.class) == null) {
queryOptions.put(ConnectionManager.class, new RequestScopeConnectionManager(this));
}
}
/**
* Closes a {@link RequestScopeConnectionManager} if it is present in the given query options with key
* {@link ConnectionManager}.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
ConnectionManager connectionManager = queryOptions.get(ConnectionManager.class);
if (connectionManager instanceof RequestScopeConnectionManager) {
((RequestScopeConnectionManager) connectionManager).close();
queryOptions.remove(ConnectionManager.class);
}
}
/**
* Creates a new unique temp file in the JVM temp directory which can be used for persistence.
* @return a new unique temp file in the JVM temp directory which can be used for persistence.
*/
public static File createTempFile() {
File tempFile;
try {
tempFile = File.createTempFile("cqengine_", ".db");
}
catch (Exception e) {
throw new IllegalStateException("Failed to create temp file for CQEngine disk persistence", e);
}
return tempFile;
}
/**
* Creates a {@link DiskPersistence} object which persists to a temp file on disk. The exact temp file used can
* be determined by calling the {@link #getFile()} method.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @return A {@link DiskPersistence} object which persists to a temp file on disk
* @see #onPrimaryKeyInFile(SimpleAttribute, File)
*/
public static <O, A extends Comparable<A>> DiskPersistence<O, A> onPrimaryKey(SimpleAttribute<O, A> primaryKeyAttribute) {
return DiskPersistence.onPrimaryKeyInFile(primaryKeyAttribute, createTempFile());
}
/**
* Creates a {@link DiskPersistence} object which persists to a given file on disk.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @param file The file on disk to which data should be persisted
* @return A {@link DiskPersistence} object which persists to the given file on disk
*/
public static <O, A extends Comparable<A>> DiskPersistence<O, A> onPrimaryKeyInFile(SimpleAttribute<O, A> primaryKeyAttribute, File file) {
return DiskPersistence.onPrimaryKeyInFileWithProperties(primaryKeyAttribute, file, new Properties());
}
/**
* Creates a {@link DiskPersistence} object which persists to a given file on disk.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @param file The file on disk to which data should be persisted
* @param overrideProperties Optional properties to override default settings (can be empty to use all default
* settings, but cannot be null)
* @return A {@link DiskPersistence} object which persists to the given file on disk
*/
public static <O, A extends Comparable<A>> DiskPersistence<O, A> onPrimaryKeyInFileWithProperties(SimpleAttribute<O, A> primaryKeyAttribute, File file, Properties overrideProperties) {
return new DiskPersistence<O, A>(primaryKeyAttribute, file, overrideProperties);
}
}
| 16,979 | 43.450262 | 188 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/CollectionWrappingObjectStore.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.persistence.support;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collection;
import java.util.Iterator;
/**
* An {@link ObjectStore} which wraps a {@link Collection} and delegates all method calls to the collection.
*
* @author niall.gallagher
*/
public class CollectionWrappingObjectStore<O> implements ObjectStore<O> {
final Collection<O> backingCollection;
public CollectionWrappingObjectStore(Collection<O> backingCollection) {
this.backingCollection = backingCollection;
}
public Collection<O> getBackingCollection() {
return backingCollection;
}
@Override
public int size(QueryOptions queryOptions) {
return backingCollection.size();
}
@Override
public boolean contains(Object o, QueryOptions queryOptions) {
return backingCollection.contains(o);
}
@Override
public CloseableIterator<O> iterator(QueryOptions queryOptions) {
final Iterator<O> i = backingCollection.iterator();
return new CloseableIterator<O>() {
@Override
public void close() {
// No op
}
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public O next() {
return i.next();
}
@Override
public void remove() {
i.remove();
}
};
}
@Override
public boolean isEmpty(QueryOptions queryOptions) {
return backingCollection.isEmpty();
}
@Override
public boolean add(O object, QueryOptions queryOptions) {
return backingCollection.add(object);
}
@Override
public boolean remove(Object o, QueryOptions queryOptions) {
return backingCollection.remove(o);
}
@Override
public boolean containsAll(Collection<?> c, QueryOptions queryOptions) {
return backingCollection.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends O> c, QueryOptions queryOptions) {
return backingCollection.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c, QueryOptions queryOptions) {
return backingCollection.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c, QueryOptions queryOptions) {
// The following code is a workaround for a performance bottleneck in JDK 8 and earlier.
// See the following issues for details:
// JDK - https://bugs.openjdk.java.net/browse/JDK-8160751
// CQEngine - https://github.com/npgall/cqengine/issues/154
// We avoid calling backingCollection.removeAll().
// The backingCollection is typically backed by a ConcurrentHashMap,
// due to being created via Collections.newSetFromMap(new ConcurrentHashMap<O, Boolean>()).
// Thus we cannot rely on the good performance of backingCollection.removeAll()
// when CQEngine is run on JDK 8 or earlier.
boolean modified = false;
for (Object e : c) {
modified |= backingCollection.remove(e);
}
return modified;
}
@Override
public void clear(QueryOptions queryOptions) {
backingCollection.clear();
}
}
| 4,021 | 29.014925 | 108 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/ObjectStoreAsSet.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.persistence.support;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.io.IOException;
import java.util.AbstractSet;
import java.util.Collection;
/**
* Adapts an {@link ObjectStore} to behave like a {@link java.util.Set}, using an existing connection to the
* persistence when methods belonging to the Set interface are called.
*/
public class ObjectStoreAsSet<O> extends AbstractSet<O> {
final ObjectStore<O> objectStore;
final QueryOptions queryOptions;
public ObjectStoreAsSet(ObjectStore<O> objectStore, QueryOptions queryOptions) {
this.objectStore = objectStore;
this.queryOptions = queryOptions;
}
@Override
public int size() {
return objectStore.size(queryOptions);
}
@Override
public boolean contains(Object o) {
return objectStore.contains(o, queryOptions);
}
@Override
public CloseableIterator<O> iterator() {
return objectStore.iterator(queryOptions);
}
@Override
public boolean isEmpty() {
return objectStore.isEmpty(queryOptions);
}
@Override
public boolean add(O object) {
return objectStore.add(object, queryOptions);
}
@Override
public boolean remove(Object o) {
return objectStore.remove(o, queryOptions);
}
@Override
public boolean containsAll(Collection<?> c) {
return objectStore.containsAll(c, queryOptions);
}
@Override
public boolean addAll(Collection<? extends O> c) {
return objectStore.addAll(c, queryOptions);
}
@Override
public boolean retainAll(Collection<?> c) {
return objectStore.retainAll(c, queryOptions);
}
@Override
public boolean removeAll(Collection<?> c) {
return objectStore.removeAll(c, queryOptions);
}
@Override
public void clear() {
objectStore.clear(queryOptions);
}
}
| 2,662 | 27.031579 | 108 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/ObjectStoreResultSet.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.persistence.support;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Iterator;
/**
* Created by npgall on 01/03/2016.
*/
public class ObjectStoreResultSet<O> extends ResultSet<O> {
final ObjectStore<O> objectStore;
final Query<O> query;
final QueryOptions queryOptions;
final int retrievalCost;
final ObjectSet<O> objectSet;
public ObjectStoreResultSet(ObjectStore<O> objectStore, Query<O> query, QueryOptions queryOptions, int retrievalCost) {
this.objectStore = objectStore;
this.query = query;
this.queryOptions = queryOptions;
this.retrievalCost = retrievalCost;
this.objectSet = ObjectSet.fromObjectStore(objectStore, queryOptions);
}
@Override
public Iterator<O> iterator() {
return objectSet.iterator();
}
@Override
public boolean contains(O object) {
return objectStore.contains(object, queryOptions);
}
@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 retrievalCost;
}
@Override
public int getMergeCost() {
return size();
}
@Override
public int size() {
return objectStore.size(queryOptions);
}
@Override
public void close() {
objectSet.close();
}
}
| 2,301 | 25.159091 | 123 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/ConcurrentOnHeapObjectStore.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.persistence.support;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
/**
* An {@link ObjectStore} which wraps a concurrent implementation of {@link java.util.Set}.
*
* @author niall.gallagher
*/
public class ConcurrentOnHeapObjectStore<O> extends CollectionWrappingObjectStore<O> {
public ConcurrentOnHeapObjectStore() {
super(Collections.newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
public ConcurrentOnHeapObjectStore(int initialCapacity, float loadFactor, int concurrencyLevel) {
super(Collections.newSetFromMap(new ConcurrentHashMap<O, Boolean>(initialCapacity, loadFactor, concurrencyLevel)));
}
}
| 1,318 | 34.648649 | 123 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/ObjectSet.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.persistence.support;
import com.googlecode.cqengine.index.support.CloseableIterable;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.io.Closeable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Represents a set of objects which may be iterated repeatedly, allowing the resources opened
* for each iteration to be closed afterwards.
* <p/>
* The {@link #iterator()} method returns a {@link CloseableIterator} which should ideally be
* closed after each iteration is complete.
* <p/>
* However this object also keeps track of iterators which were opened but not yet closed,
* and provides a {@link #close()} method which will close all iterators which remain open.
*
* @author npgall
*/
public abstract class ObjectSet<O> implements CloseableIterable<O>, Closeable {
// ====== External interface methods... ======
@Override
public abstract void close();
public abstract boolean isEmpty();
// ====== Static factories to instantiate implementations... ======
public static <O> ObjectSet<O> fromObjectStore(final ObjectStore<O> objectStore, final QueryOptions queryOptions) {
return new ObjectStoreAsObjectSet<O>(objectStore, queryOptions);
}
public static <O> ObjectSet<O> fromCollection(final Collection<O> collection) {
return new CollectionAsObjectSet<O>(collection);
}
// ====== ObjectSet implementations which wrap a Collection or ObjectStore... ======
static class CollectionAsObjectSet<O> extends ObjectSet<O> {
final Collection<O> collection;
public CollectionAsObjectSet(Collection<O> collection) {
this.collection = collection;
}
@Override
public CloseableIterator<O> iterator() {
final Iterator<O> iterator = collection.iterator();
return new CloseableIterator<O>() {
@Override
public void close() {
// No op
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public O next() {
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
@Override
public boolean isEmpty() {
return collection.isEmpty();
}
@Override
public void close() {
// No op
}
}
static class ObjectStoreAsObjectSet<O> extends ObjectSet<O> {
final ObjectStore<O> objectStore;
final QueryOptions queryOptions;
final Set<CloseableIterator<O>> openIterators = new HashSet<CloseableIterator<O>>();
public ObjectStoreAsObjectSet(ObjectStore<O> objectStore, QueryOptions queryOptions) {
this.objectStore = objectStore;
this.queryOptions = queryOptions;
}
@Override
public CloseableIterator<O> iterator() {
final CloseableIterator<O> iterator = objectStore.iterator(queryOptions);
openIterators.add(iterator);
return new CloseableIterator<O>() {
@Override
public void close() {
openIterators.remove(this);
iterator.close();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public O next() {
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
public boolean isEmpty() {
CloseableIterator<O> iterator = objectStore.iterator(queryOptions);
try {
return !iterator.hasNext();
}
finally {
iterator.close();
}
}
@Override
public void close() {
for (CloseableIterator<O> openIterator : openIterators) {
openIterator.close();
}
openIterators.clear();
}
}
}
| 5,084 | 29.63253 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/ObjectStore.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.persistence.support;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collection;
import java.util.Set;
/**
* An interface providing similar methods as {@link java.util.Set}, except the methods accept {@link QueryOptions}.
* <p/>
* This interface can thus wrap a standard on-heap Set, or an off-heap or disk implementation of a Set where the
* implementation can extract details of the persistence to use from the supplied query options.
*/
public interface ObjectStore<O> {
int size(QueryOptions queryOptions);
boolean contains(Object o, QueryOptions queryOptions);
CloseableIterator<O> iterator(QueryOptions queryOptions);
boolean isEmpty(QueryOptions queryOptions);
boolean add(O object, QueryOptions queryOptions);
boolean remove(Object o, QueryOptions queryOptions);
boolean containsAll(Collection<?> c, QueryOptions queryOptions);
boolean addAll(Collection<? extends O> c, QueryOptions queryOptions);
boolean retainAll(Collection<?> c, QueryOptions queryOptions);
boolean removeAll(Collection<?> c, QueryOptions queryOptions);
void clear(QueryOptions queryOptions);
}
| 1,862 | 34.150943 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/PersistenceFlags.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.persistence.support;
/**
* Constants for flags which may be set into query options by the query engine internally.
*/
public class PersistenceFlags {
public static String READ_REQUEST = "READ_REQUEST";
}
| 848 | 32.96 | 90 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/FilteredObjectStore.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.persistence.support;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.filter.FilteringIterator;
import java.util.Collection;
/**
* Wraps an {@link ObjectStore} and filters objects returned by its iterator to ensure they match a given query.
* <p/>
* Note this wrapper does not support any method except {@link #iterator(QueryOptions)}!
* All other methods will throw {@link UnsupportedOperationException}.
*
* @author niall.gallagher
*/
public class FilteredObjectStore<O> implements ObjectStore<O> {
final ObjectStore<O> backingObjectStore;
final Query<O> filterQuery;
public FilteredObjectStore(ObjectStore<O> backingObjectStore, Query<O> filterQuery) {
this.backingObjectStore = backingObjectStore;
this.filterQuery = filterQuery;
}
/**
* Returns the subset of objects from the backing {@link ObjectStore} which match the filter query supplied to the
* constructor.
*
* @return the subset of objects from the backing {@link ObjectStore} which match the filter query supplied to the
* constructor.
*/
@Override
public CloseableIterator<O> iterator(QueryOptions queryOptions) {
final CloseableIterator<O> backingIterator = backingObjectStore.iterator(queryOptions);
final FilteringIterator<O> filteringIterator = new FilteringIterator<O>(backingIterator, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
return filterQuery.matches(object, queryOptions);
}
};
return new CloseableIterator<O>() {
@Override
public void close() {
backingIterator.close();
}
@Override
public boolean hasNext() {
return filteringIterator.hasNext();
}
@Override
public O next() {
return filteringIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Modification not supported");
}
};
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public int size(QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean contains(Object o, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean isEmpty(QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean add(O object, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean remove(Object o, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean containsAll(Collection<?> c, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean addAll(Collection<? extends O> c, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean retainAll(Collection<?> c, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public boolean removeAll(Collection<?> c, QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException Always.
*/
@Override
public void clear(QueryOptions queryOptions) {
throw new UnsupportedOperationException();
}
}
| 5,002 | 29.882716 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/sqlite/SQLiteObjectStore.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.persistence.support.sqlite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.sqlite.SQLiteIdentityIndex;
import com.googlecode.cqengine.index.sqlite.SQLitePersistence;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.UnmodifiableIterator;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.has;
/**
* @author niall.gallagher
*/
public class SQLiteObjectStore<O, A extends Comparable<A>> implements ObjectStore<O> {
final SQLitePersistence<O, A> persistence;
final SQLiteIdentityIndex<A, O> backingIndex;
final SimpleAttribute<O, A> primaryKeyAttribute;
final Class<O> objectType;
public SQLiteObjectStore(final SQLitePersistence<O, A> persistence) {
this.persistence = persistence;
this.objectType = persistence.getPrimaryKeyAttribute().getObjectType();
this.primaryKeyAttribute = persistence.getPrimaryKeyAttribute();
this.backingIndex = persistence.createIdentityIndex();
}
public void init(QueryOptions queryOptions) {
backingIndex.init(this, queryOptions);
}
public SQLitePersistence<O, A> getPersistence() {
return persistence;
}
public SQLiteIdentityIndex<A, O> getBackingIndex() {
return backingIndex;
}
@Override
public int size(QueryOptions queryOptions) {
return backingIndex.retrieve(has(primaryKeyAttribute), queryOptions).size();
}
@Override
public boolean contains(Object o, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
O object = (O) o;
A objectId = primaryKeyAttribute.getValue(object, queryOptions);
return backingIndex.retrieve(equal(primaryKeyAttribute, objectId), queryOptions).size() > 0;
}
@Override
public CloseableIterator<O> iterator(QueryOptions queryOptions) {
final ResultSet<O> rs = backingIndex.retrieve(has(primaryKeyAttribute), queryOptions);
final Iterator<O> i = rs.iterator();
class CloseableIteratorImpl extends UnmodifiableIterator<O> implements CloseableIterator<O> {
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public O next() {
return i.next();
}
@Override
public void close() {
rs.close();
}
}
return new CloseableIteratorImpl();
}
@Override
public boolean isEmpty(QueryOptions queryOptions) {
return size(queryOptions) == 0;
}
@Override
public boolean add(O object, QueryOptions queryOptions) {
return backingIndex.addAll(ObjectSet.fromCollection(Collections.singleton(object)), queryOptions);
}
@Override
public boolean remove(Object o, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
O object = (O) o;
return backingIndex.removeAll(ObjectSet.fromCollection(Collections.singleton(object)), queryOptions);
}
@Override
public boolean containsAll(Collection<?> c, QueryOptions queryOptions) {
for (Object o : c) {
if (!contains(o, queryOptions)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends O> c, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
Collection<O> objects = (Collection<O>) c;
return backingIndex.addAll(ObjectSet.fromCollection(objects), queryOptions);
}
@Override
public boolean retainAll(Collection<?> c, QueryOptions queryOptions) {
// Note: this could be optimized...
Collection<O> objectsToRemove = new ArrayList<O>();
ResultSet<O> allObjects = backingIndex.retrieve(has(primaryKeyAttribute), queryOptions);
try {
for (O object : allObjects) {
if (!c.contains(object)) {
objectsToRemove.add(object);
}
}
}
finally {
allObjects.close();
}
return backingIndex.removeAll(ObjectSet.fromCollection(objectsToRemove), queryOptions);
}
@Override
public boolean removeAll(Collection<?> c, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
Collection<O> objects = (Collection<O>) c;
return backingIndex.removeAll(ObjectSet.fromCollection(objects), queryOptions);
}
@Override
public void clear(QueryOptions queryOptions) {
backingIndex.clear(queryOptions);
}
} | 5,606 | 33.398773 | 109 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/sqlite/SQLiteDiskIdentityIndex.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.persistence.support.sqlite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.SQLiteIdentityIndex;
import com.googlecode.cqengine.index.support.indextype.DiskTypeIndex;
/**
* A subclass of {@link SQLiteIdentityIndex} intended for use with disk persistence.
* This subclass does not override any behaviour, and exists only so that CQEngine can distinguish between
* disk-based and off-heap configurations of the superclass index.
*
* @author niall.gallagher
*/
public class SQLiteDiskIdentityIndex<A extends Comparable<A>, O> extends SQLiteIdentityIndex<A, O> implements DiskTypeIndex{
public SQLiteDiskIdentityIndex(SimpleAttribute<O, A> primaryKeyAttribute) {
super(primaryKeyAttribute);
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* Creates a new {@link SQLiteDiskIdentityIndex} 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 {@link SQLiteDiskIdentityIndex}
*/
public static <A extends Comparable<A>, O> SQLiteDiskIdentityIndex<A, O> onAttribute(final SimpleAttribute<O, A> primaryKeyAttribute) {
return new SQLiteDiskIdentityIndex<A, O>(primaryKeyAttribute);
}
}
| 2,166 | 39.886792 | 139 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/sqlite/LockReleasingConnection.java | /**
* Copyright 2012-2019 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.persistence.support.sqlite;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.locks.Lock;
/**
* Wraps a {@link Connection} in a proxy object which delegates all method calls to it, and which additionally
* unlocks the given lock whenever the {@link Connection#close()} method is closed.
* <p/>
* Unlocks the lock at most once, ignoring subsequent calls.
*/
public class LockReleasingConnection implements InvocationHandler {
final Connection targetConnection;
final Lock lockToUnlock;
boolean unlockedAlready = false;
LockReleasingConnection(Connection targetConnection, Lock lockToUnlock) {
this.targetConnection = targetConnection;
this.lockToUnlock = lockToUnlock;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result = m.invoke(targetConnection, args);
if(m.getName().equals("close") && !unlockedAlready){
lockToUnlock.unlock();
unlockedAlready = true;
}
return result;
}
public static Connection wrap(Connection targetConnection, Lock lockToUnlock) {
return (Connection) Proxy.newProxyInstance(
targetConnection.getClass().getClassLoader(),
new Class<?>[] { Connection.class },
new LockReleasingConnection(targetConnection, lockToUnlock)
);
}
}
| 2,125 | 36.298246 | 110 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/sqlite/SQLiteOffHeapIdentityIndex.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.persistence.support.sqlite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.SQLiteIdentityIndex;
import com.googlecode.cqengine.index.support.indextype.OffHeapTypeIndex;
/**
* A subclass of {@link SQLiteIdentityIndex} intended for use with off-heap persistence.
* This subclass does not override any behaviour, and exists only so that CQEngine can distinguish between
* disk-based and off-heap configurations of the superclass index.
*
* @author niall.gallagher
*/
public class SQLiteOffHeapIdentityIndex<A extends Comparable<A>, O> extends SQLiteIdentityIndex<A, O> implements OffHeapTypeIndex {
public SQLiteOffHeapIdentityIndex(SimpleAttribute<O, A> primaryKeyAttribute) {
super(primaryKeyAttribute);
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* Creates a new {@link SQLiteOffHeapIdentityIndex} 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 {@link SQLiteOffHeapIdentityIndex}
*/
public static <A extends Comparable<A>, O> SQLiteOffHeapIdentityIndex<A, O> onAttribute(final SimpleAttribute<O, A> primaryKeyAttribute) {
return new SQLiteOffHeapIdentityIndex<A, O>(primaryKeyAttribute);
}
}
| 2,195 | 40.433962 | 142 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/serialization/PersistenceConfig.java | package com.googlecode.cqengine.persistence.support.serialization;
import java.lang.annotation.*;
/**
* An annotation which can be added to POJO classes to customize persistence behavior.
*
* @author npgall
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PersistenceConfig {
/**
* The {@link PojoSerializer} implementation to use.
* <p>
* The default is {@link KryoSerializer}. Note that the behaviour of that serializer
* is highly customizable via annotations itself, including the ability to configure
* it to use Java's built-in serialization. See
* <a href="https://github.com/EsotericSoftware/kryo">Kryo</a> for details.
* </p>
*/
Class<? extends PojoSerializer> serializer() default KryoSerializer.class;
/**
* If true, causes CQEngine to persist the name of the class with every object,
* to allow the collection to contain a mix of object types within an inheritance hierarchy.
*
* If false, causes CQEngine to skip persisting the name of the class and to assume all objects
* in the collection will be instances of the same class.
* <p>
* The default value is false, which is commonly applicable and gives better performance
* and reduces the size of the serialized collection. However it will cause exceptions if
* different types of objects are added to the same collection, in which case applications
* can change this setting.
* </p>
*/
boolean polymorphic() default false;
PersistenceConfig DEFAULT_CONFIG = new PersistenceConfig() {
@Override
public Class<? extends Annotation> annotationType() {
return PersistenceConfig.class;
}
@Override
public Class<? extends PojoSerializer> serializer() {
return KryoSerializer.class;
}
@Override
public boolean polymorphic() {
return false;
}
};
}
| 2,015 | 33.758621 | 99 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/serialization/KryoSerializer.java | package com.googlecode.cqengine.persistence.support.serialization;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy;
import de.javakaffee.kryoserializers.ArraysAsListSerializer;
import de.javakaffee.kryoserializers.SynchronizedCollectionsSerializer;
import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer;
import org.objenesis.strategy.StdInstantiatorStrategy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
/**
* Uses <a href="https://github.com/EsotericSoftware/kryo">Kryo</a> to serialize and deserialize objects;
* for use with CQEngine's disk and off-heap indexes and persistence.
* <p/>
* A {@link #validateObjectIsRoundTripSerializable(Object)} method is also provided, to validate
* the compatibility of end-user POJOs with this serializer.
*
* @author npgall
*/
public class KryoSerializer<O> implements PojoSerializer<O> {
protected final Class<O> objectType;
protected final boolean polymorphic;
protected final ThreadLocal<Kryo> kryoCache = new ThreadLocal<Kryo>() {
@Override
protected Kryo initialValue() {
return createKryo(objectType);
}
};
/**
* Creates a new Kryo serializer which is configured to serialize objects of the given type.
*
* @param objectType The type of the object
* @param persistenceConfig Configuration for the serializer, in particular the polymorphic parameter which
* if true, causes Kryo to persist the name of the class with every object, to allow
* the collection to contain a mix of object types within an inheritance hierarchy;
* if false causes Kryo to skip persisting the name of the class and to assume all objects
* in the collection will be instances of the same class.
*
*/
public KryoSerializer(Class<O> objectType, PersistenceConfig persistenceConfig) {
this.objectType = objectType;
this.polymorphic = persistenceConfig.polymorphic();
}
/**
* Creates a new instance of Kryo serializer, for use with the given object type.
* <p/>
* Note: this method is public to allow end-users to validate compatibility of their POJOs,
* with the Kryo serializer as used by CQEngine.
*
* @param objectType The type of object which the instance of Kryo will serialize
* @return a new instance of Kryo serializer
*/
@SuppressWarnings({"ArraysAsListWithZeroOrOneArgument", "WeakerAccess"})
protected Kryo createKryo(Class<?> objectType) {
Kryo kryo = new Kryo();
// Instantiate serialized objects via a no-arg constructor when possible, falling back to Objenesis...
kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
// Register the object which this index will persist...
kryo.register(objectType);
kryo.setRegistrationRequired(false);
// Register additional serializers which are not built-in to Kryo 3.0...
kryo.register(Arrays.asList().getClass(), new ArraysAsListSerializer());
UnmodifiableCollectionsSerializer.registerSerializers(kryo);
SynchronizedCollectionsSerializer.registerSerializers(kryo);
return kryo;
}
/**
* Serializes the given object, using the given instance of Kryo serializer.
*
* @param object The object to serialize
* @return The serialized form of the object as a byte array
*/
@Override
public byte[] serialize(O object) {
if (object == null) {
throw new NullPointerException("Object was null");
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Output output = new Output(baos);
Kryo kryo = kryoCache.get();
if (polymorphic) {
kryo.writeClassAndObject(output, object);
}
else {
kryo.writeObject(output, object);
}
output.close();
return baos.toByteArray();
}
catch (Throwable e) {
throw new IllegalStateException("Failed to serialize object, object type: " + objectType + ". " +
"Configure @PersistenceConfig.polymorphic if the collection will contain a mix of object types. " +
"Use the KryoSerializer.validateObjectIsRoundTripSerializable() method " +
"to test your object is compatible with CQEngine.", e);
}
}
/**
* Deserializes the given bytes, into an object of the given type, using the given instance of Kryo serializer.
*
* @param bytes The serialized form of the object as a byte array
* @return The deserialized object
*/
@Override
@SuppressWarnings("unchecked")
public O deserialize(byte[] bytes) {
try {
Input input = new Input(new ByteArrayInputStream(bytes));
Kryo kryo = kryoCache.get();
O object;
if (polymorphic) {
object = (O) kryo.readClassAndObject(input);
}
else {
object = kryo.readObject(input, objectType);
}
input.close();
return object;
}
catch (Throwable e) {
throw new IllegalStateException("Failed to deserialize object, object type: " + objectType + ". " +
"Configure @PersistenceConfig.polymorphic if the collection will contain a mix of object types. " +
"Use the KryoSerializer.validateObjectIsRoundTripSerializable() method " +
"to test your object is compatible with CQEngine.", e);
}
}
/**
* Performs sanity tests on the given POJO object, to check if it can be serialized and deserialized with Kryo
* serialzier as used by CQEngine.
* <p/>
* If a POJO fails this test, then it typically means CQEngine will be unable to serialize or deserialize
* it, and thus the POJO can't be used with CQEngine's off-heap or disk indexes or persistence.
* <p/>
* Failing the test typically means the data structures or data types within the POJO are too complex. Simplifying
* the POJO will usually improve compatibility.
* <p/>
* This method will return normally if the POJO passes the tests, or will throw an exception if it fails.
*
* @param candidatePojo The POJO to test
*/
@SuppressWarnings("unchecked")
public static <O> void validateObjectIsRoundTripSerializable(O candidatePojo) {
Class<O> objectType = (Class<O>) candidatePojo.getClass();
KryoSerializer.validateObjectIsRoundTripSerializable(candidatePojo, objectType, PersistenceConfig.DEFAULT_CONFIG);
}
static <O> void validateObjectIsRoundTripSerializable(O candidatePojo, Class<O> objectType, PersistenceConfig persistenceConfig) {
try {
KryoSerializer<O> serializer = new KryoSerializer<O>(
objectType,
persistenceConfig
);
byte[] serialized = serializer.serialize(candidatePojo);
O deserializedPojo = serializer.deserialize(serialized);
serializer.kryoCache.remove(); // clear cached Kryo instance
validateObjectEquality(candidatePojo, deserializedPojo);
validateHashCodeEquality(candidatePojo, deserializedPojo);
}
catch (Exception e) {
throw new IllegalStateException("POJO object failed round trip serialization-deserialization test, object type: " + objectType + ", object: " + candidatePojo, e);
}
}
static void validateObjectEquality(Object candidate, Object deserializedPojo) {
if (!(deserializedPojo.equals(candidate))) {
throw new IllegalStateException("The POJO after round trip serialization is not equal to the original POJO");
}
}
static void validateHashCodeEquality(Object candidate, Object deserializedPojo) {
if (!(deserializedPojo.hashCode() == candidate.hashCode())) {
throw new IllegalStateException("The POJO's hashCode after round trip serialization differs from its original hashCode");
}
}
}
| 8,484 | 44.132979 | 174 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/support/serialization/PojoSerializer.java | package com.googlecode.cqengine.persistence.support.serialization;
/**
* Interface implemented by serializers.
* The serializer for a particular object can be configured via the {@link PersistenceConfig} annotation.
* <p>
* Implementations of this interface are expected to provide a constructor which takes two arguments:
* (Class objectType, PersistenceConfig persistenceConfig).
* </p>
*
* @author npgall
*/
public interface PojoSerializer<O> {
byte[] serialize(O object);
O deserialize(byte[] bytes);
}
| 535 | 27.210526 | 105 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/onheap/OnHeapPersistence.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.persistence.onheap;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.support.ConcurrentOnHeapObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* Specifies that a collection or indexes should be persisted on-heap.
*
* @author niall.gallagher
*/
public class OnHeapPersistence<O, A extends Comparable<A>> implements Persistence<O, A> {
final SimpleAttribute<O, A> primaryKeyAttribute;
final int initialCapacity;
final float loadFactor;
final int concurrencyLevel;
public OnHeapPersistence() {
this(null, 16, 0.75F, 16);
}
public OnHeapPersistence(SimpleAttribute<O, A> primaryKeyAttribute) {
this(primaryKeyAttribute, 16, 0.75F, 16);
}
public OnHeapPersistence(SimpleAttribute<O, A> primaryKeyAttribute, int initialCapacity, float loadFactor, int concurrencyLevel) {
this.primaryKeyAttribute = primaryKeyAttribute;
this.initialCapacity = initialCapacity;
this.loadFactor = loadFactor;
this.concurrencyLevel = concurrencyLevel;
}
/**
* Returns true if the given index implements the {@link OnHeapTypeIndex} marker interface.
*/
@Override
public boolean supportsIndex(Index<O> index) {
return index instanceof OnHeapTypeIndex;
}
@Override
public ObjectStore<O> createObjectStore() {
return new ConcurrentOnHeapObjectStore<O>(initialCapacity, loadFactor, concurrencyLevel);
}
/**
* Currently does nothing in this implementation of {@link Persistence}.
*/
@Override
public void openRequestScopeResources(QueryOptions queryOptions) {
// No op
}
/**
* Currently does nothing in this implementation of {@link Persistence}.
*/
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
// No op
}
@Override
public SimpleAttribute<O, A> getPrimaryKeyAttribute() {
return primaryKeyAttribute;
}
/**
* Creates an {@link OnHeapPersistence} object which persists to the Java heap.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @return An {@link OnHeapPersistence} object which persists to the Java heap.
*/
public static <O, A extends Comparable<A>> OnHeapPersistence<O, A> onPrimaryKey(SimpleAttribute<O, A> primaryKeyAttribute) {
return new OnHeapPersistence<O, A>(primaryKeyAttribute);
}
/**
* Creates an {@link OnHeapPersistence} object which persists to the Java heap, without specifying a primary key.
* As such, this persistence implementation will be compatible with on-heap indexes only.
* <p/>
* This persistence will not work with composite persistence configurations, where some indexes are located on heap,
* and some off-heap etc. To use this persistence in those configurations, it is necessary to specify a primary
* key - see: {@link #onPrimaryKey(SimpleAttribute)}.
*
* @return An {@link OnHeapPersistence} object which persists to the Java heap, and which is not configured with
* a primary key.
*/
@SuppressWarnings("unchecked")
public static <O> OnHeapPersistence<O, ? extends Comparable> withoutPrimaryKey() {
return withoutPrimaryKey_Internal();
}
static <O, A extends Comparable<A>> OnHeapPersistence<O, A> withoutPrimaryKey_Internal() {
return new OnHeapPersistence<O, A>();
}
}
| 4,399 | 36.606838 | 134 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/persistence/offheap/OffHeapPersistence.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.persistence.offheap;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.sqlite.ConnectionManager;
import com.googlecode.cqengine.index.sqlite.RequestScopeConnectionManager;
import com.googlecode.cqengine.index.sqlite.SQLitePersistence;
import com.googlecode.cqengine.index.sqlite.support.DBQueries;
import com.googlecode.cqengine.index.sqlite.support.DBUtils;
import com.googlecode.cqengine.index.support.indextype.OffHeapTypeIndex;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.persistence.support.sqlite.LockReleasingConnection;
import com.googlecode.cqengine.persistence.support.sqlite.SQLiteObjectStore;
import com.googlecode.cqengine.persistence.support.sqlite.SQLiteOffHeapIdentityIndex;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.googlecode.cqengine.persistence.support.PersistenceFlags.READ_REQUEST;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.query.option.FlagsEnabled.isFlagEnabled;
/**
* Specifies that a collection or indexes should be persisted in native memory, within the JVM process but outside the
* Java heap.
* <p/>
* Each instance of this object specifies persistence to a different area of memory. So for example, to have an
* {@link com.googlecode.cqengine.IndexedCollection} and multiple indexes all persist to the same area of memory,
* configure them all to persist via the same instance of this object.
* <p/>
* <b>Garbage collection</b><br/>
* The memory allocated off-heap will be freed automatically when this object is garbage collected. So using off-heap
* memory does not require any special handling per-se. This object will be garbage collected when any
* {@link com.googlecode.cqengine.IndexedCollection} or indexes using this object for persistence (which hold a
* reference to this object internally) are garbage collected, and the application also releases any direct reference to
* this object which it might be holding.
* <p/>
* <b>Garbage collection - implementation details</b><br/>
* Internally this persistence strategy will open a connection to an in-memory SQLite database, and it will hold open
* a connection to that database until either this object is garbage collected, or the {@link #close()} method is
* called explicitly. (The {@link #finalize()} method of this object calls {@link #close()} automatically.)
* <p/>
* This object provides additional connections to the database on-demand; which the {@link IndexedCollection}
* and indexes will request on-the-fly as necessary whenever the collection or indexes need to be read or updated.
* SQLite automatically frees the memory used by an in-memory database when the last connection to the
* database is closed. So by holding open a connection, this object keeps the in-memory database alive between requests.
* <p/>
* In terms of memory usage, the application can treat this as a very large object. The memory will be freed when this
* object is garbage collected, but the application can also free memory sooner by calling {@link #close()}, but
* this is optional.
* <p/>
* <b>Note on Concurrency</b><br/>
* Note that this persistence implementation (backed by an off-heap in-memory SQLite database) has more restrictive
* support for concurrency than other persistence implementations. This is because the concurrency support in SQLite is
* more limited in its in-memory mode than in its disk-based mode.
* <p/>
* Concurrent reads are supported when there are no ongoing writes, but writes are performed sequentially and they
* block all concurrent reads. Essentially the concurrency support is equivalent to that afforded by a
* {@link ReadWriteLock}.
* <p/>
* As a workaround, any applications requiring more concurrency with an in-memory persistence, for example concurrent
* reads and concurrent writes which don't block each other, could consider using {@link DiskPersistence} instead with
* the persistence file located on a ram disk.
*
* @author niall.gallagher
*/
public class OffHeapPersistence<O, A extends Comparable<A>> implements SQLitePersistence<O, A>, Closeable {
static final AtomicInteger INSTANCE_ID_GENERATOR = new AtomicInteger();
final SimpleAttribute<O, A> primaryKeyAttribute;
final String instanceName;
final SQLiteDataSource sqLiteDataSource;
// Note we don't configure a default busy_wait property, because SQLite's in-memory database does not support it.
static final Properties DEFAULT_PROPERTIES = new Properties();
// A connection which we keep open to prevent SQLite from freeing the in-memory database
// until this object is garbage-collected, or close() is called explicitly on this object...
volatile Connection persistentConnection;
volatile boolean closed = false;
protected OffHeapPersistence(SimpleAttribute<O, A> primaryKeyAttribute, Properties overrideProperties) {
Properties effectiveProperties = new Properties(DEFAULT_PROPERTIES);
effectiveProperties.putAll(overrideProperties);
SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
String instanceName = "cqengine_" + INSTANCE_ID_GENERATOR.incrementAndGet();
sqLiteDataSource.setUrl("jdbc:sqlite:file:" + instanceName + "?mode=memory&cache=shared");
this.primaryKeyAttribute = primaryKeyAttribute;
this.instanceName = instanceName;
this.sqLiteDataSource = sqLiteDataSource;
this.persistentConnection = getConnectionInternal(null, noQueryOptions());
}
@Override
public SimpleAttribute<O, A> getPrimaryKeyAttribute() {
return primaryKeyAttribute;
}
public String getInstanceName() {
return instanceName;
}
final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
// Wraps access to the SQLite in-memory database in a read-write lock.
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
// Acquire a read lock IFF the READ_REQUEST flag has been set, otherwise acquire a write lock by default...
final Lock connectionLock = isFlagEnabled(queryOptions, READ_REQUEST)
? readWriteLock.readLock() : readWriteLock.writeLock();
connectionLock.lock();
Connection connection;
try {
connection = getConnectionInternal(index, queryOptions);
}
catch (RuntimeException e) {
connectionLock.unlock();
throw e;
}
return LockReleasingConnection.wrap(connection, connectionLock);
}
protected Connection getConnectionInternal(Index<?> index, QueryOptions queryOptions) {
if (closed) {
throw new IllegalStateException("OffHeapPersistence has been closed: " + this.toString());
}
try {
return sqLiteDataSource.getConnection();
}
catch (SQLException e) {
throw new IllegalStateException("Failed to open SQLite connection for memory instance: " + instanceName, e);
}
}
/**
* @param index The {@link Index} for which a connection is required.
* @return True if the given index is an {@link OffHeapTypeIndex}. Otherwise false.
*/
@Override
public boolean supportsIndex(Index<O> index) {
return index instanceof OffHeapTypeIndex;
}
@Override
public void close() {
DBUtils.closeQuietly(persistentConnection);
this.persistentConnection = null;
this.closed = true;
}
@Override
public long getBytesUsed() {
Connection connection = null;
try {
connection = getConnectionInternal(null, noQueryOptions());
return DBQueries.getDatabaseSize(connection);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
public void compact() {
Connection connection = null;
try {
connection = getConnectionInternal(null, noQueryOptions());
DBQueries.compactDatabase(connection);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
public void expand(long numBytes) {
Connection connection = null;
try {
connection = getConnectionInternal(null, noQueryOptions());
DBQueries.expandDatabase(connection, numBytes);
}
finally {
DBUtils.closeQuietly(connection);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
close();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof OffHeapPersistence)) {
return false;
}
OffHeapPersistence<?, ?> that = (OffHeapPersistence<?, ?>) o;
return primaryKeyAttribute.equals(that.primaryKeyAttribute) && instanceName.equals(that.instanceName);
}
@Override
public int hashCode() {
int result = primaryKeyAttribute.hashCode();
result = 31 * result + instanceName.hashCode();
return result;
}
@Override
public String toString() {
return "OffHeapPersistence{" +
"primaryKeyAttribute=" + primaryKeyAttribute +
", instanceName='" + instanceName + '\'' +
'}';
}
@Override
public SQLiteObjectStore<O, A> createObjectStore() {
return new SQLiteObjectStore<O, A>(this);
}
@Override
public SQLiteOffHeapIdentityIndex<A, O> createIdentityIndex() {
return SQLiteOffHeapIdentityIndex.onAttribute(primaryKeyAttribute);
}
/**
* Creates a new {@link RequestScopeConnectionManager} and adds it to the given query options with key
* {@link ConnectionManager}, if an only if no object with that key is already in the query options.
* This allows the application to supply its own implementation of {@link ConnectionManager} to override the default
* if necessary.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void openRequestScopeResources(QueryOptions queryOptions) {
if (queryOptions.get(ConnectionManager.class) == null) {
queryOptions.put(ConnectionManager.class, new RequestScopeConnectionManager(this));
}
}
/**
* Closes a {@link RequestScopeConnectionManager} if it is present in the given query options with key
* {@link ConnectionManager}.
*
* @param queryOptions The query options supplied with the request into CQEngine.
*/
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
ConnectionManager connectionManager = queryOptions.get(ConnectionManager.class);
if (connectionManager instanceof RequestScopeConnectionManager) {
((RequestScopeConnectionManager) connectionManager).close();
queryOptions.remove(ConnectionManager.class);
}
}
/**
* Creates an {@link OffHeapPersistence} object which persists to native memory, within the JVM process but outside
* the Java heap.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @return An {@link OffHeapPersistence} object which persists to native memory
*/
public static <O, A extends Comparable<A>> OffHeapPersistence<O, A> onPrimaryKey(SimpleAttribute<O, A> primaryKeyAttribute) {
return OffHeapPersistence.onPrimaryKeyWithProperties(primaryKeyAttribute, new Properties());
}
/**
* Creates an {@link OffHeapPersistence} object which persists to native memory, within the JVM process but outside
* the Java heap.
*
* @param primaryKeyAttribute An attribute which returns the primary key of objects in the collection
* @param overrideProperties Optional properties to override default settings (can be empty to use all default
* settings, but cannot be null)
* @return An {@link OffHeapPersistence} object which persists to native memory
*/
public static <O, A extends Comparable<A>> OffHeapPersistence<O, A> onPrimaryKeyWithProperties(SimpleAttribute<O, A> primaryKeyAttribute, Properties overrideProperties) {
return new OffHeapPersistence<O, A>(primaryKeyAttribute, overrideProperties);
}
}
| 13,770 | 42.856688 | 174 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/Query.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.query;
import com.googlecode.cqengine.query.logical.LogicalQuery;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.SimpleQuery;
/**
* An interface implemented by all {@link Query} subclasses, including those descending from
* {@link SimpleQuery}, {@link ComparativeQuery} and {@link LogicalQuery}.
*
* @author ngallagher
* @since 2012-04-30 16:52
*/
public interface Query<O> {
/**
* Tests an object to see if it matches the assertion represented by the query.
*
* @param object The object to test
* @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 True if the object matches the query, false if it does not
*/
boolean matches(O object, QueryOptions queryOptions);
}
| 1,559 | 37.04878 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/QueryFactory.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.query;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.attribute.support.*;
import com.googlecode.cqengine.entity.MapEntity;
import com.googlecode.cqengine.entity.PrimaryKeyedMapEntity;
import com.googlecode.cqengine.query.comparative.LongestPrefix;
import com.googlecode.cqengine.query.comparative.Max;
import com.googlecode.cqengine.query.comparative.Min;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.Not;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.query.option.*;
import com.googlecode.cqengine.query.simple.*;
import net.jodah.typetools.TypeResolver;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Pattern;
/**
* A static factory for creating {@link Query} objects and its descendants.
*
* @author Niall Gallagher
*/
public class QueryFactory {
/**
* Private constructor, not used.
*/
QueryFactory() {
}
/**
* Creates an {@link Equal} query which asserts that an attribute equals a certain value.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link Equal} query
*/
public static <O, A> Equal<O, A> equal(Attribute<O, A> attribute, A attributeValue) {
return new Equal<O, A>(attribute, attributeValue);
}
/**
* Creates a {@link LessThan} query which asserts that an attribute is less than or equal to an upper bound
* (i.e. less than, inclusive).
*
* @param attribute The attribute to which the query refers
* @param attributeValue The upper bound to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link LessThan} query
*/
public static <O, A extends Comparable<A>> LessThan<O, A> lessThanOrEqualTo(Attribute<O, A> attribute, A attributeValue) {
return new LessThan<O, A>(attribute, attributeValue, true);
}
/**
* Creates a {@link LessThan} query which asserts that an attribute is less than (but not equal to) an upper
* bound (i.e. less than, exclusive).
*
* @param attribute The attribute to which the query refers
* @param attributeValue The upper bound to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link LessThan} query
*/
public static <O, A extends Comparable<A>> LessThan<O, A> lessThan(Attribute<O, A> attribute, A attributeValue) {
return new LessThan<O, A>(attribute, attributeValue, false);
}
/**
* Creates a {@link GreaterThan} query which asserts that an attribute is greater than or equal to a lower
* bound (i.e. greater than, inclusive).
*
* @param attribute The attribute to which the query refers
* @param attributeValue The lower bound to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link GreaterThan} query
*/
public static <O, A extends Comparable<A>> GreaterThan<O, A> greaterThanOrEqualTo(Attribute<O, A> attribute, A attributeValue) {
return new GreaterThan<O, A>(attribute, attributeValue, true);
}
/**
* Creates a {@link LessThan} query which asserts that an attribute is greater than (but not equal to) a lower
* bound (i.e. greater than, exclusive).
*
* @param attribute The attribute to which the query refers
* @param attributeValue The lower bound to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link GreaterThan} query
*/
public static <O, A extends Comparable<A>> GreaterThan<O, A> greaterThan(Attribute<O, A> attribute, A attributeValue) {
return new GreaterThan<O, A>(attribute, attributeValue, false);
}
/**
* Creates a {@link Between} query which asserts that an attribute is between a lower and an upper bound.
*
* @param attribute The attribute to which the query refers
* @param lowerValue The lower bound to be asserted by the query
* @param lowerInclusive Whether the lower bound is inclusive or not (true for "greater than or equal to")
* @param upperValue The upper bound to be asserted by the query
* @param upperInclusive Whether the upper bound is inclusive or not (true for "less than or equal to")
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link GreaterThan} query
*/
public static <O, A extends Comparable<A>> Between<O, A> between(Attribute<O, A> attribute, A lowerValue, boolean lowerInclusive, A upperValue, boolean upperInclusive) {
return new Between<O, A>(attribute, lowerValue, lowerInclusive, upperValue, upperInclusive);
}
/**
* Creates a {@link Between} query which asserts that an attribute is between a lower and an upper bound,
* inclusive.
*
* @param attribute The attribute to which the query refers
* @param lowerValue The lower bound to be asserted by the query
* @param upperValue The upper bound to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link GreaterThan} query
*/
public static <O, A extends Comparable<A>> Between<O, A> between(Attribute<O, A> attribute, A lowerValue, A upperValue) {
return new Between<O, A>(attribute, lowerValue, true, upperValue, true);
}
/**
* <p> Creates a {@link In} query which asserts that an attribute has at least one value matching any value in a set of values.
* <p> If the given attribute is a {@link SimpleAttribute}, this method will set a hint in the query to
* indicate that results for the child queries will inherently be disjoint and so will not require deduplication.
*
* @param attribute The attribute to which the query refers
* @param attributeValues The set of values to match
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link In} query
*/
public static <O, A> Query<O> in(Attribute<O, A> attribute, A... attributeValues) {
return in(attribute, Arrays.asList(attributeValues));
}
/**
* <p> Creates a {@link In} query which asserts that an attribute has at least one value matching any value in a set of values.
* <p> If the given attribute is a {@link SimpleAttribute}, this method will set a hint in the query to
* indicate that results for the child queries will inherently be disjoint and so will not require deduplication.
*
* @param attribute The attribute to which the query refers
* @param attributeValues TThe set of values to match
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link In} query
*/
public static <O, A> Query<O> in(Attribute<O, A> attribute, Collection<A> attributeValues) {
return in(attribute, attribute instanceof SimpleAttribute, attributeValues);
}
/**
* <p> Creates a {@link In} query which asserts that an attribute has at least one value matching any value in a set of values.
* <p> Note that <b><u>this can result in more efficient queries</u></b> than several {@link Equal} queries "OR"ed together using other means.
*
* @param attribute The attribute to which the query refers
* @param disjoint Set it to {@code true} if deduplication is not necessary because the results are disjoint. Set it to {@code false} deduplication is needed
* @param attributeValues The set of values to match
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link In} query
*/
public static <O, A> Query<O> in(Attribute<O, A> attribute, boolean disjoint, Collection<A> attributeValues) {
int n = attributeValues.size();
switch (n) {
case 0:
return none(attribute.getObjectType());
case 1:
A singleValue = attributeValues.iterator().next();
return equal(attribute, singleValue);
default:
// Copy the values into a Set if necessary...
Set<A> values = (attributeValues instanceof Set ? (Set<A>)attributeValues : new HashSet<A>(attributeValues));
return new In<O, A>(attribute, disjoint, values);
}
}
/**
* Creates a {@link StringStartsWith} query which asserts that an attribute starts with a certain string fragment.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringStartsWith} query
*/
public static <O, A extends CharSequence> StringStartsWith<O, A> startsWith(Attribute<O, A> attribute, A attributeValue) {
return new StringStartsWith<O, A>(attribute, attributeValue);
}
/**
* Creates a {@link LongestPrefix} query which finds the object with the longest matching prefix.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link LongestPrefix} query
*/
public static <O, A extends CharSequence> LongestPrefix<O, A> longestPrefix(Attribute<O, A> attribute, A attributeValue) {
return new LongestPrefix<>(attribute, attributeValue);
}
/**
* Creates a {@link Min} query which finds the object(s) which have the minimum value of the given attribute.
*
* @param attribute The attribute to which the query refers
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link Min} query
*/
public static <O, A extends Comparable<A>> Min<O, A> min(Attribute<O, A> attribute) {
return new Min<>(attribute);
}
/**
* Creates a {@link Max} query which finds the object(s) which have the maximum value of the given attribute.
*
* @param attribute The attribute to which the query refers
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return A {@link Max} query
*/
public static <O, A extends Comparable<A>> Max<O, A> max(Attribute<O, A> attribute) {
return new Max<>(attribute);
}
/**
* Creates a {@link StringIsPrefixOf} query which finds all attributes that are prefixes of a certain string
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringIsPrefixOf} query
*/
public static <O, A extends CharSequence> StringIsPrefixOf<O, A> isPrefixOf(Attribute<O, A> attribute, A attributeValue) {
return new StringIsPrefixOf<>(attribute, attributeValue);
}
/**
* Creates a {@link StringEndsWith} query which asserts that an attribute ends with a certain string fragment.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringEndsWith} query
*/
public static <O, A extends CharSequence> StringEndsWith<O, A> endsWith(Attribute<O, A> attribute, A attributeValue) {
return new StringEndsWith<O, A>(attribute, attributeValue);
}
/**
* Creates a {@link StringContains} query which asserts that an attribute contains with a certain string fragment.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringContains} query
*/
public static <O, A extends CharSequence> StringContains<O, A> contains(Attribute<O, A> attribute, A attributeValue) {
return new StringContains<O, A>(attribute, attributeValue);
}
/**
* Creates a {@link StringIsContainedIn} query which asserts that an attribute is contained in a certain string
* fragment.
*
* @param attribute The attribute to which the query refers
* @param attributeValue The value to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringStartsWith} query
*/
public static <O, A extends CharSequence> StringIsContainedIn<O, A> isContainedIn(Attribute<O, A> attribute, A attributeValue) {
return new StringIsContainedIn<O, A>(attribute, attributeValue);
}
/**
* Creates a {@link StringMatchesRegex} query which asserts that an attribute's value matches a regular expression.
* <p/>
* To accelerate {@code matchesRegex(...)} queries, add a Standing Query Index on {@code matchesRegex(...)}.
*
* @param attribute The attribute to which the query refers
* @param regexPattern The regular expression pattern to be asserted by the query
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringStartsWith} query
*/
public static <O, A extends CharSequence> StringMatchesRegex<O, A> matchesRegex(Attribute<O, A> attribute, Pattern regexPattern) {
return new StringMatchesRegex<O, A>(attribute, regexPattern);
}
/**
* Creates a {@link StringMatchesRegex} query which asserts that an attribute's value matches a regular expression.
* <p/>
* To accelerate {@code matchesRegex(...)} queries, add a Standing Query Index on {@code matchesRegex(...)}.
*
* @param attribute The attribute to which the query refers
* @param regex The regular expression to be asserted by the query (this will be compiled via {@link Pattern#compile(String)})
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link StringStartsWith} query
*/
public static <O, A extends CharSequence> StringMatchesRegex<O, A> matchesRegex(Attribute<O, A> attribute, String regex) {
return new StringMatchesRegex<O, A>(attribute, Pattern.compile(regex));
}
/**
* Creates an {@link Has} query which asserts that an attribute has a value (is not null).
* <p/>
* To accelerate {@code has(...)} queries, add a Standing Query Index on {@code has(...)}.
* <p/>
* To assert that an attribute does <i>not</i> have a value (is null), use <code>not(has(...))</code>.
* <p/>
* To accelerate <code>not(has(...))</code> queries, add a Standing Query Index on <code>not(has(...))</code>.
*
* @param attribute The attribute to which the query refers
* @param <A> The type of the attribute
* @param <O> The type of the object containing the attribute
* @return An {@link Has} query
*/
public static <O, A> Has<O, A> has(Attribute<O, A> attribute) {
return new Has<O, A>(attribute);
}
/**
* Creates an {@link And} query, representing a logical AND on child queries, which when evaluated yields the
* <u>set intersection</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical AND
* @param query2 The second child query to be connected via a logical AND
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link And} query, representing a logical AND on child queries
*/
public static <O> And<O> and(Query<O> query1, Query<O> query2) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2);
return new And<O>(queries);
}
/**
* Creates an {@link And} query, representing a logical AND on child queries, which when evaluated yields the
* <u>set intersection</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical AND
* @param query2 The second child query to be connected via a logical AND
* @param additionalQueries Additional child queries to be connected via a logical AND
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link And} query, representing a logical AND on child queries
*/
public static <O> And<O> and(Query<O> query1, Query<O> query2, Query<O>... additionalQueries) {
Collection<Query<O>> queries = new ArrayList<Query<O>>(2 + additionalQueries.length);
queries.add(query1);
queries.add(query2);
Collections.addAll(queries, additionalQueries);
return new And<O>(queries);
}
/**
* Creates an {@link And} query, representing a logical AND on child queries, which when evaluated yields the
* <u>set intersection</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical AND
* @param query2 The second child query to be connected via a logical AND
* @param additionalQueries Additional child queries to be connected via a logical AND
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link And} query, representing a logical AND on child queries
*/
public static <O> And<O> and(Query<O> query1, Query<O> query2, Collection<Query<O>> additionalQueries) {
Collection<Query<O>> queries = new ArrayList<Query<O>>(2 + additionalQueries.size());
queries.add(query1);
queries.add(query2);
queries.addAll(additionalQueries);
return new And<O>(queries);
}
/**
* Creates an {@link Or} query, representing a logical OR on child queries, which when evaluated yields the
* <u>set union</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical OR
* @param query2 The second child query to be connected via a logical OR
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link Or} query, representing a logical OR on child queries
*/
public static <O> Or<O> or(Query<O> query1, Query<O> query2) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2);
return new Or<O>(queries);
}
/**
* Creates an {@link Or} query, representing a logical OR on child queries, which when evaluated yields the
* <u>set union</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical OR
* @param query2 The second child query to be connected via a logical OR
* @param additionalQueries Additional child queries to be connected via a logical OR
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link Or} query, representing a logical OR on child queries
*/
public static <O> Or<O> or(Query<O> query1, Query<O> query2, Query<O>... additionalQueries) {
Collection<Query<O>> queries = new ArrayList<Query<O>>(2 + additionalQueries.length);
queries.add(query1);
queries.add(query2);
Collections.addAll(queries, additionalQueries);
return new Or<O>(queries);
}
/**
* Creates an {@link Or} query, representing a logical OR on child queries, which when evaluated yields the
* <u>set union</u> of the result sets from child queries.
*
* @param query1 The first child query to be connected via a logical OR
* @param query2 The second child query to be connected via a logical OR
* @param additionalQueries Additional child queries to be connected via a logical OR
* @param <O> The type of the object containing attributes to which child queries refer
* @return An {@link Or} query, representing a logical OR on child queries
*/
public static <O> Or<O> or(Query<O> query1, Query<O> query2, Collection<Query<O>> additionalQueries) {
Collection<Query<O>> queries = new ArrayList<Query<O>>(2 + additionalQueries.size());
queries.add(query1);
queries.add(query2);
queries.addAll(additionalQueries);
return new Or<O>(queries);
}
/**
* Creates a {@link Not} query, representing a logical negation of a child query, which when evaluated
* yields the <u>set complement</u> of the result set from the child query.
*
* @param query The child query to be logically negated
* @param <O> The type of the object containing attributes to which child queries refer
* @return A {@link Not} query, representing a logical negation of a child query
*/
public static <O> Not<O> not(Query<O> query) {
return new Not<O>(query);
}
/**
* Creates a query supporting the equivalent of SQL <code>EXISTS</code>.
* <p/>
* Asserts that objects in a local {@code IndexedCollection} match objects in a foreign collection,
* based on a key attribute of local objects being equal to a key attribute of the foreign objects.
* This query can be performed on the local collection, supplying the foreign collection and the
* relevant attributes, as arguments to the query.
* <p/>
* This supports the SQL equivalent of:<br/>
* <pre>
* SELECT * From LocalCollection
* WHERE EXISTS (
* SELECT * FROM ForeignCollection
* WHERE LocalCollection.localAttribute = ForeignCollection.foreignAttribute
* )
* </pre>
*
* @param foreignCollection The collection of foreign objects
* @param localKeyAttribute An attribute of the local object
* @param foreignKeyAttribute An attribute of objects in the foreign collection
* @param <O> The type of the local object
* @param <F> The type of the foreign objects
* @param <A> The type of the common attributes
* @return A query which checks if the local object matches any objects in the foreign collection based on the given
* key attributes being equal
*/
public static <O, F, A> Query<O> existsIn(final IndexedCollection<F> foreignCollection, final Attribute<O, A> localKeyAttribute, final Attribute<F, A> foreignKeyAttribute) {
return new ExistsIn<O, F, A>(foreignCollection, localKeyAttribute, foreignKeyAttribute);
}
/**
* Creates a query supporting the equivalent of SQL <code>EXISTS</code>,
* with some additional restrictions on foreign objects.
* <p/>
* Asserts that objects in a local {@code IndexedCollection} match objects in a foreign collection,
* based on a key attribute of local objects being equal to a key attribute of the foreign objects,
* AND objects in the foreign collection matching some additional criteria.
* This query can be performed on the local collection, supplying the foreign collection and the
* relevant attributes, as arguments to the query.
* <p/>
* This supports the SQL equivalent of:<br/>
* <pre>
* SELECT * From LocalCollection
* WHERE EXISTS (
* SELECT * FROM ForeignCollection
* WHERE LocalCollection.localAttribute = ForeignCollection.foreignAttribute
* AND ([AND|OR|NOT](ForeignCollection.someOtherAttribute = x) ...)
* )
* </pre>
* @param foreignCollection The collection of foreign objects
* @param localKeyAttribute An attribute of the local object
* @param foreignKeyAttribute An attribute of objects in the foreign collection
* @param foreignRestrictions A query specifying additional restrictions on foreign objects
* @param <O> The type of the local object
* @param <F> The type of the foreign objects
* @param <A> The type of the common attributes
* @return A query which checks if the local object matches any objects in the foreign collection based on the given
* key attributes being equal
*/
public static <O, F, A> Query<O> existsIn(final IndexedCollection<F> foreignCollection, final Attribute<O, A> localKeyAttribute, final Attribute<F, A> foreignKeyAttribute, final Query<F> foreignRestrictions) {
return new ExistsIn<O, F, A>(foreignCollection, localKeyAttribute, foreignKeyAttribute, foreignRestrictions);
}
/**
* Creates a query which matches all objects in the collection.
* <p/>
* This is equivalent to a literal boolean 'true'.
*
* @param <O> The type of the objects in the collection
* @return A query which matches all objects in the collection
*/
public static <O> Query<O> all(Class<O> objectType) {
return new All<O>(objectType);
}
/**
* Creates a query which matches no objects in the collection.
* <p/>
* This is equivalent to a literal boolean 'false'.
*
* @param <O> The type of the objects in the collection
* @return A query which matches no objects in the collection
*/
public static <O> Query<O> none(Class<O> objectType) {
return new None<O>(objectType);
}
/**
* Creates an {@link OrderByOption} query option, encapsulating the given list of {@link AttributeOrder} objects
* which pair an attribute with a preference to sort results by that attribute in either ascending or descending
* order.
*
* @param attributeOrders The list of attribute orders by which objects should be sorted
* @param <O> The type of the object containing the attributes
* @return An {@link OrderByOption} query option, requests results to be sorted in the given order
*/
public static <O> OrderByOption<O> orderBy(List<AttributeOrder<O>> attributeOrders) {
return new OrderByOption<O>(attributeOrders);
}
/**
* Creates an {@link OrderByOption} query option, encapsulating the given list of {@link AttributeOrder} objects
* which pair an attribute with a preference to sort results by that attribute in either ascending or descending
* order.
*
* @param attributeOrders The list of attribute orders by which objects should be sorted
* @param <O> The type of the object containing the attributes
* @return An {@link OrderByOption} query option, requests results to be sorted in the given order
*/
public static <O> OrderByOption<O> orderBy(AttributeOrder<O>... attributeOrders) {
return new OrderByOption<O>(Arrays.asList(attributeOrders));
}
/**
* Creates an {@link AttributeOrder} object which pairs an attribute with a preference to sort results by that
* attribute in ascending order. These {@code AttributeOrder} objects can then be passed to the
* {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} method to create a query option which
* sorts results by the indicated attributes and ascending/descending preferences.
*
* @param attribute An attribute to sort by
* @param <O> The type of the object containing the attributes
* @return An {@link AttributeOrder} object, encapsulating the attribute and a preference to sort results by it
* in ascending order
*/
public static <O> AttributeOrder<O> ascending(Attribute<O, ? extends Comparable> attribute) {
return new AttributeOrder<O>(attribute, false);
}
/**
* Creates an {@link AttributeOrder} object which pairs an attribute with a preference to sort results by that
* attribute in descending order. These {@code AttributeOrder} objects can then be passed to the
* {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} method to create a query option which
* sorts results by the indicated attributes and ascending/descending preferences.
*
* @param attribute An attribute to sort by
* @param <O> The type of the object containing the attributes
* @return An {@link AttributeOrder} object, encapsulating the attribute and a preference to sort results by it
* in descending order
*/
public static <O> AttributeOrder<O> descending(Attribute<O, ? extends Comparable> attribute) {
return new AttributeOrder<O>(attribute, true);
}
/**
* Creates a {@link DeduplicationOption} query option, encapsulating a given {@link DeduplicationStrategy}, which
* when supplied to the query engine requests it to eliminate duplicates objects from the results returned using
* the strategy indicated.
*
* @param deduplicationStrategy The deduplication strategy the query engine should use
* @return A {@link DeduplicationOption} query option, requests duplicate objects to be eliminated from results
*/
public static DeduplicationOption deduplicate(DeduplicationStrategy deduplicationStrategy) {
return new DeduplicationOption(deduplicationStrategy);
}
/**
* Creates a {@link IsolationOption} query option, encapsulating a given {@link IsolationLevel}, which
* when supplied to the query engine requests that level of transaction isolation.
*
* @param isolationLevel The transaction isolation level to request
* @return An {@link IsolationOption} query option
*/
public static IsolationOption isolationLevel(IsolationLevel isolationLevel) {
return new IsolationOption(isolationLevel);
}
/**
* Creates an {@link ArgumentValidationOption} query option, encapsulating a given
* {@link ArgumentValidationStrategy}, which when supplied to the query engine requests that some argument
* validation may be disabled (or enabled) for performance or reliability reasons.
*
* @param strategy The argument validation strategy to request
* @return An {@link ArgumentValidationOption} query option
*/
public static ArgumentValidationOption argumentValidation(ArgumentValidationStrategy strategy) {
return new ArgumentValidationOption(strategy);
}
/**
* A convenience method to encapsulate several objects together as {@link com.googlecode.cqengine.query.option.QueryOptions},
* where the class of the object will become its key in the QueryOptions map.
*
* @param queryOptions The objects to encapsulate as QueryOptions
* @return A {@link QueryOptions} object
*/
public static QueryOptions queryOptions(Object... queryOptions) {
return queryOptions(Arrays.asList(queryOptions));
}
/**
* A convenience method to encapsulate a collection of objects as {@link com.googlecode.cqengine.query.option.QueryOptions},
* where the class of the object will become its key in the QueryOptions map.
*
* @param queryOptions The objects to encapsulate as QueryOptions
* @return A {@link QueryOptions} object
*/
public static QueryOptions queryOptions(Collection<Object> queryOptions) {
QueryOptions resultOptions = new QueryOptions();
for (Object queryOption : queryOptions) {
resultOptions.put(queryOption.getClass(), queryOption);
}
return resultOptions;
}
/**
* A convenience method to encapsulate an empty collection of objects as
* {@link com.googlecode.cqengine.query.option.QueryOptions}.
*
* @return A {@link QueryOptions} object
*/
public static QueryOptions noQueryOptions() {
return new QueryOptions();
}
/**
* Creates a {@link FlagsEnabled} object which may be added to query options.
* This object encapsulates arbitrary "flag" objects which are said to be "enabled".
* <p/>
* Some components such as indexes allow their default behaviour to be overridden by
* setting flags in this way.
*
* @param flags Arbitrary objects which represent flags which may be interpreted by indexes etc.
* @return A populated {@link FlagsEnabled} object which may be added to query options
*/
public static FlagsEnabled enableFlags(Object... flags) {
FlagsEnabled result = new FlagsEnabled();
for (Object flag: flags) {
result.add(flag);
}
return result;
}
/**
* Creates a {@link FlagsDisabled} object which may be added to query options.
* This object encapsulates arbitrary "flag" objects which are said to be "disabled".
* <p/>
* Some components such as indexes allow their default behaviour to be overridden by
* setting flags in this way.
*
* @param flags Arbitrary objects which represent flags which may be interpreted by indexes etc.
* @return A populated {@link FlagsDisabled} object which may be added to query options
*/
public static FlagsDisabled disableFlags(Object... flags) {
FlagsDisabled result = new FlagsDisabled();
for (Object flag: flags) {
result.add(flag);
}
return result;
}
/**
* Creates a {@link Thresholds} object which may be added to query options.
* It encapsulates individual {@link Threshold} objects which are to override default values for thresholds which
* can be set to tune query performance.
*
* @param thresholds Encapsulates Double values relating to thresholds to be overridden
* @return A populated {@link Thresholds} object which may be added to query options
*/
public static Thresholds applyThresholds(Threshold... thresholds) {
return new Thresholds(Arrays.asList(thresholds));
}
/**
* Creates a {@link Threshold} object which may be added to query options.
*
* @param key The key of the threshold value to set
* @param value The value to set for the threshold
* @return A populated {@link Threshold} object encapsulating the given arguments
*/
public static Threshold threshold(Object key, Double value) {
return new Threshold(key, value);
}
/**
* Creates a {@link SelfAttribute} for the given object.
*
* @param objectType The type of object
* @return a {@link SelfAttribute} for the given object
*/
public static <O> SelfAttribute<O> selfAttribute(Class<O> objectType) {
return new SelfAttribute<O>(objectType);
}
/**
* Creates a {@link SimpleNullableMapAttribute} which retrieves the value for the given key from an
* {@link IndexedCollection} of {@link Map} objects.
*
* @param mapKey The map key
* @param mapValueType The type of the value stored for the given key
* @param <K> The type of the map key
* @param <A> The type of the resulting attribute; which is the type of the value stored
* @return a {@link SimpleNullableMapAttribute} which retrieves the value for the given key from a map
*/
public static <K, A> Attribute<Map, A> mapAttribute(K mapKey, Class<A> mapValueType) {
return new SimpleNullableMapAttribute<K, A>(mapKey, mapValueType);
}
/**
* Wraps the given Map in a {@link MapEntity}, which can improve its performance when used in an IndexedCollection.
* If the given Map already is a {@link MapEntity}, the same object will be returned.
*
* @param map The map to wrap
* @return a {@link MapEntity} wrapping the given map
*/
public static Map mapEntity(Map map) {
return map instanceof MapEntity ? map : new MapEntity(map);
}
/**
* Wraps the given Map in a {@link PrimaryKeyedMapEntity}, which can improve its performance when used in an
* IndexedCollection.
* If the given Map already is a {@link PrimaryKeyedMapEntity}, the same object will be returned.
*
* @param map The map to wrap
* @param primaryKey The key of the entry in the map to be used as a primary key
* @return a {@link PrimaryKeyedMapEntity} wrapping the given map
*/
public static Map primaryKeyedMapEntity(Map map, Object primaryKey) {
return map instanceof PrimaryKeyedMapEntity ? map : new PrimaryKeyedMapEntity(map, primaryKey);
}
/**
* Returns an {@link OrderMissingLastAttribute} which which can be used in an {@link #orderBy(AttributeOrder)}
* clause to specify that objects which do not have values for the given delegate attribute should be returned after
* objects which do have values for the attribute.
* <p/>
* Essentially, this attribute can be used to order results based on whether a {@link #has(Attribute)} query on the
* delegate attribute would return true or false. See documentation in {@link OrderMissingLastAttribute} for more
* details.
*
* @param delegateAttribute The attribute which may or may not return values, based on which results should be
* ordered
* @param <O> The type of the object containing the attribute
* @return An {@link OrderMissingLastAttribute} which orders objects with values before those without values
*/
@SuppressWarnings("unchecked")
public static <O> OrderMissingLastAttribute<O> missingLast(Attribute<O, ? extends Comparable> delegateAttribute) {
return new OrderMissingLastAttribute<O>(delegateAttribute);
}
/**
* Returns an {@link OrderMissingFirstAttribute} which which can be used in an {@link #orderBy(AttributeOrder)}
* clause to specify that objects which do not have values for the given delegate attribute should be returned
* before objects which do have values for the attribute.
* <p/>
* Essentially, this attribute can be used to order results based on whether a {@link #has(Attribute)} query on the
* delegate attribute would return true or false. See documentation in {@link OrderMissingFirstAttribute} for more
* details.
*
* @param delegateAttribute The attribute which may or may not return values, based on which results should be
* ordered
* @param <O> The type of the object containing the attribute
* @return An {@link OrderMissingFirstAttribute} which orders objects without values before those with values
*/
@SuppressWarnings("unchecked")
public static <O> OrderMissingFirstAttribute<O> missingFirst(Attribute<O, ? extends Comparable> delegateAttribute) {
return new OrderMissingFirstAttribute<O>(delegateAttribute);
}
/**
* Creates a {@link StandingQueryAttribute} based on the given query. An index can then be built on this attribute,
* and it will be able to to answer the query in constant time complexity O(1).
*
* @param standingQuery The standing query to encapsulate
* @return a {@link StandingQueryAttribute} encapsulating the given query
*/
public static <O> StandingQueryAttribute<O> forStandingQuery(Query<O> standingQuery) {
return new StandingQueryAttribute<O>(standingQuery);
}
/**
* Creates a {@link StandingQueryAttribute} which returns true if the given attribute does not have values for
* an object.
* <p/>
* An index can then be built on this attribute, and it will be able to to answer a <code>not(has(attribute))</code>
* query, returning objects which do not have values for that attribute, in constant time complexity O(1).
*
* @param attribute The attribute which will be used in a <code>not(has(attribute))</code> query
* @return a {@link StandingQueryAttribute} which returns true if the given attribute does not have values for
* an object
*/
public static <O, A> StandingQueryAttribute<O> forObjectsMissing(Attribute<O, A> attribute) {
return forStandingQuery(not(has(attribute)));
}
// ***************************************************************************************************************
// Factory methods to create attributes from lambda expressions...
// ***************************************************************************************************************
/**
* Creates a {@link SimpleAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
* <p/>
* This is a convenience method, which delegates to {@link #attribute(String, SimpleFunction)},
* supplying {@code function.getClass().getName()} as the name of the attribute.
*
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleAttribute<O, A> attribute(SimpleFunction<O, A> function) {
return attribute(function.getClass().getName(), function);
}
/**
* Creates a {@link SimpleAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
*
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleAttribute<O, A> attribute(String attributeName, SimpleFunction<O, A> function) {
FunctionGenericTypes<O, A> resolved = resolveSimpleFunctionGenericTypes(function.getClass());
return attribute(resolved.objectType, resolved.attributeType, attributeName, function);
}
/**
* Creates a {@link SimpleAttribute} from the given function or lambda expression,
* allowing the generic types of the attribute to be specified explicitly.
*
* @param objectType The type of the object containing the attribute
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleAttribute<O, A> attribute(Class<O> objectType, Class<A> attributeType, String attributeName, SimpleFunction<O, A> function) {
return new FunctionalSimpleAttribute<O, A>(objectType, attributeType, attributeName, function);
}
/**
* Creates a {@link SimpleNullableAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
* <p/>
* This is a convenience method, which delegates to {@link #nullableAttribute(String, SimpleFunction)},
* supplying {@code function.getClass().getName()} as the name of the attribute.
*
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleNullableAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleNullableAttribute<O, A> nullableAttribute(SimpleFunction<O, A> function) {
return nullableAttribute(function.getClass().getName(), function);
}
/**
* Creates a {@link SimpleNullableAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
*
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleNullableAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleNullableAttribute<O, A> nullableAttribute(String attributeName, SimpleFunction<O, A> function) {
FunctionGenericTypes<O, A> resolved = resolveSimpleFunctionGenericTypes(function.getClass());
return nullableAttribute(resolved.objectType, resolved.attributeType, attributeName, function);
}
/**
* Creates a {@link SimpleNullableAttribute} from the given function or lambda expression,
* allowing the generic types of the attribute to be specified explicitly.
*
* @param objectType The type of the object containing the attribute
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link SimpleNullableAttribute} created from the given function or lambda expression
*/
public static <O, A> SimpleNullableAttribute<O, A> nullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, SimpleFunction<O, A> function) {
return new FunctionalSimpleNullableAttribute<O, A>(objectType, attributeType, attributeName, function);
}
/**
* Creates a {@link MultiValueAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
* <p/>
* This is a convenience method, which delegates to {@link #attribute(Class, String, MultiValueFunction)},
* supplying {@code function.getClass().getName()} as the name of the attribute.
*
* @param attributeType The type of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueAttribute<O, A> attribute(Class<A> attributeType, MultiValueFunction<O, A, I> function) {
return attribute(attributeType, function.getClass().getName(), function);
}
/**
* Creates a {@link MultiValueAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
*
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueAttribute<O, A> attribute(Class<A> attributeType, String attributeName, MultiValueFunction<O, A, I> function) {
Class<O> resolvedObjectType = resolveMultiValueFunctionGenericObjectType(function.getClass());
return attribute(resolvedObjectType, attributeType, attributeName, function);
}
/**
* Creates a {@link MultiValueAttribute} from the given function or lambda expression,
* allowing the generic types of the attribute to be specified explicitly.
*
* @param objectType The type of the object containing the attribute
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueAttribute<O, A> attribute(Class<O> objectType, Class<A> attributeType, String attributeName, MultiValueFunction<O, A, I> function) {
return new FunctionalMultiValueAttribute<O, A, I>(objectType, attributeType, attributeName, function);
}
/**
* Creates a {@link MultiValueNullableAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
* <p/>
* This is a convenience method, which delegates to {@link #nullableAttribute(Class, String, MultiValueFunction)},
* supplying {@code function.getClass().getName()} as the name of the attribute.
*
* @param attributeType The type of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueNullableAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueNullableAttribute<O, A> nullableAttribute(Class<A> attributeType, MultiValueFunction<O, A, I> function) {
return nullableAttribute(attributeType, function.getClass().getName(), function);
}
/**
* Creates a {@link MultiValueNullableAttribute} from the given function or lambda expression,
* while attempting to infer generic type information for the attribute automatically.
* <p/>
* <b>Limitations of type inference</b><br/>
* As of Java 8, there are limitations of this type inference.
* CQEngine uses <a href="https://github.com/jhalterman/typetools">TypeTools</a> to infer generic types.
* See documentation of that library for details.
* If generic type information cannot be inferred, as a workaround you may use the overloaded variant of this method
* which allows the types to be specified explicitly.
*
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueNullableAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueNullableAttribute<O, A> nullableAttribute(Class<A> attributeType, String attributeName, MultiValueFunction<O, A, I> function) {
Class<O> resolvedObjectType = resolveMultiValueFunctionGenericObjectType(function.getClass());
return nullableAttribute(resolvedObjectType, attributeType, attributeName, function);
}
/**
* Creates a {@link MultiValueNullableAttribute} from the given function or lambda expression,
* allowing the generic types of the attribute to be specified explicitly.
*
* @param objectType The type of the object containing the attribute
* @param attributeType The type of the attribute
* @param attributeName The name of the attribute
* @param function A function or lambda expression
* @param <O> The type of the object containing the attribute
* @param <A> The type of the attribute
* @return A {@link MultiValueNullableAttribute} created from the given function or lambda expression
*/
public static <O, A, I extends Iterable<A>> MultiValueNullableAttribute<O, A> nullableAttribute(Class<O> objectType, Class<A> attributeType, String attributeName, MultiValueFunction<O, A, I> function) {
return new FunctionalMultiValueNullableAttribute<O, A, I>(objectType, attributeType, attributeName, true, function);
}
// ***************************************************************************************************************
// Helper methods for creating attributes from lambda expressions...
// ***************************************************************************************************************
static final String GENERIC_TYPE_RESOLUTION_FAILURE_MESSAGE =
"If the function you supplied was created from a lambda expression, then it's likely " +
"that the host JVM does not allow the generic type information to be read from lambda expressions. " +
"Alternatively, if you supplied a class-based implementation of the function, then you must ensure " +
"that you specified the generic types of the function when it was compiled. " +
"As a workaround, you can use the counterpart methods in QueryFactory " +
"which allow the generic types to be specified explicitly.";
static <O, A, F> FunctionGenericTypes<O, A> resolveSimpleFunctionGenericTypes(Class<?> subType) {
Class<?>[] typeArgs = TypeResolver.resolveRawArguments(SimpleFunction.class, subType);
validateSimpleFunctionGenericTypes(typeArgs, subType);
@SuppressWarnings("unchecked") Class<O> objectType = (Class<O>) typeArgs[0];
@SuppressWarnings("unchecked") Class<A> attributeType = (Class<A>) typeArgs[1];
return new FunctionGenericTypes<O, A>(objectType, attributeType);
}
static void validateSimpleFunctionGenericTypes(Class<?>[] typeArgs, Class<?> subType) {
if (typeArgs == null) {
throw new IllegalStateException("Could not resolve any generic type information from the given " +
"function of type: " + subType.getName() + ". " + GENERIC_TYPE_RESOLUTION_FAILURE_MESSAGE);
}
if (typeArgs.length != 2 || typeArgs[0] == TypeResolver.Unknown.class || typeArgs[1] == TypeResolver.Unknown.class) {
throw new IllegalStateException("Could not resolve sufficient generic type information from the given " +
"function of type: " + subType.getName() + ", resolved: " + Arrays.toString(typeArgs) + ". " +
GENERIC_TYPE_RESOLUTION_FAILURE_MESSAGE);
}
}
static <O> Class<O> resolveMultiValueFunctionGenericObjectType(Class<?> subType) {
Class<?>[] typeArgs = TypeResolver.resolveRawArguments(MultiValueFunction.class, subType);
validateMultiValueFunctionGenericTypes(typeArgs, subType);
@SuppressWarnings("unchecked") Class<O> objectType = (Class<O>) typeArgs[0];
return objectType;
}
static void validateMultiValueFunctionGenericTypes(Class<?>[] typeArgs, Class<?> subType) {
if (typeArgs == null) {
throw new IllegalStateException("Could not resolve any generic type information from the given " +
"function of type: " + subType.getName() + ". " + GENERIC_TYPE_RESOLUTION_FAILURE_MESSAGE);
}
if (typeArgs.length != 3 || typeArgs[0] == TypeResolver.Unknown.class) {
throw new IllegalStateException("Could not resolve sufficient generic type information from the given " +
"function of type: " + subType.getName() + ", resolved: " + Arrays.toString(typeArgs) + ". " +
GENERIC_TYPE_RESOLUTION_FAILURE_MESSAGE);
}
}
static class FunctionGenericTypes<O, A> {
final Class<O> objectType;
final Class<A> attributeType;
FunctionGenericTypes(Class<O> objectType, Class<A> attributeType) {
this.objectType = objectType;
this.attributeType = attributeType;
}
}
// ***************************************************************************************************************
// The following methods are just overloaded vararg variants of existing methods above.
// These methods are unnecessary as of Java 7, and are provided only for backward compatibility with Java 6 and
// earlier.
//
// The methods exists to work around warnings output by the Java compiler for *client code* invoking generic
// vararg methods: "unchecked generic array creation of type Query<Foo>[] for varargs parameter" and similar.
// See http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000217.html - project coin feature
// in Java 7 which addresses the issue.
// ***************************************************************************************************************
/**
* Overloaded variant of {@link #and(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> And<O> and(Query<O> query1, Query<O> query2, Query<O> query3) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3);
return new And<O>(queries);
}
/**
* Overloaded variant of {@link #and(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> And<O> and(Query<O> query1, Query<O> query2, Query<O> query3, Query<O> query4) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3, query4);
return new And<O>(queries);
}
/**
* Overloaded variant of {@link #and(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> And<O> and(Query<O> query1, Query<O> query2, Query<O> query3, Query<O> query4, Query<O> query5) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3, query4, query5);
return new And<O>(queries);
}
// ***************************************************************************************************************
/**
* Overloaded variant of {@link #or(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> Or<O> or(Query<O> query1, Query<O> query2, Query<O> query3) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3);
return new Or<O>(queries);
}
/**
* Overloaded variant of {@link #or(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> Or<O> or(Query<O> query1, Query<O> query2, Query<O> query3, Query<O> query4) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3, query4);
return new Or<O>(queries);
}
/**
* Overloaded variant of {@link #or(Query, Query, Query[])} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> Or<O> or(Query<O> query1, Query<O> query2, Query<O> query3, Query<O> query4, Query<O> query5) {
@SuppressWarnings({"unchecked"})
Collection<Query<O>> queries = Arrays.asList(query1, query2, query3, query4, query5);
return new Or<O>(queries);
}
// ***************************************************************************************************************
/**
* Overloaded variant of {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} - see that method
* for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> OrderByOption<O> orderBy(AttributeOrder<O> attributeOrder) {
@SuppressWarnings({"unchecked"})
List<AttributeOrder<O>> attributeOrders = Collections.singletonList(attributeOrder);
return new OrderByOption<O>(attributeOrders);
}
/**
* Overloaded variant of {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} - see that method
* for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> OrderByOption<O> orderBy(AttributeOrder<O> attributeOrder1, AttributeOrder<O> attributeOrder2) {
@SuppressWarnings({"unchecked"})
List<AttributeOrder<O>> attributeOrders = Arrays.asList(attributeOrder1, attributeOrder2);
return new OrderByOption<O>(attributeOrders);
}
/**
* Overloaded variant of {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} - see that method
* for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> OrderByOption<O> orderBy(AttributeOrder<O> attributeOrder1, AttributeOrder<O> attributeOrder2,
AttributeOrder<O> attributeOrder3) {
@SuppressWarnings({"unchecked"})
List<AttributeOrder<O>> attributeOrders = Arrays.asList(attributeOrder1, attributeOrder2, attributeOrder3);
return new OrderByOption<O>(attributeOrders);
}
/**
* Overloaded variant of {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} - see that method
* for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> OrderByOption<O> orderBy(AttributeOrder<O> attributeOrder1, AttributeOrder<O> attributeOrder2,
AttributeOrder<O> attributeOrder3, AttributeOrder<O> attributeOrder4) {
@SuppressWarnings({"unchecked"})
List<AttributeOrder<O>> attributeOrders = Arrays.asList(attributeOrder1, attributeOrder2, attributeOrder3,
attributeOrder4);
return new OrderByOption<O>(attributeOrders);
}
/**
* Overloaded variant of {@link #orderBy(com.googlecode.cqengine.query.option.AttributeOrder[])} - see that method
* for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static <O> OrderByOption<O> orderBy(AttributeOrder<O> attributeOrder1, AttributeOrder<O> attributeOrder2,
AttributeOrder<O> attributeOrder3, AttributeOrder<O> attributeOrder4,
AttributeOrder<O> attributeOrder5) {
@SuppressWarnings({"unchecked"})
List<AttributeOrder<O>> attributeOrders = Arrays.asList(attributeOrder1, attributeOrder2, attributeOrder3,
attributeOrder4, attributeOrder5);
return new OrderByOption<O>(attributeOrders);
}
/**
* Converts a {@link Query} to a {@link Predicate} which can evaluate if the the query matches any given object.
* The predicate will determine this by invoking {@link Query#matches(Object, QueryOptions)}, supplying null for
* the query options.
* <p/>
* Note that while most queries do not utilize query options and thus will be compatible with this method,
* it's possible that some queries might require query options. For those cases, create the predicate via
* the counterpart method {@link #predicate(Query, QueryOptions)} instead.
*
* @param query The query to be converted to a predicate
* @return A predicate which can evaluate if the the query matches any given object
*/
public static <O> Predicate<O> predicate(Query<O> query) {
return predicate(query, null);
}
/**
* Converts a {@link Query} to a {@link Predicate} which can evaluate if the the query matches any given object.
* The predicate will determine this by invoking {@link Query#matches(Object, QueryOptions)}.
*
* @param query The query to be converted to a predicate
* @param queryOptions The query options to supply to the {@link Query#matches(Object, QueryOptions)} method
* @return A predicate which can evaluate if the the query matches any given object
*/
public static <O> Predicate<O> predicate(Query<O> query, QueryOptions queryOptions) {
return object -> query.matches(object, queryOptions);
}
// ***************************************************************************************************************
/**
* Overloaded variant of {@link #queryOptions(Object...)} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static QueryOptions queryOptions(Object queryOption) {
return queryOptions(Collections.singleton(queryOption));
}
/**
* Overloaded variant of {@link #queryOptions(Object...)} - see that method for details.
* <p/>
* Note: This method is unnecessary as of Java 7, and is provided only for backward compatibility with Java 6 and
* earlier, to eliminate generic array creation warnings output by the compiler in those versions.
*/
@SuppressWarnings({"JavaDoc"})
public static QueryOptions queryOptions(Object queryOption1, Object queryOption2) {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
List<Object> queryOptions = Arrays.asList(queryOption1, queryOption2);
return queryOptions(queryOptions);
}
}
| 72,354 | 50.793128 | 213 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/ComparativeQuery.java | package com.googlecode.cqengine.query;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.comparative.LongestPrefix;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A special type of query which can only be evaluated by comparing objects stored in the collection with each other.
* <p>
* It is not possible to determine if a certain object matches a comparative query in isolation; for example by calling
* {@link #matches(Object, QueryOptions)}. Therefore if that method is called on queries of this type, it will throw
* an exception. Comparative queries are instead evaluated via the method {@link #getMatches(ObjectSet, QueryOptions)}.
* <p>
* Examples of comparative queries include {@link QueryFactory#min(Attribute)}, {@link QueryFactory#max(Attribute)}.
* It is only possible to determine the object(s) which have the minimum or maximum values of an attribute by examining
* all such attribute values throughout the collection (this may however be accelerated by an index). In this case,
* the objects are compared via the {@link Comparable} interface. The object(s) whose attribute values in the collection
* sort lower or higher (respectively) are the results of those queries.
* <p>
* Note that comparative queries are not always implemented via the {@link Comparable} interface. For example, the
* {@link LongestPrefix} query examines the lengths of matched prefixes, rather
* than the relative ordering of objects in the collection as determined by {@link Comparable}. Therefore, this
* interface does not require that the generic type A extend Comparable per-se.
*
* @param <O> Type of objects in the collection
* @param <A> Type of the attribute being examined by this query
*/
public interface ComparativeQuery<O, A> extends Query<O> {
/**
* {@inheritDoc}
* @throws UnsupportedOperationException always
*/
@Override
default boolean matches(O object, QueryOptions queryOptions) {
throw new UnsupportedOperationException("This method is not supported on comparative queries");
}
/**
* Evaluates the comparative query, returning the objects in the collection which match the query.
* @param objectsInCollection All objects in the collection
* @param queryOptions Optional query options to use
* @return An iterator which provides the subset of objects in the collection which match the query
*/
Iterable<O> getMatches(ObjectSet<O> objectsInCollection, QueryOptions queryOptions);
/**
* Returns the attribute to which the query relates.
* @return the attribute to which the query relates
*/
Attribute<O, A> getAttribute();
}
| 2,773 | 50.37037 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/EngineThresholds.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.query.option;
/**
* An enum whose members can be used to set query options with {@link Double} values, representing thresholds which
* can be overridden to tune CQEngine query performance.
* <p/>
* If a threshold is not set as a query option, a default threshold will be applied.
* <i>Note that default thresholds might change between CQEngine versions.</i>
*
* @author niall.gallagher
*/
public enum EngineThresholds {
/**
* A threshold between 0.0 and 1.0, which refers to the selectivity of the query which triggers CQEngine to
* use an index to order results, instead of retrieving all results and ordering them afterwards.
* <p/>
* There is a trade-off between these strategies, because index ordering forces use of a particular index whereas
* that index might not always be the most optimal to quickly locate objects which match the query. On the other
* hand if the query matches a large number of results then sorting those results afterwards can be relatively
* expensive. Hence this threshold, which refers to the point at which CQEngine will automatically choose one
* of these strategies over the other for each particular query.
* <p/>
* CQEngine calculates the selectivity of the query roughly as:<br/>
* <code>1.0 - [number of objects the query matches]/[number of objects in the collection]</code><br/>
* Therefore a query with low selectivity matches most of the collection, and a query with high selectivity matches
* a small number of objects in the collection.
* <p/>
* When CQEngine determines that the selectivity of the query is lower than this configured threshold,
* then it will use an index to order results. When query selectivity is higher than this threshold then it will
* retrieve all results and order them afterwards.
*/
INDEX_ORDERING_SELECTIVITY(0.0);
final double thresholdDefault;
EngineThresholds(double thresholdDefault) {
this.thresholdDefault = thresholdDefault;
}
public double getThresholdDefault() {
return thresholdDefault;
}
}
| 2,758 | 44.983333 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/QueryLog.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.query.option;
/**
* If set as a query option causes CQEngine to log its internal decisions during query evaluation to the given sink.
* The given sink could be System.out in the simplest case.
* This can be used for debugging, or for testing CQEngine itself.
*
* @author niall.gallagher
*/
public class QueryLog {
final Appendable sink;
final String lineSeparator;
public QueryLog(Appendable sink) {
this(sink, System.getProperty("line.separator"));
}
public QueryLog(Appendable sink, String lineSeparator) {
this.sink = sink;
this.lineSeparator = lineSeparator;
}
public Appendable getSink() {
return sink;
}
public void log(String message) {
try {
sink.append(message);
if (lineSeparator != null) {
sink.append(lineSeparator);
}
}
catch (Exception e) {
throw new IllegalStateException("Exception appending to query log", e);
}
}
}
| 1,650 | 28.482143 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/FlagsDisabled.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.query.option;
import com.googlecode.cqengine.query.QueryFactory;
import java.util.HashSet;
import java.util.Set;
/**
* A wrapper around object keys ("flags") which are said to be disabled.
* <p/>
* Example usage using {@link QueryFactory}:<br/>
* <code>QueryOptions queryOptions = queryOptions(disableFlags("flag1", "flag2"))</code>
*
* @author niall.gallagher
*/
public class FlagsDisabled {
final Set<Object> flags = new HashSet<Object>();
public void add(Object flag) {
flags.add(flag);
}
public void remove(Object flag) {
flags.remove(flag);
}
public boolean isFlagDisabled(Object flag) {
return flags.contains(flag);
}
@Override
public String toString() {
return "flagsDisabled=" + flags;
}
/**
* Returns an existing {@link FlagsDisabled} 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 FlagsDisabled or a new instance.
*/
public static FlagsDisabled forQueryOptions(final QueryOptions queryOptions) {
FlagsDisabled flags = queryOptions.get(FlagsDisabled.class);
if (flags == null) {
flags = new FlagsDisabled();
queryOptions.put(FlagsDisabled.class, flags);
}
return flags;
}
public static boolean isFlagDisabled(QueryOptions queryOptions, Object flag) {
FlagsDisabled flagsDisabled = queryOptions.get(FlagsDisabled.class);
return flagsDisabled != null && flagsDisabled.isFlagDisabled(flag);
}
}
| 2,275 | 30.178082 | 88 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/QueryOptions.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.query.option;
import java.util.HashMap;
import java.util.Map;
/**
* Encapsulates a map of optional key-value parameters supplied by the application to the query engine, attributes
* and indexes.
* <p/>
* These parameters can request specific behaviour from the query engine such as specifying transaction
* isolation levels.
* <p/>
* Query options also allow the application to pass arbitrary or request-scope objects to custom Attributes or Indexes.
*/
public class QueryOptions {
final Map<Object, Object> options;
public QueryOptions(Map<Object, Object> options) {
this.options = options;
}
public QueryOptions() {
this.options = new HashMap<Object, Object>();
}
public Map<Object, Object> getOptions() {
return this.options;
}
public <T> T get(Class<T> optionType) {
@SuppressWarnings("unchecked")
T optionValue = (T) get((Object)optionType);
return optionValue;
}
public Object get(Object key) {
return options.get(key);
}
public void put(Object key, Object value) {
options.put(key, value);
}
public void remove(Object key) {
options.remove(key);
}
@Override
public String toString() {
return "queryOptions(" + options + ')';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof QueryOptions)) return false;
QueryOptions that = (QueryOptions) o;
if (!options.equals(that.options)) return false;
return true;
}
@Override
public int hashCode() {
return options.hashCode();
}
}
| 2,305 | 25.813953 | 119 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/DeduplicationStrategy.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.query.option;
/**
* @author Niall Gallagher
*/
public enum DeduplicationStrategy {
DUPLICATES_ALLOWED,
LOGICAL_ELIMINATION,
MATERIALIZE
}
| 789 | 29.384615 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/ArgumentValidationStrategy.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.query.option;
/**
* Allows the app to disable argument validation in CQEngine via a QueryOption, to improve performance.
* This should only be done when application developers are sure that their code has no bugs!
*
* @author niall.gallagher
*/
public enum ArgumentValidationStrategy {
VALIDATE,
SKIP
}
| 953 | 33.071429 | 103 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/IsolationLevel.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.query.option;
/**
* @author Niall Gallagher
*/
public enum IsolationLevel {
READ_COMMITTED,
READ_UNCOMMITTED
}
| 758 | 29.36 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/FlagsEnabled.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.query.option;
import com.googlecode.cqengine.query.QueryFactory;
import java.util.HashSet;
import java.util.Set;
/**
* A wrapper around object keys ("flags") which are said to be enabled.
* <p/>
* Example usage using {@link QueryFactory}:<br/>
* <code>QueryOptions queryOptions = queryOptions(enableFlags("flag1", "flag2"))</code>
*
* @author niall.gallagher
*/
public class FlagsEnabled {
final Set<Object> flags = new HashSet<Object>();
public void add(Object flag) {
flags.add(flag);
}
public void remove(Object flag) {
flags.remove(flag);
}
public boolean isFlagEnabled(Object flag) {
return flags.contains(flag);
}
@Override
public String toString() {
return "flagsEnabled=" + flags;
}
/**
* Returns an existing {@link FlagsEnabled} 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 FlagsEnabled or a new instance.
*/
public static FlagsEnabled forQueryOptions(final QueryOptions queryOptions) {
FlagsEnabled flags = queryOptions.get(FlagsEnabled.class);
if (flags == null) {
flags = new FlagsEnabled();
queryOptions.put(FlagsEnabled.class, flags);
}
return flags;
}
public static boolean isFlagEnabled(QueryOptions queryOptions, Object flag) {
FlagsEnabled flagsDisabled = queryOptions.get(FlagsEnabled.class);
return flagsDisabled != null && flagsDisabled.isFlagEnabled(flag);
}
}
| 2,259 | 29.958904 | 87 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/IsolationOption.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.query.option;
/**
* @author Niall Gallagher
*/
public class IsolationOption {
private final IsolationLevel isolationLevel;
public IsolationOption(IsolationLevel isolationLevel) {
this.isolationLevel = isolationLevel;
}
public IsolationLevel getIsolationLevel() {
return isolationLevel;
}
@Override
public String toString() {
return "isolationLevel(" + isolationLevel + ")";
}
/**
* Utility method to extract an {@link IsolationOption} object from the query options provided, and to check
* if its level is the same as the one supplied.
*
* @param queryOptions The query options to check
* @param level The isolation level to compare with
* @return True if {@link IsolationOption} object is contained in those provided and its level matches that given
*/
public static boolean isIsolationLevel(QueryOptions queryOptions, IsolationLevel level) {
IsolationOption option = queryOptions.get(IsolationOption.class);
return option != null && level.equals(option.getIsolationLevel());
}
} | 1,743 | 33.88 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/Threshold.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.query.option;
/**
* A wrapper around a key and an associated {@link Double} value, representing the value for that threshold key
* which is to be applied to tune CQEngine query performance. These thresholds can be supplied as query options.
* <p/>
* See {@link EngineThresholds} for information about some thresholds which can be set.
*
* @author niall.gallagher
*/
public class Threshold {
final Object key;
final Double value;
public Threshold(Object key, Double value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Threshold)) {
return false;
}
Threshold threshold = (Threshold) o;
if (!key.equals(threshold.key)) {
return false;
}
return value.equals(threshold.value);
}
@Override
public int hashCode() {
int result = key.hashCode();
result = 31 * result + value.hashCode();
return result;
}
}
| 1,718 | 27.180328 | 112 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/ArgumentValidationOption.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.query.option;
/**
* @author niall.gallagher
*/
public class ArgumentValidationOption {
private final ArgumentValidationStrategy strategy;
public ArgumentValidationOption(ArgumentValidationStrategy strategy) {
this.strategy = strategy;
}
public ArgumentValidationStrategy getStrategy() {
return strategy;
}
/**
* Utility method to extract a {@link ArgumentValidationOption} object from the query options provided, and to check
* if the strategy specified is {@link ArgumentValidationStrategy#SKIP}.
*
* @param queryOptions The query options to check
* @return True if {@link ArgumentValidationOption} object is contained in those provided and its strategy is
* {@link com.googlecode.cqengine.query.option.ArgumentValidationStrategy#SKIP}
*/
public static <O> boolean isSkip(QueryOptions queryOptions) {
ArgumentValidationOption option = queryOptions.get(ArgumentValidationOption.class);
return option != null && ArgumentValidationStrategy.SKIP.equals(option.getStrategy());
}
@Override
public String toString() {
return "argumentValidation(" + strategy + ")";
}
}
| 1,827 | 34.153846 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/OrderByOption.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.query.option;
import java.util.Iterator;
import java.util.List;
/**
* Represents a list of attributes and associated preferences for sorting results according to those attributes each
* in ascending or descending order.
*
* @author Roberto Socrates
* @author Niall Gallagher
*/
public class OrderByOption<O> {
private final List<AttributeOrder<O>> attributeOrders;
public OrderByOption(List<AttributeOrder<O>> attributeOrders) {
if (attributeOrders.isEmpty()) {
throw new IllegalArgumentException("The list of attribute orders cannot be empty");
}
this.attributeOrders = attributeOrders;
}
public List<AttributeOrder<O>> getAttributeOrders() {
return attributeOrders;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("orderBy(");
for (Iterator<AttributeOrder<O>> iterator = attributeOrders.iterator(); iterator.hasNext(); ) {
AttributeOrder<?> childQuery = iterator.next();
sb.append(childQuery);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderByOption)) return false;
OrderByOption that = (OrderByOption) o;
if (!attributeOrders.equals(that.attributeOrders)) return false;
return true;
}
@Override
public int hashCode() {
return attributeOrders.hashCode();
}
}
| 2,251 | 29.026667 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/AttributeOrder.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.query.option;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.OrderControlAttribute;
import com.googlecode.cqengine.attribute.OrderMissingFirstAttribute;
import com.googlecode.cqengine.attribute.OrderMissingLastAttribute;
/**
* Represents an attribute and an associated preference for sorting results according to that attribute
* in ascending or descending order.
*
* @author Roberto Socrates
* @author Niall Gallagher
*/
public class AttributeOrder<O> {
private final Attribute<O, ? extends Comparable> attribute;
private final boolean descending;
public AttributeOrder(Attribute<O, ? extends Comparable> attribute, boolean descending) {
this.attribute = attribute;
this.descending = descending;
}
public Attribute<O, ? extends Comparable> getAttribute() {
return attribute;
}
public boolean isDescending() {
return descending;
}
@Override
public String toString() {
if (attribute instanceof OrderMissingLastAttribute) {
OrderControlAttribute orderControlAttribute = (OrderControlAttribute) attribute;
@SuppressWarnings("unchecked")
Attribute<O, ? extends Comparable> delegateAttribute = orderControlAttribute.getDelegateAttribute();
return descending
? "descending(missingLast(" + delegateAttribute.getObjectType().getSimpleName() + "." + delegateAttribute.getAttributeName() + "))"
: "ascending(missingLast(" + delegateAttribute.getObjectType().getSimpleName() + "." + delegateAttribute.getAttributeName() + "))";
}
if (attribute instanceof OrderMissingFirstAttribute) {
OrderControlAttribute orderControlAttribute = (OrderControlAttribute) attribute;
@SuppressWarnings("unchecked")
Attribute<O, ? extends Comparable> delegateAttribute = orderControlAttribute.getDelegateAttribute();
return descending
? "descending(missingFirst(" + delegateAttribute.getObjectType().getSimpleName() + "." + delegateAttribute.getAttributeName() + "))"
: "ascending(missingFirst(" + delegateAttribute.getObjectType().getSimpleName() + "." + delegateAttribute.getAttributeName() + "))";
}
else {
return descending
? "descending(" + attribute.getObjectType().getSimpleName() + "." + attribute.getAttributeName() + ")"
: "ascending(" + attribute.getObjectType().getSimpleName() + "." + attribute.getAttributeName() + ")";
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AttributeOrder)) return false;
AttributeOrder that = (AttributeOrder) o;
if (descending != that.descending) return false;
if (!attribute.equals(that.attribute)) return false;
return true;
}
@Override
public int hashCode() {
int result = attribute.hashCode();
result = 31 * result + (descending ? 1 : 0);
return result;
}
}
| 3,759 | 39 | 152 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/DeduplicationOption.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.query.option;
import java.util.Map;
/**
* @author Niall Gallagher
*/
public class DeduplicationOption {
private final DeduplicationStrategy strategy;
public DeduplicationOption(DeduplicationStrategy strategy) {
this.strategy = strategy;
}
public DeduplicationStrategy getStrategy() {
return strategy;
}
/**
* Utility method to extract a {@link DeduplicationOption} object from the query options provided, and to check
* if the strategy specified is {@link DeduplicationStrategy#LOGICAL_ELIMINATION}.
*
* @param queryOptions The query options to check
* @return True if {@link DeduplicationOption} object is contained in those provided and its strategy is
* {@link DeduplicationStrategy#LOGICAL_ELIMINATION}
*/
public static <O> boolean isLogicalElimination(QueryOptions queryOptions) {
DeduplicationOption option = queryOptions.get(DeduplicationOption.class);
return option != null && DeduplicationStrategy.LOGICAL_ELIMINATION.equals(option.getStrategy());
}
/**
* Utility method to extract a {@link DeduplicationOption} object from the query options provided, and to check
* if the strategy specified is {@link DeduplicationStrategy#MATERIALIZE}.
*
* @param queryOptions The query options to check
* @return True if {@link DeduplicationOption} object is contained in those provided and its strategy is
* {@link DeduplicationStrategy#MATERIALIZE}
*/
public static <O> boolean isMaterialize(QueryOptions queryOptions) {
DeduplicationOption option = queryOptions.get(DeduplicationOption.class);
return option != null && DeduplicationStrategy.MATERIALIZE.equals(option.getStrategy());
}
@Override
public String toString() {
return "deduplicate(" + strategy + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DeduplicationOption)) return false;
DeduplicationOption that = (DeduplicationOption) o;
if (strategy != that.strategy) return false;
return true;
}
@Override
public int hashCode() {
return strategy.hashCode();
}
}
| 2,873 | 33.626506 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/Thresholds.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.query.option;
import com.googlecode.cqengine.query.QueryFactory;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A wrapper around {@link Threshold}s which have been set into query options.
* <p/>
* Example usage using {@link QueryFactory}:<br/>
* <code>QueryOptions queryOptions = queryOptions(applyThresholds(INDEX_ORDERING_SELECTIVITY, 0.4))</code>
*
* @author niall.gallagher
*/
public class Thresholds {
final Map<Object, Double> thresholds = new LinkedHashMap<Object, Double>();
public Thresholds(Collection<Threshold> thresholds) {
for (Threshold threshold : thresholds) {
this.thresholds.put(threshold.key, threshold.value);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Thresholds)) {
return false;
}
Thresholds that = (Thresholds) o;
return thresholds.equals(that.thresholds);
}
@Override
public int hashCode() {
return thresholds.hashCode();
}
public Double getThreshold(Object key) {
return thresholds.get(key);
}
@Override
public String toString() {
return thresholds.toString();
}
public static Double getThreshold(QueryOptions queryOptions, Object key) {
Thresholds thresholds = queryOptions.get(Thresholds.class);
return thresholds == null ? null : thresholds.getThreshold(key);
}
}
| 2,149 | 28.452055 | 106 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/option/EngineFlags.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.query.option;
import com.googlecode.cqengine.query.QueryFactory;
/**
* An enum of some flags which can be set into {@link QueryOptions} to request certain behaviours from the query engine.
* This enum is not an exhaustive set of possible flags which can be set. For example custom indexes are free to define
* their own flags. This enum is just a central collection of flags used directly by the query engine.
* <p/>
* Example usage using {@link QueryFactory}:<br/>
* <code>QueryOptions queryOptions =
* queryOptions(enableFlags(EngineFlags.SOME_FLAG, EngineFlags.OTHER_FLAG), disableFlags(EngineFlags.ANOTHER_FLAG))
* </code>
*
* @author niall.gallagher
*/
public enum EngineFlags {
/**
* A performance tuning flag which may be useful in applications in which objects are stored off-heap, remotely, or
* on disk, or generally where it is more expensive to retrieve values from CQEngine attributes, than it is to
* probe indexes on those attributes, when evaluating a query.
* <p/>
* <b>Example</b><br/>
* Consider the query: <code>and(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Color.BLUE))</code><br/>
* <ol>
* <li>Let's say there are indexes on both the MANUFACTURER and COLOR attributes.</li>
* <li>CQEngine will query those indexes to determine which is the smallest candidate set:
* are there fewer Ford cars in the collection, or are there fewer BLUE cars in the collection? Let's say
* there are fewer Ford cars in the collection.</li>
* <li>CQEngine will then use the index on MANUFACTURER, to jump to the set of Ford cars, and then it will
* need to determine if each of those Ford cars is also BLUE.</li>
* <li>This flag determines CQEngine's strategy at this point:
* <ul>
* <li>If this flag is <i>disabled</i> (or is not set) then CQEngine will retrieve the color of the car
* being evaluated from the COLOR attribute, and it will compare that value with the color in the query.
* If they match, the candidate object is considered to match the overall query.</li>
* <li>If this flag is <i>enabled</i> then CQEngine will instead try to access an index on the COLOR
* attribute, and it will ask that index if it contains a BLUE car which refers to this object.
* If the index reports that it contains such an object, then the candidate object is considered to match
* the overall query.</li>
* </ul>
* </li>
* </ol>
*/
PREFER_INDEX_MERGE_STRATEGY,
/**
* A performance tuning flag for when the index ordering strategy is used, which configures the strategy to
* maximize ordering speed, at the expense of allowing a slightly inexact ordering of objects which have multiple
* values for the attribute by which they are being ordered.
* <p/>
* For example: if object 1 has values ["a"] and object 2 has values ["a", "b"] then technically object 1 should
* always be returned before object 2, when results are to be returned in ascending order. The relative ordering
* of these objects should also be reversed, when results are to be returned in descending order. That is, to be
* consistent with the other ordering strategies in CQEngine.
* <p/>
* However this technically-correct and deterministic ordering, does not come for free, and requires that the
* strategy re-sort the objects in each bucket encountered.
* <p/>
* If this flag is enabled, the index ordering strategy will avoid re-sorting the buckets in the index used for
* ordering. This will improve retrieval speed, at the expense of allowing the relative ordering of objects having
* one attribute value in common, and having other differing attribute values, to be slightly inexact.
*/
INDEX_ORDERING_ALLOW_FAST_ORDERING_OF_MULTI_VALUED_ATTRIBUTES
}
| 4,603 | 55.146341 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/comparative/LongestPrefix.java | package com.googlecode.cqengine.query.comparative;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.ArrayList;
import java.util.List;
import static com.googlecode.cqengine.query.simple.SimpleQuery.asLiteral;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* LongestPrefix queries are used to find the longest prefix in a dataset for a given query term.
* Given a data set with the following records
*
* <pre>
* | id | code | Operator |
* | 0 | 35387 | Foo |
* | 1 | 35385 | Bar |
* | 2 | 353855 | A.N.Other |
* </pre>
* A longest prefix query using a query as shown below would return the entity with id 0
* <p/>
* {@code Query<Foo> query1 = longestPrefix(Foo.CODE, "35387123456")); }
*
* @author Glen Lockhart
*/
public class LongestPrefix<O, A extends CharSequence> extends SimpleComparativeQuery<O, A> {
private final A value;
public LongestPrefix(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LongestPrefix)) return false;
LongestPrefix<?, ?> that = (LongestPrefix<?, ?>) o;
if (!super.attribute.equals(that.attribute)) return false;
return this.value.equals(that.value);
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public Iterable<O> getMatchesForSimpleAttribute(SimpleAttribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
List<O> results = new ArrayList<>();
int currentCount = -1;
for (O object : objectsInCollection) {
CharSequence attributeValue = attribute.getValue(object, queryOptions);
int count = countPrefixChars(value, attributeValue);
if (count == 0) {
continue;
}
if (count > currentCount) {
currentCount = count;
results.clear();
results.add(object);
} else if (count == currentCount) {
results.add(object);
}
}
return results;
}
@Override
public Iterable<O> getMatchesForNonSimpleAttribute(Attribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
List<O> results = new ArrayList<>();
int currentCount = -1;
for (O object : objectsInCollection) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
int count = countPrefixChars(value, attributeValue);
if (count == 0) {
continue;
}
if (count > currentCount) {
currentCount = count;
results.clear();
results.add(object);
} else if (count == currentCount) {
results.add(object);
}
}
}
return results;
}
@Override
public String toString() {
return "longestPrefix(" + asLiteral(super.getAttributeName()) + ", " + asLiteral(value) + ")";
}
/**
* Returns the length of the given candidate prefix if it is a prefix of the given main sequence.
* Returns 0 if the candidate is not actually a prefix of the main sequence.
*/
static int countPrefixChars(CharSequence mainSequence, CharSequence candidatePrefix) {
int charsMatched = 0;
for (int i = 0, length = Math.min(mainSequence.length(), candidatePrefix.length()); i < length; i++) {
if (mainSequence.charAt(i) != candidatePrefix.charAt(i)) {
break;
}
charsMatched++;
}
return charsMatched == candidatePrefix.length() ? charsMatched : 0;
}
}
| 4,340 | 34.008065 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/comparative/Max.java | package com.googlecode.cqengine.query.comparative;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.HashSet;
import java.util.Set;
import static com.googlecode.cqengine.query.simple.SimpleQuery.asLiteral;
/**
* A comparative query which matches objects in the collection whose attribute values sort higher than all others.
*/
public class Max<O, A extends Comparable<A>> extends SimpleComparativeQuery<O, A> {
/**
* Creates a new {@link SimpleComparativeQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public Max(Attribute<O, A> attribute) {
super(attribute);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Max)) return false;
Max max = (Max) o;
return super.attribute.equals(max.attribute);
}
@Override
protected int calcHashCode() {
return super.attribute.hashCode();
}
@Override
public Iterable<O> getMatchesForSimpleAttribute(SimpleAttribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
A maximumValue = null;
Set<O> results = new HashSet<>();
for (O object : objectsInCollection) {
A attributeValue = attribute.getValue(object, queryOptions);
maximumValue = evaluate(object, attributeValue, maximumValue, (Set<O>) results);
}
return results;
}
@Override
public Iterable<O> getMatchesForNonSimpleAttribute(Attribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
A maximumValue = null;
Set<O> results = new HashSet<>();
for (O object : objectsInCollection) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
maximumValue = evaluate(object, attributeValue, maximumValue, results);
}
}
return results;
}
/**
* Helper method which evaluates each attribute value encountered. Adds the object to the given set of
* results if the attribute value equals the max, or clears the results if a new maximum value is detected.
*
* @return The new maximum value
*/
A evaluate(O currentObject, A currentAttributeValue, A currentMaximumValue, Set<O> results) {
if (currentMaximumValue == null) {
currentMaximumValue = currentAttributeValue;
results.add(currentObject);
return currentMaximumValue;
}
final int cmp = currentAttributeValue.compareTo(currentMaximumValue);
if (cmp == 0) {
// We found another object whose attribute value is the same as the current maximum value.
// Add that object to the set of results...
results.add(currentObject);
} else if (cmp > 0) {
// We found an object whose attribute value is greater than the maximum value found so far.
// Clear all results encountered so far, and add this object to the set of results...
currentMaximumValue = currentAttributeValue;
results.clear();
results.add(currentObject);
}
return currentMaximumValue;
}
@Override
public String toString() {
return "max(" + asLiteral(super.getAttributeName()) + ")";
}
}
| 3,684 | 36.602041 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/comparative/SimpleComparativeQuery.java | package com.googlecode.cqengine.query.comparative;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.ComparativeQuery;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* A superclass of classes implementing {@link ComparativeQuery}.
* This class simply factors out some repetitive logic from subclasses.
*
* @param <A> The type of the attribute to which this query relates
* @param <O> The type of the objects in the collection
*
* @author Niall Gallagher
*/
public abstract class SimpleComparativeQuery<O, A> implements ComparativeQuery<O, A> {
protected final boolean attributeIsSimple;
protected final Attribute<O, A> attribute;
protected final SimpleAttribute<O, A> simpleAttribute;
// Lazy calculate and cache hash code...
private transient int cachedHashCode = 0;
/**
* Creates a new {@link SimpleComparativeQuery} initialized to make assertions on values of the specified attribute
* @param attribute The attribute on which the assertion is to be made
*/
public SimpleComparativeQuery(Attribute<O, A> attribute) {
if (attribute == null) {
throw new IllegalArgumentException("The attribute argument was null.");
}
this.attribute = attribute;
if (attribute instanceof SimpleAttribute) {
this.attributeIsSimple = true;
this.simpleAttribute = (SimpleAttribute<O, A>) attribute;
}
else {
this.attributeIsSimple = false;
this.simpleAttribute = null;
}
}
/**
* Returns the type of the attribute originally supplied to the constructor, a shortcut for
* {@link Attribute#getAttributeType()}.
* @return the type of the attribute originally supplied to the constructor
*/
public Class<A> getAttributeType() {
return attribute.getAttributeType();
}
/**
* Returns the name of the attribute originally supplied to the constructor, a shortcut for
* {@link Attribute#getAttributeName()}.
* @return the name of the attribute originally supplied to the constructor
*/
public String getAttributeName() {
return attribute.getAttributeName();
}
/**
* Returns the attribute originally supplied to the constructor.
* @return The attribute originally supplied to the constructor
*/
public Attribute<O, A> getAttribute() {
return attribute;
}
@Override
public int hashCode() {
// Lazy calculate and cache hash code...
int h = this.cachedHashCode;
if (h == 0) { // hash code not cached
h = calcHashCode();
if (h == 0) { // 0 is normally a valid hash code, coalesce with another...
h = -1838660945; // was randomly chosen
}
this.cachedHashCode = h; // cache hash code
}
return h;
}
protected abstract int calcHashCode();
@Override
public Iterable<O> getMatches(ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
return attributeIsSimple
? getMatchesForSimpleAttribute(simpleAttribute, objectsInCollection, queryOptions)
: getMatchesForNonSimpleAttribute(attribute, objectsInCollection, queryOptions);
}
public abstract Iterable<O> getMatchesForSimpleAttribute(SimpleAttribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions);
public abstract Iterable<O> getMatchesForNonSimpleAttribute(Attribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions);
}
| 3,750 | 36.51 | 155 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/comparative/Min.java | package com.googlecode.cqengine.query.comparative;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.HashSet;
import java.util.Set;
import static com.googlecode.cqengine.query.simple.SimpleQuery.asLiteral;
/**
* A comparative query which matches objects in the collection whose attribute values sort lower than all others.
*/
public class Min<O, A extends Comparable<A>> extends SimpleComparativeQuery<O, A> {
/**
* Creates a new {@link SimpleComparativeQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public Min(Attribute<O, A> attribute) {
super(attribute);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Min)) return false;
Min min = (Min) o;
return super.attribute.equals(min.attribute);
}
@Override
protected int calcHashCode() {
return super.attribute.hashCode();
}
@Override
public Iterable<O> getMatchesForSimpleAttribute(SimpleAttribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
A minimumValue = null;
Set<O> results = new HashSet<>();
for (O object : objectsInCollection) {
A attributeValue = attribute.getValue(object, queryOptions);
minimumValue = evaluate(object, attributeValue, minimumValue, (Set<O>) results);
}
return results;
}
@Override
public Iterable<O> getMatchesForNonSimpleAttribute(Attribute<O, A> attribute, ObjectSet<O> objectsInCollection, QueryOptions queryOptions) {
A minimumValue = null;
Set<O> results = new HashSet<>();
for (O object : objectsInCollection) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
minimumValue = evaluate(object, attributeValue, minimumValue, results);
}
}
return results;
}
/**
* Helper method which evaluates each attribute value encountered. Adds the object to the given set of
* results if the attribute value equals the max, or clears the results if a new maximum value is detected.
*
* @return The new maximum value
*/
A evaluate(O currentObject, A currentAttributeValue, A currentMinimumValue, Set<O> results) {
if (currentMinimumValue == null) {
currentMinimumValue = currentAttributeValue;
results.add(currentObject);
return currentMinimumValue;
}
final int cmp = currentAttributeValue.compareTo(currentMinimumValue);
if (cmp == 0) {
// We found another object whose attribute value is the same as the current minimum value.
// Add that object to the set of results...
results.add(currentObject);
} else if (cmp < 0) {
// We found an object whose attribute value is less than the minimum value found so far.
// Clear all results encountered so far, and add this object to the set of results...
currentMinimumValue = currentAttributeValue;
results.clear();
results.add(currentObject);
}
return currentMinimumValue;
}
@Override
public String toString() {
return "min(" + asLiteral(super.getAttributeName()) + ")";
}
}
| 3,679 | 36.938144 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/LessThan.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than an attribute is less than an upper bound.
*
* @author Niall Gallagher
*/
public class LessThan<O, A extends Comparable<A>> extends SimpleQuery<O, A> {
private final A value;
private final boolean valueInclusive;
public LessThan(Attribute<O, A> attribute, A value, boolean valueInclusive) {
super(attribute);
this.value = checkQueryValueNotNull(value);
this.valueInclusive = valueInclusive;
}
public A getValue() {
return value;
}
public boolean isValueInclusive() {
return valueInclusive;
}
@Override
public String toString() {
if (valueInclusive) {
return "lessThanOrEqualTo(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
else {
return "lessThan(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
if (valueInclusive) {
return value.compareTo(attributeValue) >= 0;
}
else {
return value.compareTo(attributeValue) > 0;
}
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
if (valueInclusive) {
for (A attributeValue : attributeValues) {
if (value.compareTo(attributeValue) >= 0) {
return true;
}
}
}
else {
for (A attributeValue : attributeValues) {
if (value.compareTo(attributeValue) > 0) {
return true;
}
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LessThan)) return false;
LessThan lessThan = (LessThan) o;
if (!attribute.equals(lessThan.attribute)) return false;
if (valueInclusive != lessThan.valueInclusive) return false;
if (!value.equals(lessThan.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
result = 31 * result + (valueInclusive ? 1 : 0);
return result;
}
}
| 3,595 | 30 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringEndsWith.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than a {@link CharSequence}-based attribute ends with a given {@link CharSequence}-based suffix.
* @author Niall Gallagher
*/
public class StringEndsWith<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final A value;
/**
* Creates a new {@link SimpleQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public StringEndsWith(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
return matchesValue(attributeValue, queryOptions);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (matchesValue(attributeValue, queryOptions)) {
return true;
}
}
return false;
}
@SuppressWarnings("unused")
public boolean matchesValue(A aValue, QueryOptions queryOptions){
int charsMatched = 0;
for (int i = aValue.length() - 1, j = value.length() - 1; i >= 0 && j >= 0; i--, j--) {
char documentChar = aValue.charAt(i);
char suffixChar = value.charAt(j);
if (documentChar != suffixChar) {
break;
}
charsMatched++;
}
return charsMatched == value.length();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringEndsWith)) return false;
StringEndsWith that = (StringEndsWith) o;
if (!attribute.equals(that.attribute)) return false;
if (!value.equals(that.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public String toString() {
return "endsWith(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
| 3,390 | 31.605769 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringIsContainedIn.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than a {@link CharSequence}-based attribute is contained in a given {@link CharSequence}-based document.
* @author Niall Gallagher
*/
public class StringIsContainedIn<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final A value;
/**
* Creates a new {@link SimpleQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public StringIsContainedIn(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
CharSequence attributeValue = attribute.getValue(object, queryOptions);
// Same as string contains, except we swap the arguments...
return StringContains.containsFragment(value, attributeValue);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
// Same as string contains, except we swap the arguments...
if (StringContains.containsFragment(value, attributeValue)) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringIsContainedIn)) return false;
StringIsContainedIn that = (StringIsContainedIn) o;
if (!attribute.equals(that.attribute)) return false;
if (!value.equals(that.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public String toString() {
return "isContainedIn(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
| 3,104 | 32.387097 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/FilterQuery.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* Extracting a value from an object via an {@link Attribute} can sometimes be expensive, for example if the attribute
* is <i>virtual</i> wherein the data it reads is not already stored in memory, but has to be uncompressed or decoded
* on-the-fly, or if it reads the data on-the-fly from a remote datasource.
* <p/>
* Often there may be an index on such attributes available locally, wherein a copy of the attribute values would be
* available locally in already-decoded form. Indexes would typically report that they can accelerate standard CQEngine
* queries on those attributes. However some queries cannot be accelerated by indexes in a straightforward manner; for
* example queries which perform regular expressions or some other function on the raw data. Indexes are unlikely
* to report that they can natively accelerate regular expression queries, because regular expressions must be evaluated
* by filtering. Therefore CQEngine will typically fall back to evaluating regular expression queries on the fly by
* filtering values returned by <i>the attribute</i> from which the query reads. If reading from the attribute is
* expensive, then it makes sense to allow the query to filter data from the index instead.
* <p/>
* Queries which implement this interface are evaluated by filtering the data contained in an index built on
* the attribute, as opposed to the data returned by the attribute.
* <p/>
* Note that most standard CQEngine queries do not implement this interface, because CQEngine cannot know how expensive
* user-defined attributes are (plus, ordinarily reading from attributes is cheap). If the application requires this
* behaviour for some queries, it can subclass some of the existing queries and have them implement this interface,
* or it can define custom queries which implement this interface.
* <p/>
* Note that the existing {@link StringMatchesRegex} and {@link StringEndsWith} queries are already compatible with this
* interface. To have those queries answered by filtering data in an index instead of from an attribute, <i>subclass
* those queries and declare that they implement this interface</i>. They already implement the required
* {@link #matchesValue(Object, QueryOptions)} method.
*
* @author Silvano Riz
*/
public interface FilterQuery<O, A> extends Query<O>{
/**
* Asserts the value matches the query.
*
* @param value The value to check. It can come from an {@link Attribute} or from any other source, for example an
* {@link com.googlecode.cqengine.index.Index}
* @param queryOptions The {@link QueryOptions}
* @return true if the value matches the query, false otherwise
*/
boolean matchesValue(A value, QueryOptions queryOptions);
}
| 3,577 | 55.793651 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/SimpleQuery.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* The superclass of {@link Query}s which make assertions on attribute values.
*
* @param <A> The type of the attribute on which this query makes assertions
* @param <O> The type of the object containing the attribute
*
* @author Niall Gallagher
*/
public abstract class SimpleQuery<O, A> implements Query<O> {
protected final boolean attributeIsSimple;
protected final Attribute<O, A> attribute;
protected final SimpleAttribute<O, A> simpleAttribute;
// Lazy calculate and cache hash code...
private transient int cachedHashCode = 0;
/**
* Creates a new {@link SimpleQuery} initialized to make assertions on values of the specified attribute
* @param attribute The attribute on which the assertion is to be made
*/
public SimpleQuery(Attribute<O, A> attribute) {
if (attribute == null) {
throw new IllegalArgumentException("The attribute argument was null.");
}
this.attribute = attribute;
if (attribute instanceof SimpleAttribute) {
this.attributeIsSimple = true;
this.simpleAttribute = (SimpleAttribute<O, A>) attribute;
}
else {
this.attributeIsSimple = false;
this.simpleAttribute = null;
}
}
/**
* Returns the type of the attribute originally supplied to the constructor, a shortcut for
* {@link Attribute#getAttributeType()}.
* @return the type of the attribute originally supplied to the constructor
*/
public Class<A> getAttributeType() {
return attribute.getAttributeType();
}
/**
* Returns the name of the attribute originally supplied to the constructor, a shortcut for
* {@link Attribute#getAttributeName()}.
* @return the name of the attribute originally supplied to the constructor
*/
public String getAttributeName() {
return attribute.getAttributeName();
}
/**
* Returns the attribute originally supplied to the constructor.
* @return The attribute originally supplied to the constructor
*/
public Attribute<O, A> getAttribute() {
return attribute;
}
@Override
public final boolean matches(O object, QueryOptions queryOptions) {
if (attributeIsSimple) {
return matchesSimpleAttribute(simpleAttribute, object, queryOptions);
}
else {
return matchesNonSimpleAttribute(attribute, object, queryOptions);
}
}
protected abstract boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions);
protected abstract boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions);
@Override
public int hashCode() {
// Lazy calculate and cache hash code...
int h = this.cachedHashCode;
if (h == 0) { // hash code not cached
h = calcHashCode();
if (h == 0) { // 0 is normally a valid hash code, coalesce with another...
h = -1838660945; // was randomly chosen
}
this.cachedHashCode = h; // cache hash code
}
return h;
}
abstract protected int calcHashCode();
public static String asLiteral(Object value) {
return value instanceof String ? "\"" + value + "\"" : String.valueOf(value);
}
public static String asLiteral(String value) {
return "\"" + value + "\"";
}
}
| 4,334 | 34.532787 | 124 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/Equal.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than an attribute equals a certain value.
*
* @author Niall Gallagher
*/
public class Equal<O, A> extends SimpleQuery<O, A> {
private final A value;
public Equal(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
public String toString() {
return "equal("+ asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
return value.equals(attribute.getValue(object, queryOptions));
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (value.equals(attributeValue)) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Equal)) return false;
Equal equal = (Equal) o;
if (!attribute.equals(equal.attribute)) return false;
if (!value.equals(equal.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
}
| 2,492 | 28.678571 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringIsPrefixOf.java | package com.googlecode.cqengine.query.simple;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
public class StringIsPrefixOf<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final A value;
public StringIsPrefixOf(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
CharSequence attributeValue = attribute.getValue(object, queryOptions);
//swap the order of values
return StringStartsWith.matchesValue(value, attributeValue, queryOptions);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (StringStartsWith.matchesValue(value, attributeValue, queryOptions)) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringIsPrefixOf)) return false;
StringIsPrefixOf<?, ?> that = (StringIsPrefixOf<?, ?>) o;
if (!attribute.equals(that.attribute)) return false;
if (!value.equals(that.value)) return false;
return true;
}
}
| 2,032 | 29.343284 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/All.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SelfAttribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkObjectTypeNotNull;
/**
* A query which matches all objects in the collection.
* <p/>
* This is equivalent to a literal boolean 'true'.
*
* @author ngallagher
*/
public class All<O> extends SimpleQuery<O, O> {
final Class<O> objectType;
public All(Class<O> objectType) {
super(new SelfAttribute<O>(checkObjectTypeNotNull(objectType), "all"));
this.objectType = objectType;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, O> attribute, O object, QueryOptions queryOptions) {
return true;
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, O> attribute, O object, QueryOptions queryOptions) {
return true;
}
@Override
protected int calcHashCode() {
return 765906512; // chosen randomly
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof All)) return false;
All that = (All) o;
return this.objectType.equals(that.objectType);
}
@Override
public String toString() {
return "all(" + super.getAttribute().getObjectType().getSimpleName() + ".class)";
}
} | 2,145 | 30.558824 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/In.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Set;
/**
* Asserts that an attribute has at least one of the values specified by the In query.
*
* @author Silvano Riz
*/
public class In<O, A> extends SimpleQuery<O, A> {
private final Set<A> values;
private final boolean disjoint;
public In(Attribute<O, A> attribute, boolean disjoint, Set<A> values) {
super(attribute);
if (values == null || values.size() == 0){
throw new IllegalArgumentException("The IN query must have at least one value.");
}
this.values = values;
this.disjoint = disjoint;
}
public Set<A> getValues() {
return values;
}
public boolean isDisjoint() {
return disjoint;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
return values.contains(attribute.getValue(object, queryOptions));
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (values.contains(attributeValue)) {
return true;
}
}
return false;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + values.hashCode();
result = 31 * result + (disjoint ? 1 : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof In)) return false;
In<?, ?> in = (In<?, ?>) o;
if (disjoint != in.disjoint) return false;
if (!attribute.equals(in.attribute)) return false;
return values.equals(in.values);
}
@Override
public String toString() {
return "in("+ asLiteral(super.getAttributeName()) +
", " + asLiteral(values) +
")";
}
}
| 2,820 | 29.663043 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/ExistsIn.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.query.simple;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Objects.requireNonNull;
/**
* Asserts than an object exists in a foreign collection, based on an attribute in the local collection being equal
* to an attribute in the foreign collection, and optionally with restrictions applied to objects in the foreign
* collection. This supports the equivalent of SQL EXISTS-type queries and JOINs between IndexedCollections.
* @author ngallagher
* @since 2013-08-27 20:05
*/
public class ExistsIn<O, F, A> extends SimpleQuery<O, A> {
final IndexedCollection<F> foreignCollection;
final Attribute<O, A> localKeyAttribute;
final Attribute<F, A> foreignKeyAttribute;
final Query<F> foreignRestrictions;
public ExistsIn(IndexedCollection<F> foreignCollection, Attribute<O, A> localKeyAttribute, Attribute<F, A> foreignKeyAttribute) {
this(foreignCollection, localKeyAttribute, foreignKeyAttribute, null);
}
public ExistsIn(IndexedCollection<F> foreignCollection, Attribute<O, A> localKeyAttribute, Attribute<F, A> foreignKeyAttribute, Query<F> foreignRestrictions) {
super(requireNonNull(localKeyAttribute, "The localKeyAttribute cannot be null"));
this.foreignCollection = requireNonNull(foreignCollection, "The foreignCollection cannot be null");
this.localKeyAttribute = requireNonNull(localKeyAttribute, "The localKeyAttribute cannot be null");
this.foreignKeyAttribute = requireNonNull(foreignKeyAttribute, "The foreignKeyAttribute cannot be null");
this.foreignRestrictions = foreignRestrictions; // ..this may be null
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A localValue = attribute.getValue(object, queryOptions);
return foreignRestrictions == null
? foreignCollectionContains(foreignCollection, equal(foreignKeyAttribute, localValue))
: foreignCollectionContains(foreignCollection, and(equal(foreignKeyAttribute, localValue), foreignRestrictions));
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
if (foreignRestrictions == null) {
for (A localValue : attribute.getValues(object, queryOptions)) {
boolean contained = foreignCollectionContains(foreignCollection, equal(foreignKeyAttribute, localValue));
if (contained) {
return true;
}
}
return false;
}
else {
for (A localValue : attribute.getValues(object, queryOptions)) {
boolean contained = foreignCollectionContains(foreignCollection, and(equal(foreignKeyAttribute, localValue), foreignRestrictions));
if (contained) {
return true;
}
}
return false;
}
}
@Override
public String toString() {
if (foreignRestrictions == null) {
return "existsIn(" +
"IndexedCollection<" + foreignKeyAttribute.getObjectType().getSimpleName() + ">" +
", " + asLiteral(localKeyAttribute.getAttributeName()) +
", " + asLiteral(foreignKeyAttribute.getAttributeName()) +
")";
}
else {
return "existsIn(" +
"IndexedCollection<" + foreignKeyAttribute.getObjectType().getSimpleName() + ">" +
", " + asLiteral(localKeyAttribute.getAttributeName()) +
", " + asLiteral(foreignKeyAttribute.getAttributeName()) +
", " + foreignRestrictions +
")";
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ExistsIn)) return false;
ExistsIn existsIn = (ExistsIn) o;
if (!foreignKeyAttribute.equals(existsIn.foreignKeyAttribute)) return false;
if (foreignRestrictions != null ? !foreignRestrictions.equals(existsIn.foreignRestrictions) : existsIn.foreignRestrictions != null)
return false;
if (!localKeyAttribute.equals(existsIn.localKeyAttribute)) return false;
// Evaluate equals() on the foreignCollection last, to avoid performance hit if possible...
if (!foreignCollection.equals(existsIn.foreignCollection)) return false;
return true;
}
@Override
protected int calcHashCode() {
// Use identityHashCode() to avoid expensive hashCode computation in case the foreignCollection is large...
int result = System.identityHashCode(foreignCollection);
result = 31 * result + localKeyAttribute.hashCode();
result = 31 * result + foreignKeyAttribute.hashCode();
result = 31 * result + (foreignRestrictions != null ? foreignRestrictions.hashCode() : 0);
return result;
}
/**
* Checks if the given foreign collection contains objects which match the given query.
* @param foreignCollection The foreign collection to check
* @param query The query to check
* @return True if the foreign collection contains one or more objects which match the query, otherwise false
*/
static <F> boolean foreignCollectionContains(IndexedCollection<F> foreignCollection, Query<F> query) {
ResultSet<F> resultSet = foreignCollection.retrieve(query);
try {
return resultSet.isNotEmpty();
}
finally {
resultSet.close();
}
}
}
| 6,586 | 42.913333 | 163 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/GreaterThan.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than an attribute is greater than a lower bound.
* @author Niall Gallagher
*/
public class GreaterThan<O, A extends Comparable<A>> extends SimpleQuery<O, A> {
private final A value;
private final boolean valueInclusive;
public GreaterThan(Attribute<O, A> attribute, A value, boolean valueInclusive) {
super(attribute);
this.value = checkQueryValueNotNull(value);
this.valueInclusive = valueInclusive;
}
public A getValue() {
return value;
}
public boolean isValueInclusive() {
return valueInclusive;
}
@Override
public String toString() {
if (valueInclusive) {
return "greaterThanOrEqualTo(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
else {
return "greaterThan(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
if (valueInclusive) {
return value.compareTo(attributeValue) <= 0;
}
else {
return value.compareTo(attributeValue) < 0;
}
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
if (valueInclusive) {
for (A attributeValue : attributeValues) {
if (value.compareTo(attributeValue) <= 0) {
return true;
}
}
}
else {
for (A attributeValue : attributeValues) {
if (value.compareTo(attributeValue) < 0) {
return true;
}
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GreaterThan)) return false;
GreaterThan that = (GreaterThan) o;
if (!attribute.equals(that.attribute)) return false;
if (valueInclusive != that.valueInclusive) return false;
if (!value.equals(that.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
result = 31 * result + (valueInclusive ? 1 : 0);
return result;
}
}
| 3,599 | 30.304348 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringContains.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than a {@link CharSequence}-based attribute ends with a given {@link CharSequence}-based suffix.
* @author Niall Gallagher
*/
public class StringContains<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final A value;
/**
* Creates a new {@link SimpleQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public StringContains(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
CharSequence attributeValue = attribute.getValue(object, queryOptions);
return containsFragment(attributeValue, value);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (containsFragment(attributeValue, value)) {
return true;
}
}
return false;
}
static boolean containsFragment(CharSequence document, CharSequence fragment) {
final int documentLength = document.length();
final int fragmentLength = fragment.length();
final int lastStartOffset = documentLength - fragmentLength;
for (int startOffset = 0; startOffset <= lastStartOffset; startOffset++) {
int charsMatched = 0;
for (int endOffset = startOffset, j = 0; j < fragmentLength; j++, endOffset++) {
char documentChar = document.charAt(endOffset);
char fragmentChar = fragment.charAt(j);
if (documentChar != fragmentChar) {
break; // break inner loop
}
charsMatched++;
}
if (charsMatched == fragmentLength) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringContains)) return false;
StringContains that = (StringContains) o;
if (!attribute.equals(that.attribute)) return false;
if (!value.equals(that.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public String toString() {
return "contains(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
| 3,782 | 32.776786 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/Between.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than an attribute is between a lower and an upper bound.
* @author Niall Gallagher
*/
public class Between<O, A extends Comparable<A>> extends SimpleQuery<O, A> {
private final A lowerValue;
private final boolean lowerInclusive;
private final A upperValue;
private final boolean upperInclusive;
public Between(Attribute<O, A> attribute, A lowerValue, boolean lowerInclusive, A upperValue, boolean upperInclusive) {
super(attribute);
this.lowerValue = checkQueryValueNotNull(lowerValue);
this.lowerInclusive = lowerInclusive;
this.upperValue = checkQueryValueNotNull(upperValue);
this.upperInclusive = upperInclusive;
}
public A getLowerValue() {
return lowerValue;
}
public boolean isLowerInclusive() {
return lowerInclusive;
}
public A getUpperValue() {
return upperValue;
}
public boolean isUpperInclusive() {
return upperInclusive;
}
@Override
public String toString() {
if (lowerInclusive && upperInclusive) {
return "between(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(lowerValue) +
", " + asLiteral(upperValue) +
")";
}
else {
return "between(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(lowerValue) +
", " + lowerInclusive +
", " + asLiteral(upperValue) +
", " + upperInclusive +
")";
}
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
if (lowerInclusive && upperInclusive) {
if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) >= 0) {
return true;
}
}
else if (lowerInclusive) {
if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) > 0) {
return true;
}
}
else if (upperInclusive) {
if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) >= 0) {
return true;
}
}
else {
if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) > 0) {
return true;
}
}
return false;
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
Iterable<A> attributeValues = attribute.getValues(object, queryOptions);
if (lowerInclusive && upperInclusive) {
for (A attributeValue : attributeValues) {
if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) >= 0) {
return true;
}
}
}
else if (lowerInclusive) {
for (A attributeValue : attributeValues) {
if (lowerValue.compareTo(attributeValue) <= 0 && upperValue.compareTo(attributeValue) > 0) {
return true;
}
}
}
else if (upperInclusive) {
for (A attributeValue : attributeValues) {
if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) >= 0) {
return true;
}
}
}
else {
for (A attributeValue : attributeValues) {
if (lowerValue.compareTo(attributeValue) < 0 && upperValue.compareTo(attributeValue) > 0) {
return true;
}
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Between)) return false;
Between between = (Between) o;
if (!attribute.equals(between.attribute)) return false;
if (lowerInclusive != between.lowerInclusive) return false;
if (upperInclusive != between.upperInclusive) return false;
if (!lowerValue.equals(between.lowerValue)) return false;
if (!upperValue.equals(between.upperValue)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + lowerValue.hashCode();
result = 31 * result + (lowerInclusive ? 1 : 0);
result = 31 * result + upperValue.hashCode();
result = 31 * result + (upperInclusive ? 1 : 0);
return result;
}
}
| 5,728 | 33.721212 | 123 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringMatchesRegex.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.regex.Pattern;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts that an attribute's value matches a regular expression.
* <p/>
* To accelerate {@code matchesRegex(...)} queries, add a Standing Query Index on {@code matchesRegex(...)}.
*
* @author Niall Gallagher, Silvano Riz
*/
public class StringMatchesRegex<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final Pattern regexPattern;
/**
* Creates a new {@link StringMatchesRegex} initialized to make assertions on whether values of the specified
* attribute match the given regular expression pattern.
*
* @param attribute The attribute on which the assertion is to be made
* @param regexPattern The regular expression pattern with which values of the attribute should be tested
*/
public StringMatchesRegex(Attribute<O, A> attribute, Pattern regexPattern) {
super(attribute);
this.regexPattern = checkQueryValueNotNull(regexPattern);
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
return matchesValue(attributeValue, queryOptions);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (matchesValue(attributeValue, queryOptions)) {
return true;
}
}
return false;
}
@SuppressWarnings("unused")
public boolean matchesValue(A aValue, QueryOptions queryOptions){
return regexPattern.matcher(aValue).matches();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringMatchesRegex)) return false;
StringMatchesRegex that = (StringMatchesRegex) o;
return this.attribute.equals(that.attribute)
&& this.regexPattern.pattern().equals(that.regexPattern.pattern())
&& this.regexPattern.flags() == that.regexPattern.flags();
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + regexPattern.hashCode();
return result;
}
@Override
public String toString() {
return "matchesRegex(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(regexPattern.pattern()) + ")";
}
} | 3,444 | 36.043011 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/StringStartsWith.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkQueryValueNotNull;
/**
* Asserts than a {@link CharSequence}-based attribute starts with a given {@link CharSequence}-based prefix.
* @author Niall Gallagher
*/
public class StringStartsWith<O, A extends CharSequence> extends SimpleQuery<O, A> {
private final A value;
/**
* Creates a new {@link SimpleQuery} initialized to make assertions on values of the specified attribute
*
* @param attribute The attribute on which the assertion is to be made
*/
public StringStartsWith(Attribute<O, A> attribute, A value) {
super(attribute);
this.value = checkQueryValueNotNull(value);
}
public A getValue() {
return value;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
A attributeValue = attribute.getValue(object, queryOptions);
return matchesValue(attributeValue, value, queryOptions);
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (matchesValue(attributeValue, value, queryOptions)) {
return true;
}
}
return false;
}
@SuppressWarnings("unused")
public static boolean matchesValue(CharSequence aValue, CharSequence bValue, QueryOptions queryOptions) {
int charsMatched = 0;
for (int i = 0, length = Math.min(aValue.length(), bValue.length()); i < length; i++) {
if (aValue.charAt(i) != bValue.charAt(i)) {
break;
}
charsMatched++;
}
return charsMatched == bValue.length();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringStartsWith)) return false;
StringStartsWith that = (StringStartsWith) o;
if (!attribute.equals(that.attribute)) return false;
if (!value.equals(that.value)) return false;
return true;
}
@Override
protected int calcHashCode() {
int result = attribute.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public String toString() {
return "startsWith(" + asLiteral(super.getAttributeName()) +
", " + asLiteral(value) +
")";
}
}
| 3,373 | 31.757282 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/None.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SelfAttribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.support.QueryValidation.checkObjectTypeNotNull;
/**
* A query which matches no objects in the collection.
* <p/>
* This is equivalent to a literal boolean 'false'.
*
* @author ngallagher
*/
public class None<O> extends SimpleQuery<O, O> {
final Class<O> objectType;
public None(Class<O> objectType) {
super(new SelfAttribute<O>(checkObjectTypeNotNull(objectType), "none"));
this.objectType = objectType;
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, O> attribute, O object, QueryOptions queryOptions) {
return false;
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, O> attribute, O object, QueryOptions queryOptions) {
return false;
}
@Override
protected int calcHashCode() {
return 1357656699; // chosen randomly
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof None)) return false;
None that = (None) o;
return this.objectType.equals(that.objectType);
}
@Override
public String toString() {
return "none(" + super.getAttribute().getObjectType().getSimpleName() + ".class)";
}
} | 2,155 | 30.705882 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/simple/Has.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.query.simple;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* Asserts that an attribute has a value (is not null).
*
* @author Niall Gallagher
*/
public class Has<O, A> extends SimpleQuery<O, A> {
public Has(Attribute<O, A> attribute) {
super(attribute);
}
@Override
public String toString() {
return "has(" + asLiteral(super.getAttributeName()) + ")";
}
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
return attribute.getValue(object, queryOptions) != null;
}
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
for (A attributeValue : attribute.getValues(object, queryOptions)) {
if (attributeValue != null) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Has)) return false;
Has equal = (Has) o;
if (!attribute.equals(equal.attribute)) return false;
return true;
}
@Override
protected int calcHashCode() {
return attribute.hashCode();
}
}
| 2,045 | 28.228571 | 116 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/support/QueryValidation.java | /**
* Copyright 2012-2019 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.query.support;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
/**
* Contains static helper methods for validating query arguments.
*/
public class QueryValidation {
public static <T> T checkQueryValueNotNull(T value) {
return Objects.requireNonNull(value, "The value supplied to a query cannot be null. To check for null values, you should instead use a has() query to check if an attribute value exists, or use a not(has()) query to check if an attribute value does not exist.");
}
public static <T> Class<T> checkObjectTypeNotNull(Class<T> objectType) {
return requireNonNull(objectType, "The objectType supplied to a query cannot be null");
}
}
| 1,351 | 36.555556 | 269 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/logical/Or.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.query.logical;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collection;
import java.util.Iterator;
/**
* Represents a logical OR on child queries, which when evaluated yields the set union of the result sets
* from child queries.
*
* @author ngallagher
* @since 2012-04-30 17:00
*/
public class Or<O> extends LogicalQuery<O> {
private final boolean disjoint;
/**
* Constructor.
* <p/>
* Delegates to {@link #Or(java.util.Collection, boolean)} supplying false for disjointness.
*
* @param childQueries Child queries for which a set union is required
*/
public Or(Collection<Query<O>> childQueries) {
this(childQueries, false);
}
/**
* Constructor with a hint regarding deduplication.
*
* @param childQueries Child queries for which a set union is required
* @param disjoint A hint to the query engine: if true indicates that results from the child queries will be
* disjoint and so there will be no need to perform deduplication; if false disjointness is unknown, deduplication
* might be required
*/
public Or(Collection<Query<O>> childQueries, boolean disjoint) {
super(childQueries);
if (this.size() < 2) {
throw new IllegalStateException("An 'Or' query cannot have fewer than 2 child queries, " + childQueries.size() + " were supplied");
}
this.disjoint = disjoint;
}
/**
* Returns true if at least one child query matches the given object, returns false if none match.
* @return true if at least one child query matches the given object, returns false if none match
*/
@Override
public boolean matches(O object, QueryOptions queryOptions) {
if (super.hasComparativeQueries()) {
throw new UnsupportedOperationException("This method is not supported on logical queries which encapsulate comparative queries");
}
for (Query<O> query : super.getSimpleQueries()) {
if (query.matches(object, queryOptions)) {
return true;
}
}
for (Query<O> query : super.getLogicalQueries()) {
if (query.matches(object, queryOptions)) {
return true;
}
}
// No queries evaluated true...
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Or)) return false;
Or or = (Or) o;
if (disjoint != or.disjoint) return false;
if (!childQueries.equals(or.childQueries)) return false;
return true;
}
/**
* Returns the value of the <code>disjoint</code> flag supplied to the constructor
* {@link #Or(java.util.Collection, boolean)}.
* @return The value of the <code>disjoint</code> flag supplied to the constructor
*/
public boolean isDisjoint() {
return disjoint;
}
@Override
protected int calcHashCode() {
int result = childQueries.hashCode();
result = 31 * result + (disjoint ? 1 : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("or(");
for (Iterator<Query<O>> iterator = childQueries.iterator(); iterator.hasNext(); ) {
Query<O> childQuery = iterator.next();
sb.append(childQuery);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
}
| 4,280 | 32.445313 | 143 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/logical/And.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.query.logical;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collection;
import java.util.Iterator;
/**
* Represents a logical AND on child queries, which when evaluated yields the set intersection of the result sets
* from child queries.
*
* @author ngallagher
* @since 2012-04-30 17:00
*/
public class And<O> extends LogicalQuery<O> {
public And(Collection<Query<O>> childQueries) {
super(childQueries);
if (this.size() < 2) {
throw new IllegalStateException("An 'And' query cannot have fewer than 2 child queries, " + childQueries.size() + " were supplied");
}
}
/**
* Returns true if and only if all child queries matches the given object, otherwise returns false.
* @return True if and only if all child queries matches the given object, otherwise returns false
*/
@Override
public boolean matches(O object, QueryOptions queryOptions) {
if (super.hasComparativeQueries()) {
throw new UnsupportedOperationException("This method is not supported on logical queries which encapsulate comparative queries");
}
for (Query<O> query : super.getSimpleQueries()) {
if (!query.matches(object, queryOptions)) {
return false;
}
}
for (Query<O> query : super.getLogicalQueries()) {
if (!query.matches(object, queryOptions)) {
return false;
}
}
// No queries evaluated false therefore all evaluated true...
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof And)) return false;
And and = (And) o;
if (!childQueries.equals(and.childQueries)) return false;
return true;
}
@Override
protected int calcHashCode() {
return childQueries.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("and(");
for (Iterator<Query<O>> iterator = childQueries.iterator(); iterator.hasNext(); ) {
Query<O> childQuery = iterator.next();
sb.append(childQuery);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
}
| 3,076 | 31.389474 | 144 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/logical/LogicalQuery.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.query.logical;
import com.googlecode.cqengine.query.ComparativeQuery;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.simple.SimpleQuery;
import java.util.*;
/**
* The superclass of {@link Query}s which logically connect other queries together to form complex queries.
*
* @param <O> The type of the object containing the attributes on which child queries in the query make assertions
*
* @author ngallagher
* @since 2012-04-30 16:56
*/
public abstract class LogicalQuery<O> implements Query<O> {
protected final Collection<Query<O>> childQueries;
private final List<LogicalQuery<O>> logicalQueries = new ArrayList<LogicalQuery<O>>();
private final List<SimpleQuery<O, ?>> simpleQueries = new ArrayList<SimpleQuery<O, ?>>();
private final List<ComparativeQuery<O, ?>> comparativeQueries = new ArrayList<ComparativeQuery<O, ?>>();
private final boolean hasLogicalQueries;
private final boolean hasSimpleQueries;
private final boolean hasComparativeQueries;
private final int size;
// Lazy calculate and cache hash code...
private transient int cachedHashCode = 0;
/**
* Creates a new {@link LogicalQuery} initialized to logically connect the supplied set of child queries.
*
* @param childQueries The child queries which this {@code LogicalQuery} is to logically connect
*/
public LogicalQuery(Collection<Query<O>> childQueries) {
Objects.requireNonNull(childQueries, "The child queries supplied to a logical query cannot be null");
for (Query<O> query : childQueries) {
if (query instanceof LogicalQuery) {
logicalQueries.add((LogicalQuery<O>) query);
}
else if (query instanceof SimpleQuery) {
simpleQueries.add((SimpleQuery<O, ?>) query);
}
else if (query instanceof ComparativeQuery) {
comparativeQueries.add((ComparativeQuery<O, ?>) query);
}
else {
throw new IllegalStateException("Unexpected type of query: " + (query == null ? null : query + ", " + query.getClass()));
}
}
this.hasLogicalQueries = !logicalQueries.isEmpty();
this.hasSimpleQueries = !simpleQueries.isEmpty();
this.hasComparativeQueries = !comparativeQueries.isEmpty();
this.size = childQueries.size();
this.childQueries = childQueries;
}
/**
* Returns a collection of child queries which are themselves {@link LogicalQuery}s.
* @return a collection of child queries which are themselves {@link LogicalQuery}s
*/
public List<LogicalQuery<O>> getLogicalQueries() {
return logicalQueries;
}
/**
* Returns a collection of child queries which are themselves {@link SimpleQuery}s.
* @return a collection of child queries which are themselves {@link SimpleQuery}s
*/
public List<SimpleQuery<O, ?>> getSimpleQueries() {
return simpleQueries;
}
/**
* Returns a collection of child queries which are themselves {@link ComparativeQuery}s.
* @return a collection of child queries which are themselves {@link ComparativeQuery}s
*/
public List<ComparativeQuery<O, ?>> getComparativeQueries() {
return comparativeQueries;
}
/**
* The entire collection of child queries, which may be either {@link SimpleQuery}s or {@link LogicalQuery}s.
* @return The entire collection of child queries, which may be either {@link SimpleQuery}s or {@link LogicalQuery}s.
*/
public Collection<Query<O>> getChildQueries() {
return childQueries;
}
/**
* Returns true if this logical query has child queries which are themselves {@link LogicalQuery}s.
* @return true if this logical query has child queries which are themselves {@link LogicalQuery}s,
* false if this logical query has no child queries which are themselves {@link LogicalQuery}s
*/
public boolean hasLogicalQueries() {
return hasLogicalQueries;
}
/**
* Returns true if this logical query has child queries which are themselves {@link SimpleQuery}s.
* @return true if this logical query has child queries which are themselves {@link SimpleQuery}s,
* false if this logical query has no child queries which are themselves {@link SimpleQuery}s
*/
public boolean hasSimpleQueries() {
return hasSimpleQueries;
}
/**
* Returns true if this logical query has child queries which are themselves {@link ComparativeQuery}s.
* @return true if this logical query has child queries which are themselves {@link ComparativeQuery}s,
* false if this logical query has no child queries which are themselves {@link ComparativeQuery}s
*/
public boolean hasComparativeQueries() {
return hasComparativeQueries;
}
/**
* Returns the total number of child queries (both logical and simple).
* @return the total number of child queries (both logical and simple)
*/
public int size() {
return size;
}
@Override
public int hashCode() {
// Lazy calculate and cache hash code...
int h = this.cachedHashCode;
if (h == 0) { // hash code not cached
h = calcHashCode();
if (h == 0) { // 0 is normally a valid hash code, coalesce with another...
h = -976419167; // was randomly chosen
}
this.cachedHashCode = h; // cache hash code
}
return h;
}
abstract protected int calcHashCode();
}
| 6,256 | 38.853503 | 137 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/logical/Not.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.query.logical;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collections;
import static java.util.Objects.requireNonNull;
/**
* Represents a logical negation on a child query, which when evaluated yields the set complement of the result set
* from the child query.
*
* @author ngallagher
* @since 2012-04-30 17:00
*/
public class Not<O> extends LogicalQuery<O> {
private final Query<O> negatedQuery;
public Not(Query<O> negatedQuery) {
super(Collections.singleton(requireNonNull(negatedQuery, "The negated query cannot be null")));
this.negatedQuery = negatedQuery;
}
public Query<O> getNegatedQuery() {
return negatedQuery;
}
/**
* Returns the <i>inverse</i> of whether the negated query matches the given object.
* @return The <i>inverse</i> of whether the negated query matches the given object
*/
@Override
public boolean matches(O object, QueryOptions queryOptions) {
return !negatedQuery.matches(object, queryOptions);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Not)) return false;
Not other = (Not) o;
if (!negatedQuery.equals(other.negatedQuery)) return false;
return true;
}
@Override
protected int calcHashCode() {
return negatedQuery.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("not(");
sb.append(negatedQuery);
sb.append(")");
return sb.toString();
}
}
| 2,308 | 27.8625 | 115 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/CQNParser.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.query.parser.cqn;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.parser.common.ParseResult;
import com.googlecode.cqengine.query.parser.common.QueryParser;
import com.googlecode.cqengine.query.parser.common.InvalidQueryException;
import com.googlecode.cqengine.query.parser.cqn.grammar.CQNGrammarLexer;
import com.googlecode.cqengine.query.parser.cqn.grammar.CQNGrammarParser;
import com.googlecode.cqengine.query.parser.cqn.support.*;
import com.googlecode.cqengine.query.parser.cqn.support.StringParser;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.Map;
/**
* A parser for CQN queries - CQEngine-Native syntax.
* <p/>
* CQN syntax is based on how CQEngine queries look in native Java code, and the format returned by
* {@link Query#toString()}.
*
* @author Niall Gallagher
*/
public class CQNParser<O> extends QueryParser<O> {
public CQNParser(Class<O> objectType) {
super(objectType);
StringParser stringParser = new StringParser();
super.registerValueParser(String.class, stringParser);
super.registerFallbackValueParser(new FallbackValueParser(stringParser));
}
@Override
public ParseResult<O> parse(String query) {
try {
if (query == null) {
throw new IllegalArgumentException("Query was null");
}
CQNGrammarLexer lexer = new CQNGrammarLexer(new ANTLRInputStream(query));
lexer.removeErrorListeners();
lexer.addErrorListener(SYNTAX_ERROR_LISTENER);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CQNGrammarParser parser = new CQNGrammarParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(SYNTAX_ERROR_LISTENER);
CQNGrammarParser.StartContext queryContext = parser.start();
ParseTreeWalker walker = new ParseTreeWalker();
CQNAntlrListener<O> listener = new CQNAntlrListener<O>(this);
walker.walk(listener, queryContext);
return new ParseResult<O>(listener.getParsedQuery(), listener.getQueryOptions());
}
catch (InvalidQueryException e) {
throw e;
}
catch (Exception e) {
throw new InvalidQueryException("Failed to parse query", e);
}
}
/**
* Creates a new CQNParser for the given POJO class.
* @param pojoClass The type of object stored in the collection
* @return a new CQNParser for the given POJO class
*/
public static <O> CQNParser<O> forPojo(Class<O> pojoClass) {
return new CQNParser<O>(pojoClass);
}
/**
* Creates a new CQNParser for the given POJO class, and registers the given attributes with it.
* @param pojoClass The type of object stored in the collection
* @param attributes The attributes to register with the parser
* @return a new CQNParser for the given POJO class
*/
public static <O> CQNParser<O> forPojoWithAttributes(Class<O> pojoClass, Map<String, ? extends Attribute<O, ?>> attributes) {
CQNParser<O> parser = forPojo(pojoClass);
parser.registerAttributes(attributes);
return parser;
}
}
| 3,951 | 38.128713 | 129 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/support/FallbackValueParser.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.query.parser.cqn.support;
import com.googlecode.cqengine.query.parser.common.ValueParser;
import java.lang.reflect.Method;
/**
* Parses values using a static {@code valueOf()} method in the type's class.
* <p/>
* Created by npgall on 25/05/2015.
*/
public class FallbackValueParser extends ValueParser<Object> {
final StringParser stringParser;
public FallbackValueParser(StringParser stringParser) {
this.stringParser = stringParser;
}
@Override
protected Object parse(Class<?> valueType, String stringValue) {
try {
stringValue = stringParser.parse(String.class, stringValue);
Method valueOf = valueType.getMethod("valueOf", String.class);
return valueType.cast(valueOf.invoke(null, stringValue));
}
catch (Exception e) {
throw new IllegalStateException("Failed to parse value using a valueOf() method in class '" + valueType.getName() + "': " + stringValue, e);
}
}
}
| 1,629 | 33.680851 | 152 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/support/CQNAntlrListener.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.query.parser.cqn.support;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.query.option.AttributeOrder;
import com.googlecode.cqengine.query.option.OrderByOption;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.parser.common.QueryParser;
import com.googlecode.cqengine.query.parser.cqn.grammar.CQNGrammarBaseListener;
import com.googlecode.cqengine.query.parser.cqn.grammar.CQNGrammarParser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.query.QueryFactory.orderBy;
import static com.googlecode.cqengine.query.QueryFactory.queryOptions;
import static com.googlecode.cqengine.query.parser.common.ParserUtils.*;
/**
* @author Niall Gallagher
*/
public class CQNAntlrListener<O> extends CQNGrammarBaseListener {
/*
NOTE: this class depends on classes auto-generated by the antlr4-maven-plugin.
Run "mvn clean compile" to generate those classes.
*/
protected final QueryParser<O> queryParser;
// A map of parent context, to parsed child queries belonging to that context...
protected final Map<ParserRuleContext, Collection<Query<O>>> childQueries = new HashMap<ParserRuleContext, Collection<Query<O>>>();
protected int numQueriesEncountered = 0;
protected int numQueriesParsed = 0;
protected final List<AttributeOrder<O>> attributeOrders = new LinkedList<AttributeOrder<O>>();
public CQNAntlrListener(QueryParser<O> queryParser) {
this.queryParser = queryParser;
}
// ======== Handler methods for each type of query defined in the antlr grammar... ========
@Override
public void exitAndQuery(CQNGrammarParser.AndQueryContext ctx) {
addParsedQuery(ctx, new And<O>(childQueries.get(ctx)));
}
@Override
public void exitOrQuery(CQNGrammarParser.OrQueryContext ctx) {
addParsedQuery(ctx, new Or<O>(childQueries.get(ctx)));
}
@Override
public void exitNotQuery(CQNGrammarParser.NotQueryContext ctx) {
addParsedQuery(ctx, QueryFactory.not(childQueries.get(ctx).iterator().next()));
}
@Override
public void exitEqualQuery(CQNGrammarParser.EqualQueryContext ctx) {
Attribute<O, Object> attribute = queryParser.getAttribute(ctx.attributeName(), Object.class);
Object value = queryParser.parseValue(attribute, ctx.queryParameter());
addParsedQuery(ctx, QueryFactory.equal(attribute, value));
}
@Override
@SuppressWarnings("unchecked")
public void exitLessThanOrEqualToQuery(CQNGrammarParser.LessThanOrEqualToQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
Comparable value = queryParser.parseValue(attribute, ctx.queryParameter());
addParsedQuery(ctx, QueryFactory.lessThanOrEqualTo(attribute, value));
}
@Override
@SuppressWarnings("unchecked")
public void exitLessThanQuery(CQNGrammarParser.LessThanQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
Comparable value = queryParser.parseValue(attribute, ctx.queryParameter());
addParsedQuery(ctx, QueryFactory.lessThan(attribute, value));
}
@Override
@SuppressWarnings("unchecked")
public void exitGreaterThanOrEqualToQuery(CQNGrammarParser.GreaterThanOrEqualToQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
Comparable value = queryParser.parseValue(attribute, ctx.queryParameter());
addParsedQuery(ctx, QueryFactory.greaterThanOrEqualTo(attribute, value));
}
@Override
@SuppressWarnings("unchecked")
public void exitGreaterThanQuery(CQNGrammarParser.GreaterThanQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
Comparable value = queryParser.parseValue(attribute, ctx.queryParameter());
addParsedQuery(ctx, QueryFactory.greaterThan(attribute, value));
}
@Override
@SuppressWarnings("unchecked")
public void exitVerboseBetweenQuery(CQNGrammarParser.VerboseBetweenQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
List<? extends ParseTree> queryParameters = ctx.queryParameter(), booleanParameters = ctx.BooleanLiteral();
Comparable lowerValue = queryParser.parseValue(attribute, queryParameters.get(0));
boolean lowerInclusive = queryParser.parseValue(Boolean.class, booleanParameters.get(0));
Comparable upperValue = queryParser.parseValue(attribute, queryParameters.get(1));
boolean upperInclusive = queryParser.parseValue(Boolean.class, booleanParameters.get(1));
addParsedQuery(ctx, QueryFactory.between(attribute, lowerValue, lowerInclusive, upperValue, upperInclusive));
}
@Override
@SuppressWarnings("unchecked")
public void exitBetweenQuery(CQNGrammarParser.BetweenQueryContext ctx) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(ctx.attributeName(), Comparable.class);
List<? extends ParseTree> queryParameters = ctx.queryParameter();
Comparable lowerValue = queryParser.parseValue(attribute, queryParameters.get(0));
Comparable upperValue = queryParser.parseValue(attribute, queryParameters.get(1));
addParsedQuery(ctx, QueryFactory.between(attribute, lowerValue, upperValue));
}
@Override
@SuppressWarnings("unchecked")
public void exitInQuery(CQNGrammarParser.InQueryContext ctx) {
Attribute<O, Object> attribute = queryParser.getAttribute(ctx.attributeName(), Object.class);
List<? extends ParseTree> queryParameters = ctx.queryParameter();
Collection<Object> values = new ArrayList<Object>(queryParameters.size());
for (ParseTree queryParameter : queryParameters) {
Object value = queryParser.parseValue(attribute, queryParameter);
values.add(value);
}
addParsedQuery(ctx, QueryFactory.in(attribute, values));
}
@Override
public void exitStartsWithQuery(CQNGrammarParser.StartsWithQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.startsWith(attribute, value));
}
@Override
public void exitEndsWithQuery(CQNGrammarParser.EndsWithQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.endsWith(attribute, value));
}
@Override
public void exitContainsQuery(CQNGrammarParser.ContainsQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.contains(attribute, value));
}
@Override
public void exitIsContainedInQuery(CQNGrammarParser.IsContainedInQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.isContainedIn(attribute, value));
}
@Override
public void exitMatchesRegexQuery(CQNGrammarParser.MatchesRegexQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.matchesRegex(attribute, value));
}
@Override
public void exitHasQuery(CQNGrammarParser.HasQueryContext ctx) {
Attribute<O, Object> attribute = queryParser.getAttribute(ctx.attributeName(), Object.class);
addParsedQuery(ctx, QueryFactory.has(attribute));
}
@Override
public void exitAllQuery(CQNGrammarParser.AllQueryContext ctx) {
validateObjectTypeParameter(queryParser.getObjectType(), ctx.objectType().getText());
addParsedQuery(ctx, QueryFactory.all(queryParser.getObjectType()));
}
@Override
public void exitNoneQuery(CQNGrammarParser.NoneQueryContext ctx) {
validateObjectTypeParameter(queryParser.getObjectType(), ctx.objectType().getText());
addParsedQuery(ctx, QueryFactory.none(queryParser.getObjectType()));
}
@Override
public void exitLongestPrefixQuery(CQNGrammarParser.LongestPrefixQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.longestPrefix(attribute, value));
}
@Override
public void exitIsPrefixOfQuery(CQNGrammarParser.IsPrefixOfQueryContext ctx) {
Attribute<O, String> attribute = queryParser.getAttribute(ctx.attributeName(), String.class);
String value = queryParser.parseValue(attribute, ctx.stringQueryParameter());
addParsedQuery(ctx, QueryFactory.isPrefixOf(attribute, value));
}
/** This handler is called for all queries, allows us to validate that no handlers are missing. */
@Override
public void exitQuery(CQNGrammarParser.QueryContext ctx) {
numQueriesEncountered++;
validateAllQueriesParsed(numQueriesEncountered, numQueriesParsed);
}
@Override
public void exitOrderByOption(CQNGrammarParser.OrderByOptionContext ctx) {
for (CQNGrammarParser.AttributeOrderContext attributeOrderContext : ctx.attributeOrder()) {
Attribute<O, Comparable> attribute = queryParser.getAttribute(attributeOrderContext.attributeName(), Comparable.class);
boolean descending = "descending".equals(attributeOrderContext.direction().getText());
attributeOrders.add(new AttributeOrder<O>(attribute, descending));
}
}
// ======== Utility methods... ========
/**
* Adds the given query to a list of child queries which have not yet been wrapped in a parent query.
*/
void addParsedQuery(ParserRuleContext currentContext, Query<O> parsedQuery) {
// Retrieve the possibly null parent query...
ParserRuleContext parentContext = getParentContextOfType(currentContext, getAndOrNotContextClasses());
Collection<Query<O>> childrenOfParent = this.childQueries.get(parentContext);
if (childrenOfParent == null) {
childrenOfParent = new ArrayList<Query<O>>();
this.childQueries.put(parentContext, childrenOfParent); // parentContext will be null if this is root query
}
childrenOfParent.add(parsedQuery);
numQueriesParsed++;
}
/**
* Can be called when parsing has finished, to retrieve the parsed query.
*/
public Query<O> getParsedQuery() {
Collection<Query<O>> rootQuery = childQueries.get(null);
validateExpectedNumberOfChildQueries(1, rootQuery.size());
return rootQuery.iterator().next();
}
/**
* Can be called when parsing has finished, to retrieve the {@link QueryOptions}, which may include an
* {@link OrderByOption} if found in the string query.
*
* @return The parsed {@link QueryOptions}
*/
public QueryOptions getQueryOptions() {
return attributeOrders.isEmpty() ? noQueryOptions() : queryOptions(orderBy(attributeOrders));
}
protected Class[] getAndOrNotContextClasses() {
return new Class[] {CQNGrammarParser.AndQueryContext.class, CQNGrammarParser.OrQueryContext.class, CQNGrammarParser.NotQueryContext.class};
}
}
| 13,071 | 46.191336 | 147 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/support/StringParser.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.query.parser.cqn.support;
import com.googlecode.cqengine.query.parser.common.ValueParser;
/**
* @author Niall Gallagher
*/
public class StringParser extends ValueParser<String> {
@Override
public String parse(Class<? extends String> valueType, String stringValue) {
return stripQuotes(stringValue);
}
public static String stripQuotes(String stringValue) {
int length = stringValue.length();
if (length >= 2 && stringValue.charAt(0) == '\"' && stringValue.charAt(length - 1) == '\"') {
return stringValue.substring(1, length - 1);
}
return stringValue;
}
}
| 1,270 | 32.447368 | 101 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/support/DateMathParser.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.query.parser.cqn.support;
import com.googlecode.cqengine.query.parser.common.ValueParser;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Parses date math expressions into {@link java.util.Date} objects, using {@link ApacheSolrDataMathParser}.
* <p/>
* Examples:
* <pre>
* /HOUR
* ... Round to the start of the current hour
* /DAY
* ... Round to the start of the current day
* +2YEARS
* ... Exactly two years in the future from now
* -1DAY
* ... Exactly 1 day prior to now
* /DAY+6MONTHS+3DAYS
* ... 6 months and 3 days in the future from the start of
* the current day
* +6MONTHS+3DAYS/DAY
* ... 6 months and 3 days in the future from now, rounded
* down to nearest day
* </pre>
* See {@link ApacheSolrDataMathParser} for more details.
*
* @author niall.gallagher
*/
public class DateMathParser extends ValueParser<Date> {
final TimeZone timeZone;
final Locale locale;
final Date now;
public DateMathParser() {
this(ApacheSolrDataMathParser.DEFAULT_MATH_TZ, ApacheSolrDataMathParser.DEFAULT_MATH_LOCALE, null);
}
public DateMathParser(Date now) {
this(ApacheSolrDataMathParser.DEFAULT_MATH_TZ, ApacheSolrDataMathParser.DEFAULT_MATH_LOCALE, now);
}
public DateMathParser(TimeZone timeZone, Locale locale) {
this(timeZone, locale, null);
}
public DateMathParser(TimeZone timeZone, Locale locale, Date now) {
this.timeZone = timeZone;
this.locale = locale;
this.now = now;
}
@Override
protected Date parse(Class<? extends Date> valueType, String stringValue) {
try {
ApacheSolrDataMathParser solrParser = new ApacheSolrDataMathParser();
if (now != null) {
solrParser.setNow(now);
}
return solrParser.parseMath(stripQuotes(stringValue));
}
catch (Exception e) {
throw new IllegalStateException("Failed to parse date math expression: " + stringValue, e);
}
}
protected String stripQuotes(String stringValue) {
return StringParser.stripQuotes(stringValue);
}
}
| 2,847 | 30.296703 | 108 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/cqn/support/ApacheSolrDataMathParser.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.query.parser.cqn.support;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.text.ParseException;
import java.util.regex.Pattern;
/**
* This class (Apache license) is copied from Apache Solr:
* http://grepcode.com/file_/repo1.maven.org/maven2/org.apache.solr/solr-core/4.7.2/org/apache/solr/util/DateMathParser.java/?v=source
*
*
* A Simple Utility class for parsing "math" like strings relating to Dates.
*
* <p>
* The basic syntax support addition, subtraction and rounding at various
* levels of granularity (or "units"). Commands can be chained together
* and are parsed from left to right. '+' and '-' denote addition and
* subtraction, while '/' denotes "round". Round requires only a unit, while
* addition/subtraction require an integer value and a unit.
* Command strings must not include white space, but the "No-Op" command
* (empty string) is allowed....
* </p>
*
* <pre>
* /HOUR
* ... Round to the start of the current hour
* /DAY
* ... Round to the start of the current day
* +2YEARS
* ... Exactly two years in the future from now
* -1DAY
* ... Exactly 1 day prior to now
* /DAY+6MONTHS+3DAYS
* ... 6 months and 3 days in the future from the start of
* the current day
* +6MONTHS+3DAYS/DAY
* ... 6 months and 3 days in the future from now, rounded
* down to nearest day
* </pre>
*
* <p>
* (Multiple aliases exist for the various units of time (ie:
* <code>MINUTE</code> and <code>MINUTES</code>; <code>MILLI</code>,
* <code>MILLIS</code>, <code>MILLISECOND</code>, and
* <code>MILLISECONDS</code>.) The complete list can be found by
* inspecting the keySet of {@link #CALENDAR_UNITS})
* </p>
*
* <p>
* All commands are relative to a "now" which is fixed in an instance of
* ApacheSolrDataMathParser such that
* <code>p.parseMath("+0MILLISECOND").equals(p.parseMath("+0MILLISECOND"))</code>
* no matter how many wall clock milliseconds elapse between the two
* distinct calls to parse (Assuming no other thread calls
* "<code>setNow</code>" in the interim). The default value of 'now' is
* the time at the moment the <code>ApacheSolrDataMathParser</code> instance is
* constructed, unless overridden by the {@code CommonParams#NOW NOW}
* request param.
* </p>
*
* <p>
* All commands are also affected to the rules of a specified {@link TimeZone}
* (including the start/end of DST if any) which determine when each arbitrary
* day starts. This not only impacts rounding/adding of DAYs, but also
* cascades to rounding of HOUR, MIN, MONTH, YEAR as well. The default
* <code>TimeZone</code> used is <code>UTC</code> unless overridden by the
* {@code CommonParams#TZ TZ}
* request param.
* </p>
*/
public class ApacheSolrDataMathParser {
public static TimeZone UTC = TimeZone.getTimeZone("UTC");
/** Default TimeZone for DateMath rounding (UTC) */
public static final TimeZone DEFAULT_MATH_TZ = UTC;
/** Default Locale for DateMath rounding (Locale.ROOT) */
public static final Locale DEFAULT_MATH_LOCALE = Locale.ROOT;
/**
* A mapping from (uppercased) String labels idenyifying time units,
* to the corresponding Calendar constant used to set/add/roll that unit
* of measurement.
*
* <p>
* A single logical unit of time might be represented by multiple labels
* for convenience (ie: <code>DATE==DAY</code>,
* <code>MILLI==MILLISECOND</code>)
* </p>
*
* @see Calendar
*/
public static final Map<String,Integer> CALENDAR_UNITS = makeUnitsMap();
/** @see #CALENDAR_UNITS */
private static Map<String,Integer> makeUnitsMap() {
// NOTE: consciously choosing not to support WEEK at this time,
// because of complexity in rounding down to the nearest week
// arround a month/year boundry.
// (Not to mention: it's not clear what people would *expect*)
//
// If we consider adding some time of "week" support, then
// we probably need to change "Locale loc" to default to something
// from a param via SolrRequestInfo as well.
Map<String,Integer> units = new HashMap<String,Integer>(13);
units.put("YEAR", Calendar.YEAR);
units.put("YEARS", Calendar.YEAR);
units.put("MONTH", Calendar.MONTH);
units.put("MONTHS", Calendar.MONTH);
units.put("DAY", Calendar.DATE);
units.put("DAYS", Calendar.DATE);
units.put("DATE", Calendar.DATE);
units.put("HOUR", Calendar.HOUR_OF_DAY);
units.put("HOURS", Calendar.HOUR_OF_DAY);
units.put("MINUTE", Calendar.MINUTE);
units.put("MINUTES", Calendar.MINUTE);
units.put("SECOND", Calendar.SECOND);
units.put("SECONDS", Calendar.SECOND);
units.put("MILLI", Calendar.MILLISECOND);
units.put("MILLIS", Calendar.MILLISECOND);
units.put("MILLISECOND", Calendar.MILLISECOND);
units.put("MILLISECONDS",Calendar.MILLISECOND);
return units;
}
/**
* Modifies the specified Calendar by "adding" the specified value of units
*
* @exception IllegalArgumentException if unit isn't recognized.
* @see #CALENDAR_UNITS
*/
public static void add(Calendar c, int val, String unit) {
Integer uu = CALENDAR_UNITS.get(unit);
if (null == uu) {
throw new IllegalArgumentException("Adding Unit not recognized: "
+ unit);
}
c.add(uu.intValue(), val);
}
/**
* Modifies the specified Calendar by "rounding" down to the specified unit
*
* @exception IllegalArgumentException if unit isn't recognized.
* @see #CALENDAR_UNITS
*/
public static void round(Calendar c, String unit) {
Integer uu = CALENDAR_UNITS.get(unit);
if (null == uu) {
throw new IllegalArgumentException("Rounding Unit not recognized: "
+ unit);
}
int u = uu.intValue();
switch (u) {
case Calendar.YEAR:
c.clear(Calendar.MONTH);
/* fall through */
case Calendar.MONTH:
c.clear(Calendar.DAY_OF_MONTH);
c.clear(Calendar.DAY_OF_WEEK);
c.clear(Calendar.DAY_OF_WEEK_IN_MONTH);
c.clear(Calendar.DAY_OF_YEAR);
c.clear(Calendar.WEEK_OF_MONTH);
c.clear(Calendar.WEEK_OF_YEAR);
/* fall through */
case Calendar.DATE:
c.clear(Calendar.HOUR_OF_DAY);
c.clear(Calendar.HOUR);
c.clear(Calendar.AM_PM);
/* fall through */
case Calendar.HOUR_OF_DAY:
c.clear(Calendar.MINUTE);
/* fall through */
case Calendar.MINUTE:
c.clear(Calendar.SECOND);
/* fall through */
case Calendar.SECOND:
c.clear(Calendar.MILLISECOND);
break;
default:
throw new IllegalStateException
("No logic for rounding value ("+u+") " + unit);
}
}
private TimeZone zone;
private Locale loc;
private Date now;
/**
* Default constructor that assumes UTC should be used for rounding unless
* otherwise specified in the SolrRequestInfo
*
* @see #DEFAULT_MATH_LOCALE
*/
public ApacheSolrDataMathParser() {
this(null, DEFAULT_MATH_LOCALE);
}
/**
* @param tz The TimeZone used for rounding (to determine when hours/days begin). If null, then this method defaults to the value dicated by the SolrRequestInfo if it
* exists -- otherwise it uses UTC.
* @param l The Locale used for rounding (to determine when weeks begin). If null, then this method defaults to en_US.
* @see #DEFAULT_MATH_TZ
* @see #DEFAULT_MATH_LOCALE
* @see Calendar#getInstance(TimeZone,Locale)
*/
public ApacheSolrDataMathParser(TimeZone tz, Locale l) {
loc = (l == null) ? DEFAULT_MATH_LOCALE : l;
tz = (tz == null) ? DEFAULT_MATH_TZ : tz;
zone = tz;
}
/**
* Defines this instance's concept of "now".
* @see #getNow
*/
public void setNow(Date n) {
now = n;
}
/**
* Returns a cloned of this instance's concept of "now".
*
* If setNow was never called (or if null was specified) then this method
* first defines 'now' as the value dictated by the SolrRequestInfo if it
* exists -- otherwise it uses a new Date instance at the moment getNow()
* is first called.
* @see #setNow
*/
public Date getNow() {
if (now == null) {
now = new Date();
}
return (Date) now.clone();
}
/**
* Parses a string of commands relative "now" are returns the resulting Date.
*
* @exception ParseException positions in ParseExceptions are token positions, not character positions.
*/
public Date parseMath(String math) throws ParseException {
Calendar cal = Calendar.getInstance(zone, loc);
cal.setTime(getNow());
/* check for No-Op */
if (0==math.length()) {
return cal.getTime();
}
String[] ops = splitter.split(math);
int pos = 0;
while ( pos < ops.length ) {
if (1 != ops[pos].length()) {
throw new ParseException
("Multi character command found: \"" + ops[pos] + "\"", pos);
}
char command = ops[pos++].charAt(0);
switch (command) {
case '/':
if (ops.length < pos + 1) {
throw new ParseException
("Need a unit after command: \"" + command + "\"", pos);
}
try {
round(cal, ops[pos++]);
} catch (IllegalArgumentException e) {
throw new ParseException
("Unit not recognized: \"" + ops[pos-1] + "\"", pos-1);
}
break;
case '+': /* fall through */
case '-':
if (ops.length < pos + 2) {
throw new ParseException
("Need a value and unit for command: \"" + command + "\"", pos);
}
int val = 0;
try {
val = Integer.valueOf(ops[pos++]);
} catch (NumberFormatException e) {
throw new ParseException
("Not a Number: \"" + ops[pos-1] + "\"", pos-1);
}
if ('-' == command) {
val = 0 - val;
}
try {
String unit = ops[pos++];
add(cal, val, unit);
} catch (IllegalArgumentException e) {
throw new ParseException
("Unit not recognized: \"" + ops[pos-1] + "\"", pos-1);
}
break;
default:
throw new ParseException
("Unrecognized command: \"" + command + "\"", pos-1);
}
}
return cal.getTime();
}
private static Pattern splitter = Pattern.compile("\\b|(?<=\\d)(?=\\D)");
} | 12,372 | 35.498525 | 171 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/InvalidQueryException.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.query.parser.common;
/**
* @author Niall Gallagher
*/
public class InvalidQueryException extends IllegalStateException {
public InvalidQueryException(String s) {
super(s);
}
public InvalidQueryException(String message, Throwable cause) {
super(message, cause);
}
}
| 938 | 29.290323 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/ParseResult.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.query.parser.common;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
/**
* Encapsulates the result of parsing a string-based query: the parsed query itself, and any query options associated
* with the query.
* <p/>
* Query options specify optional non-query parameters which might have been parsed along with the query, such as how
* results should be ordered etc.
*
* @author niall.gallagher
*/
public class ParseResult<O> {
final Query<O> query;
final QueryOptions queryOptions;
public ParseResult(Query<O> query, QueryOptions queryOptions) {
this.query = query;
this.queryOptions = queryOptions;
}
/**
* Returns the parsed query.
* @return The parsed query (never null).
*/
public Query<O> getQuery() {
return query;
}
/**
* Returns the parsed query options, which may include {@link com.googlecode.cqengine.query.option.OrderByOption}
* if ordering was specified in the string query.
* <p/>
* If no query options were specified in the string then the returned query options will not be null, but will be
* empty.
*
* @return The parsed query options.
*/
public QueryOptions getQueryOptions() {
return queryOptions;
}
}
| 1,954 | 31.04918 | 117 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/QueryParser.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.query.parser.common;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.parser.common.valuetypes.*;
import com.googlecode.cqengine.resultset.ResultSet;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
* A service provider interface for parsers which can convert string queries to CQEngine native queries.
* <p/>
* Subclasses can implement this to support string-based queries in various dialects,
* such as SQL or a string representation of a CQEngine native query.
*
* @author Niall Gallagher
*/
public abstract class QueryParser<O> {
protected final Class<O> objectType;
protected final Map<String, Attribute<O, ?>> attributes = new HashMap<String, Attribute<O, ?>>();
protected final Map<Class<?>, ValueParser<?>> valueParsers = new HashMap<Class<?>, ValueParser<?>>();
protected volatile ValueParser<Object> fallbackValueParser = null;
protected static final BaseErrorListener SYNTAX_ERROR_LISTENER = new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e)
throws ParseCancellationException {
throw new InvalidQueryException("Failed to parse query at line " + line + ":" + charPositionInLine + ": " + msg);
}
};
public QueryParser(Class<O> objectType) {
registerValueParser(Boolean.class, new BooleanParser());
registerValueParser(Byte.class, new ByteParser());
registerValueParser(Character.class, new CharacterParser());
registerValueParser(Short.class, new ShortParser());
registerValueParser(Integer.class, new IntegerParser());
registerValueParser(Long.class, new LongParser());
registerValueParser(Float.class, new FloatParser());
registerValueParser(Double.class, new DoubleParser());
registerValueParser(BigInteger.class, new BigIntegerParser());
registerValueParser(BigDecimal.class, new BigDecimalParser());
this.objectType = objectType;
}
public <A> void registerAttribute(Attribute<O, A> attribute) {
attributes.put(attribute.getAttributeName(), attribute);
}
public void registerAttributes(Map<String, ? extends Attribute<O, ?>> attributes) {
registerAttributes(attributes.values());
}
public void registerAttributes(Iterable<? extends Attribute<O, ?>> attributes) {
for (Attribute<O, ?> attribute : attributes) {
registerAttribute(attribute);
}
}
public <A> void registerValueParser(Class<A> valueType, ValueParser<A> valueParser) {
valueParsers.put(valueType, valueParser);
}
public void registerFallbackValueParser(ValueParser<Object> fallbackValueParser) {
this.fallbackValueParser = fallbackValueParser;
}
public Class<O> getObjectType() {
return objectType;
}
public <A> Attribute<O, A> getAttribute(ParseTree attributeNameContext, Class<A> expectedSuperType) {
String attributeName = parseValue(String.class, attributeNameContext.getText());
Attribute<O, ?> attribute = attributes.get(attributeName);
if (attribute == null) {
throw new IllegalStateException("No such attribute has been registered with the parser: " + attributeName);
}
if (!expectedSuperType.isAssignableFrom(attribute.getAttributeType())) {
throw new IllegalStateException("Non-" + expectedSuperType.getSimpleName() + " attribute used in a query which requires a " + expectedSuperType.getSimpleName() + " attribute: " + attribute.getAttributeName());
}
@SuppressWarnings("unchecked")
Attribute<O, A> result = (Attribute<O, A>) attribute;
return result;
}
public <A> A parseValue(Attribute<O, A> attribute, ParseTree parameterContext) {
return parseValue(attribute.getAttributeType(), parameterContext.getText());
}
public <A> A parseValue(Class<A> valueType, ParseTree parameterContext) {
return parseValue(valueType, parameterContext.getText());
}
public <A> A parseValue(Class<A> valueType, String text) {
@SuppressWarnings("unchecked")
ValueParser<A> valueParser = (ValueParser<A>) valueParsers.get(valueType);
if (valueParser != null) {
return valueParser.validatedParse(valueType, text);
} else {
ValueParser<Object> fallbackValueParser = this.fallbackValueParser;
if (fallbackValueParser != null) {
return valueType.cast(fallbackValueParser.parse(valueType, text));
}
else {
throw new IllegalStateException("No value parser has been registered to parse type: " + valueType.getName());
}
}
}
/**
* Parses the given query and its query options, encapsulating both in the object returned.
* @param query The query to parse
* @return An object encapsulating the parsed query and its query options
*/
public abstract ParseResult<O> parse(String query);
/**
* Shortcut for parsing the given query and its query options, and then retrieving objects matching the
* query from the given collection, using the parsed query options.
* @param query The query to parse
* @return The results of querying the collection with the parsed query and its query options
*/
public ResultSet<O> retrieve(IndexedCollection<O> collection, String query) {
ParseResult<O> parseResult = parse(query);
return collection.retrieve(parseResult.getQuery(), parseResult.getQueryOptions());
}
/**
* Shortcut for calling {@code parse(query).getQuery()}.
* @param query The query to parse
* @return The parsed query on its own, without any query options
*/
public Query<O> query(String query) {
return parse(query).getQuery();
}
/**
* Shortcut for calling {@code parse(query).getQueryOptions()}.
* @param query The query to parse
* @return The query options, without the actual query
*/
public QueryOptions queryOptions(String query) {
return parse(query).getQueryOptions();
}
}
| 7,361 | 41.554913 | 221 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/ValueParser.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.query.parser.common;
/**
* @author Niall Gallagher
*/
public abstract class ValueParser<A> {
public A validatedParse(Class<A> valueType, String stringValue) {
try {
return parse(valueType, stringValue);
}
catch (Exception e) {
throw new InvalidQueryException("Failed to parse as type " + valueType.getSimpleName() + ": " + stringValue, e);
}
}
protected abstract A parse(Class<? extends A> valueType, String stringValue);
}
| 1,133 | 32.352941 | 124 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/ParserUtils.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.query.parser.common;
import org.antlr.v4.runtime.ParserRuleContext;
/**
* @author niall.gallagher
*/
public class ParserUtils {
/**
* Examines the parent rule contexts of the given context, and returns the first parent context which is assignable
* from (i.e. is a, or is a subclass of) one of the given context types.
* @param currentContext The starting context whose parent contexts should be examined
* @param parentContextTypes The types of parent context sought
* @return The first parent context which is assignable from one of the given context types,
* or null if there is no such parent in the tree
*/
public static ParserRuleContext getParentContextOfType(ParserRuleContext currentContext, Class<?>... parentContextTypes) {
while (currentContext != null) {
currentContext = currentContext.getParent();
if (currentContext != null) {
for (Class<?> parentContextType : parentContextTypes) {
if (parentContextType.isAssignableFrom(currentContext.getClass())) {
return currentContext;
}
}
}
}
return null;
}
public static void validateObjectTypeParameter(Class<?> expectedType, String actualType) {
if (!expectedType.getSimpleName().equals(actualType)) {
throw new IllegalStateException("Unexpected object type parameter, expected: " + expectedType.getSimpleName() + ", found: " + actualType);
}
}
public static void validateExpectedNumberOfChildQueries(int expected, int actual) {
if (actual != expected) {
throw new IllegalStateException("Unexpected number of child queries, expected: " + expected + ", actual: " + actual);
}
}
public static void validateAllQueriesParsed(int numQueriesEncountered, int numQueriesParsed) {
if (numQueriesEncountered != numQueriesParsed) {
throw new IllegalStateException("A query declared in the antlr grammar, was not parsed by the listener. If a new query is added in the grammar, a corresponding handler must also be added in the listener.");
}
}
}
| 2,849 | 42.181818 | 218 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/valuetypes/LongParser.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.query.parser.common.valuetypes;
import com.googlecode.cqengine.query.parser.common.ValueParser;
/**
* @author Niall Gallagher
*/
public class LongParser extends ValueParser<Long> {
@Override
public Long parse(Class<? extends Long> valueType, String stringValue) {
return Long.valueOf(stringValue);
}
}
| 963 | 31.133333 | 76 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/valuetypes/ByteParser.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.query.parser.common.valuetypes;
import com.googlecode.cqengine.query.parser.common.ValueParser;
/**
* @author Niall Gallagher
*/
public class ByteParser extends ValueParser<Byte> {
@Override
public Byte parse(Class<? extends Byte> valueType, String stringValue) {
return Byte.valueOf(stringValue);
}
}
| 963 | 31.133333 | 76 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/valuetypes/ShortParser.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.query.parser.common.valuetypes;
import com.googlecode.cqengine.query.parser.common.ValueParser;
/**
* @author Niall Gallagher
*/
public class ShortParser extends ValueParser<Short> {
@Override
public Short parse(Class<? extends Short> valueType, String stringValue) {
return Short.valueOf(stringValue);
}
}
| 968 | 31.3 | 78 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/valuetypes/IntegerParser.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.query.parser.common.valuetypes;
import com.googlecode.cqengine.query.parser.common.ValueParser;
/**
* @author Niall Gallagher
*/
public class IntegerParser extends ValueParser<Integer> {
@Override
public Integer parse(Class<? extends Integer> valueType, String stringValue) {
return Integer.valueOf(stringValue);
}
}
| 978 | 31.633333 | 82 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/query/parser/common/valuetypes/BigIntegerParser.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.query.parser.common.valuetypes;
import com.googlecode.cqengine.query.parser.common.ValueParser;
import java.math.BigInteger;
/**
* @author Niall Gallagher
*/
public class BigIntegerParser extends ValueParser<BigInteger> {
@Override
public BigInteger parse(Class<? extends BigInteger> valueType, String stringValue) {
return new BigInteger(stringValue);
}
}
| 1,019 | 30.875 | 88 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.