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/test/java/com/googlecode/cqengine/codegen/AttributeSourceGeneratorTest.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 org.junit.Test;
import java.util.List;
import static com.googlecode.cqengine.codegen.AttributeSourceGenerator.generateAttributesForPastingIntoTargetClass;
import static com.googlecode.cqengine.codegen.AttributeSourceGenerator.generateSeparateAttributesClass;
import static org.junit.Assert.assertEquals;
/**
* @author Niall Gallagher
*/
public class AttributeSourceGeneratorTest {
public static class CarParent {
private int inaccessible;
protected int inheritedCarId;
}
public static class Car extends CarParent {
public String name;
private String description;
List<String> features;
double[] prices;
String[] extras;
public double[] getPrices() { return prices; }
public String[] getExtras(String someParameter) { return extras; }
}
@Test
public void testGenerateAttributesForPastingIntoTargetClass() {
String expected = "" +
"\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.name}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this field cannot be null, replace this SimpleNullableAttribute with a SimpleAttribute\n" +
" public static final Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>(\"NAME\") {\n" +
" public String getValue(Car car, QueryOptions queryOptions) { return car.name; }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.description}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this field cannot be null, replace this SimpleNullableAttribute with a SimpleAttribute\n" +
" public static final Attribute<Car, String> DESCRIPTION = new SimpleNullableAttribute<Car, String>(\"DESCRIPTION\") {\n" +
" public String getValue(Car car, QueryOptions queryOptions) { return car.description; }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.features}.\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 field itself cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, String> FEATURES = new MultiValueNullableAttribute<Car, String>(\"FEATURES\", true) {\n" +
" public Iterable<String> getNullableValues(Car car, QueryOptions queryOptions) { return car.features; }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.prices}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this field cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, Double> PRICES = new MultiValueNullableAttribute<Car, Double>(\"PRICES\", false) {\n" +
" public Iterable<Double> getNullableValues(final Car car, QueryOptions queryOptions) {\n" +
" return new AbstractList<Double>() {\n" +
" public Double get(int i) { return car.prices[i]; }\n" +
" public int size() { return car.prices.length; }\n" +
" };\n" +
" }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.extras}.\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 field itself cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, String> EXTRAS = new MultiValueNullableAttribute<Car, String>(\"EXTRAS\", true) {\n" +
" public Iterable<String> getNullableValues(Car car, QueryOptions queryOptions) { return Arrays.asList(car.extras); }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.inheritedCarId}.\n" +
" */\n" +
" public static final Attribute<Car, Integer> INHERITED_CAR_ID = new SimpleAttribute<Car, Integer>(\"INHERITED_CAR_ID\") {\n" +
" public Integer getValue(Car car, QueryOptions queryOptions) { return car.inheritedCarId; }\n" +
" };";
assertEquals(expected, generateAttributesForPastingIntoTargetClass(Car.class));
}
@Test
public void testGenerateSeparateAttributesClass() {
String expected = "" +
"package com.googlecode.cqengine.codegen;\n" +
"\n" +
"import com.googlecode.cqengine.attribute.*;\n" +
"import com.googlecode.cqengine.query.option.QueryOptions;\n" +
"import java.util.*;\n" +
"import com.googlecode.cqengine.codegen.AttributeSourceGeneratorTest.Car;\n" +
"\n" +
"/**\n" +
" * CQEngine attributes for accessing the members of class {@code com.googlecode.cqengine.codegen.AttributeSourceGeneratorTest.Car}.\n" +
" * <p/>.\n" +
" * Auto-generated by CQEngine's {@code AttributeSourceGenerator}.\n" +
" */\n" +
"public class CQCar {\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.name}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this field cannot be null, replace this SimpleNullableAttribute with a SimpleAttribute\n" +
" public static final Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>(\"NAME\") {\n" +
" public String getValue(Car car, QueryOptions queryOptions) { return car.name; }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.features}.\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 field itself cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, String> FEATURES = new MultiValueNullableAttribute<Car, String>(\"FEATURES\", true) {\n" +
" public Iterable<String> getNullableValues(Car car, QueryOptions queryOptions) { return car.features; }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.prices}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this field cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, Double> PRICES = new MultiValueNullableAttribute<Car, Double>(\"PRICES\", false) {\n" +
" public Iterable<Double> getNullableValues(final Car car, QueryOptions queryOptions) {\n" +
" return new AbstractList<Double>() {\n" +
" public Double get(int i) { return car.prices[i]; }\n" +
" public int size() { return car.prices.length; }\n" +
" };\n" +
" }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.extras}.\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 field itself cannot be null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, String> EXTRAS = new MultiValueNullableAttribute<Car, String>(\"EXTRAS\", true) {\n" +
" public Iterable<String> getNullableValues(Car car, QueryOptions queryOptions) { return Arrays.asList(car.extras); }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing method {@code Car.getPrices()}.\n" +
" */\n" +
" // Note: For best performance:\n" +
" // - if this method cannot return null, replace this\n" +
" // MultiValueNullableAttribute with a MultiValueAttribute (and change getNullableValues() to getValues())\n" +
" public static final Attribute<Car, Double> GET_PRICES = new MultiValueNullableAttribute<Car, Double>(\"GET_PRICES\", false) {\n" +
" public Iterable<Double> getNullableValues(final Car car, QueryOptions queryOptions) {\n" +
" return new AbstractList<Double>() {\n" +
" public Double get(int i) { return car.getPrices()[i]; }\n" +
" public int size() { return car.getPrices().length; }\n" +
" };\n" +
" }\n" +
" };\n" +
"\n" +
" /**\n" +
" * CQEngine attribute for accessing field {@code Car.inheritedCarId}.\n" +
" */\n" +
" public static final Attribute<Car, Integer> INHERITED_CAR_ID = new SimpleAttribute<Car, Integer>(\"INHERITED_CAR_ID\") {\n" +
" public Integer getValue(Car car, QueryOptions queryOptions) { return car.inheritedCarId; }\n" +
" };\n" +
"}\n";
assertEquals(expected, generateSeparateAttributesClass(Car.class, Car.class.getPackage()));
}
}
| 12,393 | 60.356436 | 153 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/codegen/support/GeneratedAttributeSupportTest.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 org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
@SuppressWarnings("deprecation")
public class GeneratedAttributeSupportTest {
@Test
public void testAsList_PrimitiveArray() throws Exception {
int[] input = new int[] {1, 2, 3, 4, 5};
List<Integer> list = GeneratedAttributeSupport.valueOf(input);
Assert.assertEquals(5, list.size());
for (int i = 0; i < 5; i++) {
Assert.assertEquals(Integer.valueOf(input[i]), list.get(i));
}
list.set(2, 7);
Assert.assertEquals(Integer.valueOf(7), list.get(2));
Assert.assertEquals(7, input[2]);
}
@Test
public void testAsList_ObjectArray() throws Exception {
Integer[] input = new Integer[] {1, 2, 3, 4, 5};
List<Integer> list = GeneratedAttributeSupport.valueOf(input);
Assert.assertEquals(5, list.size());
for (int i = 0; i < 5; i++) {
Assert.assertEquals(input[i], list.get(i));
}
list.set(2, 7);
Assert.assertEquals(Integer.valueOf(7), list.get(2));
Assert.assertEquals(Integer.valueOf(7), input[2]);
}
@Test
public void testValueOfPrimitiveMethods() {
assertEquals(Byte.valueOf((byte)5), GeneratedAttributeSupport.valueOf((byte)5));
assertEquals(Short.valueOf((short)5), GeneratedAttributeSupport.valueOf((short)5));
assertEquals(Integer.valueOf(5), GeneratedAttributeSupport.valueOf(5));
assertEquals(Long.valueOf(5L), GeneratedAttributeSupport.valueOf(5L));
assertEquals(Float.valueOf(5.0F), GeneratedAttributeSupport.valueOf(5.0F));
assertEquals(Double.valueOf(5.0), GeneratedAttributeSupport.valueOf(5.0));
assertEquals(Boolean.TRUE, GeneratedAttributeSupport.valueOf(true));
assertEquals(Character.valueOf('c'), GeneratedAttributeSupport.valueOf('c'));
}
@Test
public void testValueOfPrimitiveArrayMethods() {
assertEquals(asList((byte)5, (byte)6), GeneratedAttributeSupport.valueOf(new byte[]{(byte)5, (byte)6}));
assertEquals(asList((short) 5, (short) 6), GeneratedAttributeSupport.valueOf(new short[]{(short)5, (short)6}));
assertEquals(asList(5, 6), GeneratedAttributeSupport.valueOf(new int[]{5, 6}));
assertEquals(asList(5L, 6L), GeneratedAttributeSupport.valueOf(new long[]{5L, 6L}));
assertEquals(asList(5.0F, 6.0F), GeneratedAttributeSupport.valueOf(new float[]{5.0F, 6.0F}));
assertEquals(asList(5.0, 6.0), GeneratedAttributeSupport.valueOf(new double[]{5.0, 6.0}));
assertEquals(asList(true, false), GeneratedAttributeSupport.valueOf(new boolean[]{true, false}));
assertEquals(asList('c', 'd'), GeneratedAttributeSupport.valueOf(new char[]{'c', 'd'}));
}
@Test
public void testValueOfObjectArray() {
assertEquals(asList("a", "b"), GeneratedAttributeSupport.valueOf(new String[]{"a", "b"}));
}
@Test
public void testValueOfList() {
ArrayList<String> input = new ArrayList<String>(asList("a", "b"));
assertSame(input, GeneratedAttributeSupport.valueOf(input));
}
@Test
public void testValueOfObject() {
Object input = new Object();
assertSame(input, GeneratedAttributeSupport.valueOf(input));
}
} | 4,044 | 39.858586 | 119 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/IntegerQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
/**
* @author Niall Gallagher
*/
public class IntegerQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<Integer> quantizer = IntegerQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0", quantizer.getQuantizedValue(0).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(4).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(5).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(9).toString());
Assert.assertEquals("10", quantizer.getQuantizedValue(11).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(-0).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(-4).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(-5).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(-9).toString());
Assert.assertEquals("-10", quantizer.getQuantizedValue(-11).toString());
}
@Test(expected = IllegalArgumentException.class)
public void testWithCompressionFactor_1() throws Exception {
IntegerQuantizer.withCompressionFactor(1);
}
}
| 2,008 | 41.744681 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/DoubleQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
/**
* @author Niall Gallagher
*/
public class DoubleQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<Double> quantizer = DoubleQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0.0", quantizer.getQuantizedValue(0.0).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(4.2).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(5.0).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(9.9).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-0.0).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-4.2).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-5.0).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-9.9).toString());
}
@Test
public void testWithCompressionFactor_1() throws Exception {
Quantizer<Double> quantizer = DoubleQuantizer.withCompressionFactor(1);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0.0", quantizer.getQuantizedValue(0.0).toString());
Assert.assertEquals("4.0", quantizer.getQuantizedValue(4.2).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(5.0).toString());
Assert.assertEquals("9.0", quantizer.getQuantizedValue(9.9).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-0.0).toString());
Assert.assertEquals("-4.0", quantizer.getQuantizedValue(-4.2).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-5.0).toString());
Assert.assertEquals("-9.0", quantizer.getQuantizedValue(-9.9).toString());
}
}
| 2,634 | 47.796296 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/BigDecimalQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
/**
* @author Niall Gallagher
*/
public class BigDecimalQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<BigDecimal> quantizer = BigDecimalQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(0.0)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(4.2)).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(BigDecimal.valueOf(5.0)).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(BigDecimal.valueOf(9.9)).toString());
Assert.assertEquals("10", quantizer.getQuantizedValue(BigDecimal.valueOf(11.3)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(-0.0)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(-4.2)).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(BigDecimal.valueOf(-5.0)).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(BigDecimal.valueOf(-9.9)).toString());
Assert.assertEquals("-10", quantizer.getQuantizedValue(BigDecimal.valueOf(-11.3)).toString());
}
@Test
public void testWithCompressionFactor_1() throws Exception {
Quantizer<BigDecimal> quantizer = BigDecimalQuantizer.withCompressionFactor(1);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(0.0)).toString());
Assert.assertEquals("4", quantizer.getQuantizedValue(BigDecimal.valueOf(4.2)).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(BigDecimal.valueOf(5.0)).toString());
Assert.assertEquals("9", quantizer.getQuantizedValue(BigDecimal.valueOf(9.9)).toString());
Assert.assertEquals("11", quantizer.getQuantizedValue(BigDecimal.valueOf(11.3)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigDecimal.valueOf(-0.0)).toString());
Assert.assertEquals("-4", quantizer.getQuantizedValue(BigDecimal.valueOf(-4.2)).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(BigDecimal.valueOf(-5.0)).toString());
Assert.assertEquals("-9", quantizer.getQuantizedValue(BigDecimal.valueOf(-9.9)).toString());
Assert.assertEquals("-11", quantizer.getQuantizedValue(BigDecimal.valueOf(-11.3)).toString());
}
}
| 3,380 | 55.35 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/BigIntegerQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
/**
* @author Niall Gallagher
*/
public class BigIntegerQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<BigInteger> quantizer = BigIntegerQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0", quantizer.getQuantizedValue(BigInteger.valueOf(0)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigInteger.valueOf(4)).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(BigInteger.valueOf(5)).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(BigInteger.valueOf(9)).toString());
Assert.assertEquals("10", quantizer.getQuantizedValue(BigInteger.valueOf(11)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigInteger.valueOf(-0)).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(BigInteger.valueOf(-4)).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(BigInteger.valueOf(-5)).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(BigInteger.valueOf(-9)).toString());
Assert.assertEquals("-10", quantizer.getQuantizedValue(BigInteger.valueOf(-11)).toString());
}
@Test(expected = IllegalArgumentException.class)
public void testWithCompressionFactor_1() throws Exception {
BigIntegerQuantizer.withCompressionFactor(1);
}
}
| 2,252 | 43.176471 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/LongQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
/**
* @author Niall Gallagher
*/
public class LongQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<Long> quantizer = LongQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0", quantizer.getQuantizedValue(0L).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(4L).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(5L).toString());
Assert.assertEquals("5", quantizer.getQuantizedValue(9L).toString());
Assert.assertEquals("10", quantizer.getQuantizedValue(11L).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(-0L).toString());
Assert.assertEquals("0", quantizer.getQuantizedValue(-4L).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(-5L).toString());
Assert.assertEquals("-5", quantizer.getQuantizedValue(-9L).toString());
Assert.assertEquals("-10", quantizer.getQuantizedValue(-11L).toString());
}
@Test(expected = IllegalArgumentException.class)
public void testWithCompressionFactor_1() throws Exception {
LongQuantizer.withCompressionFactor(1);
}
}
| 2,010 | 41.787234 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/quantizer/FloatQuantizerTest.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 org.junit.Assert;
import org.junit.Test;
/**
* @author Niall Gallagher
*/
public class FloatQuantizerTest {
@Test
public void testWithCompressionFactor_5() throws Exception {
Quantizer<Float> quantizer = FloatQuantizer.withCompressionFactor(5);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0.0", quantizer.getQuantizedValue(0.0F).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(4.2F).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(5.0F).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(9.9F).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-0.0F).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-4.2F).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-5.0F).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-9.9F).toString());
}
@Test
public void testWithCompressionFactor_1() throws Exception {
Quantizer<Float> quantizer = FloatQuantizer.withCompressionFactor(1);
// Note: comparing using toString, as double comparison with epsilon would not distinguish 0.0 from -0.0...
Assert.assertEquals("0.0", quantizer.getQuantizedValue(0.0F).toString());
Assert.assertEquals("4.0", quantizer.getQuantizedValue(4.2F).toString());
Assert.assertEquals("5.0", quantizer.getQuantizedValue(5.0F).toString());
Assert.assertEquals("9.0", quantizer.getQuantizedValue(9.9F).toString());
Assert.assertEquals("0.0", quantizer.getQuantizedValue(-0.0F).toString());
Assert.assertEquals("-4.0", quantizer.getQuantizedValue(-4.2F).toString());
Assert.assertEquals("-5.0", quantizer.getQuantizedValue(-5.0F).toString());
Assert.assertEquals("-9.0", quantizer.getQuantizedValue(-9.9F).toString());
}
}
| 2,649 | 48.074074 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/engine/CollectionQueryEngineTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
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.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.ConcurrentOnHeapObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.persistence.wrapping.WrappingPersistence;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import com.googlecode.cqengine.testutil.IterationCountingSet;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.resultset.iterator.IteratorUtil.countElements;
public class CollectionQueryEngineTest {
@Test(expected = IllegalStateException.class)
public void testAddIndex_ArgumentValidation1() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(null, noQueryOptions());
}
@Test(expected = IllegalStateException.class)
public void testUnexpectedQueryTye() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.retrieveRecursive(new Query<Car>() {
@Override
public boolean matches(Car object, QueryOptions queryOptions) {
return false;
}
}, noQueryOptions());
}
@Test
public void testGetClassName() throws Exception {
Assert.assertEquals(CollectionQueryEngineTest.class.getName(), CollectionQueryEngine.getClassNameNullSafe(this));
Assert.assertNull(CollectionQueryEngine.getClassNameNullSafe(null));
}
@Test(expected = IllegalStateException.class)
public void testAddDuplicateStandingQueryIndex() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(StandingQueryIndex.onQuery(QueryFactory.has(Car.CAR_ID)), noQueryOptions());
queryEngine.addIndex(StandingQueryIndex.onQuery(QueryFactory.has(Car.CAR_ID)), noQueryOptions());
}
@Test(expected = IllegalStateException.class)
public void testAddDuplicateCompoundIndex() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.MODEL), noQueryOptions());
queryEngine.addIndex(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.MODEL), noQueryOptions());
}
@Test
public void testIsMutable() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
Assert.assertTrue(queryEngine.isMutable());
queryEngine.addIndex(createImmutableIndex(), noQueryOptions());
Assert.assertFalse(queryEngine.isMutable());
}
@Test(expected = IllegalStateException.class)
public void testEnsureMutable() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(createImmutableIndex(), noQueryOptions());
queryEngine.addAll(ObjectSet.fromCollection(Collections.singleton(CarFactory.createCar(1))), noQueryOptions());
}
@Test(expected = IllegalStateException.class)
public void testAddDuplicateIndex() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(HashIndex.onAttribute(Car.MANUFACTURER), noQueryOptions());
queryEngine.addIndex(HashIndex.onAttribute(Car.MANUFACTURER), noQueryOptions());
}
@Test
public void testAddNonDuplicateIndex() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.addIndex(HashIndex.onAttribute(Car.MANUFACTURER), noQueryOptions());
queryEngine.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER), noQueryOptions());
}
@Test
@SuppressWarnings({"MismatchedQueryAndUpdateOfCollection", "StatementWithEmptyBody"})
public void testOrQueryCollectionScan() {
IterationCountingSet<Car> iterationCountingSet = new IterationCountingSet<Car>(CarFactory.createCollectionOfCars(10));
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(WrappingPersistence.aroundCollection(iterationCountingSet));
Query<Car> query = or(equal(Car.COLOR, Car.Color.BLUE), equal(Car.MANUFACTURER, "Honda"));
ResultSet<Car> resultSet = collection.retrieve(query);
for (Car car : resultSet) {
// No op
}
// The two-branch or() query should have been evaluated by scanning the collection only once...
Assert.assertEquals(iterationCountingSet.size(), iterationCountingSet.getItemsIteratedCount());
}
@Test
public void testFallbackIndexToStream() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addAll(CarFactory.createCollectionOfCars(10));
Query<Car> query = equal(Car.MANUFACTURER, "0xabc");
ResultSet<Car> resultSet = collection.retrieve(query);
List<Car> carsList = resultSet.stream().collect(Collectors.toList());
Iterator<Integer> carIds = resultSet.stream().map(Car::getCarId).iterator();
Assert.assertEquals(0, carsList.size());
Assert.assertFalse(carIds.hasNext());
}
@Test
public void testRemoveIndex() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
HashIndex<String, Car> index1 = HashIndex.onAttribute(Car.MANUFACTURER);
queryEngine.addIndex(index1, noQueryOptions());
UniqueIndex<Integer, Car> index2 = UniqueIndex.onAttribute(Car.CAR_ID);
queryEngine.addIndex(index2, noQueryOptions());
StandingQueryIndex<Car> index3 = StandingQueryIndex.onQuery(equal(Car.MODEL, "Focus"));
queryEngine.addIndex(index3, noQueryOptions());
CompoundIndex<Car> index4 = CompoundIndex.onAttributes(Car.MANUFACTURER, Car.MODEL);
queryEngine.addIndex(index4, noQueryOptions());
HashIndex<Boolean, Car> index5 = HashIndex.onAttribute(forStandingQuery(equal(Car.MANUFACTURER, "Ford")));
queryEngine.addIndex(index5, noQueryOptions());
Assert.assertEquals(5, countElements(queryEngine.getIndexes()));
queryEngine.removeIndex(index1, noQueryOptions());
Assert.assertEquals(4, countElements(queryEngine.getIndexes()));
queryEngine.removeIndex(index2, noQueryOptions());
Assert.assertEquals(3, countElements(queryEngine.getIndexes()));
queryEngine.removeIndex(index3, noQueryOptions());
Assert.assertEquals(2, countElements(queryEngine.getIndexes()));
queryEngine.removeIndex(index4, noQueryOptions());
Assert.assertEquals(1, countElements(queryEngine.getIndexes()));
queryEngine.removeIndex(index5, noQueryOptions());
Assert.assertEquals(0, countElements(queryEngine.getIndexes()));
}
@Test(expected = IllegalStateException.class)
public void testRemoveIndex_ArgumentValidation1() {
CollectionQueryEngine<Car> queryEngine = new CollectionQueryEngine<Car>();
queryEngine.init(emptyObjectStore(), queryOptionsWithOnHeapPersistence());
queryEngine.removeIndex(null, noQueryOptions());
}
static QueryOptions queryOptionsWithOnHeapPersistence() {
QueryOptions queryOptions = new QueryOptions();
queryOptions.put(Persistence.class, OnHeapPersistence.withoutPrimaryKey());
return queryOptions;
}
static ObjectStore<Car> emptyObjectStore() {
return new ConcurrentOnHeapObjectStore<Car>();
}
static HashIndex<Integer, Car> createImmutableIndex() {
HashIndex.DefaultIndexMapFactory<Integer, Car> defaultIndexMapFactory = new HashIndex.DefaultIndexMapFactory<Integer, Car>();
HashIndex.DefaultValueSetFactory<Car> defaultValueSetFactory = new HashIndex.DefaultValueSetFactory<Car>();
return new HashIndex<Integer, Car>(defaultIndexMapFactory, defaultValueSetFactory, Car.CAR_ID ) {
@Override
public boolean isMutable() {
return false;
}
};
}
} | 10,354 | 43.82684 | 141 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/IndexingBenchmarkRunner.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.indexingbenchmark;
import com.googlecode.cqengine.indexingbenchmark.task.*;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class IndexingBenchmarkRunner {
// TODO: Use Google Caliper?
static final int COLLECTION_SIZE = 100000;
static final int WARMUP_REPETITIONS = 50;
static final int MEASUREMENT_REPETITIONS = 50;
static final List<? extends IndexingTask> benchmarkTasks = Arrays.asList(
new HashIndex_CarId(),
new UniqueIndex_CarId(),
new Quantized_HashIndex_CarId(),
new HashIndex_Manufacturer(),
new HashIndex_Model(),
new CompoundIndex_ManufacturerColorDoors(),
new NavigableIndex_Price(),
new RadixTreeIndex_Model(),
new SuffixTreeIndex_Model()
);
public static void main(String[] args) {
Collection<Car> collection = CarFactory.createCollectionOfCars(COLLECTION_SIZE);
printResultsHeader(System.out);
for (IndexingTask task : benchmarkTasks) {
// Warmup...
dummyTimingsHolder = runBenchmarkTask(task, WARMUP_REPETITIONS, collection);
// Run GC...
System.gc();
// Run the benchmark task...
IndexingTaskTimings results = runBenchmarkTask(task, MEASUREMENT_REPETITIONS, collection);
// Print timings for this task...
printTimings(results, System.out);
}
}
static IndexingTaskTimings runBenchmarkTask(IndexingTask indexingTask, int repetitions, Collection<Car> collection) {
IndexingTaskTimings timings = new IndexingTaskTimings();
timings.testName = indexingTask.getClass().getSimpleName();
timings.collectionSize = collection.size();
long startTimeNanos, timeTakenNanos = 0;
for (int i = 0; i < repetitions; i++) {
indexingTask.init(collection);
startTimeNanos = System.nanoTime();
indexingTask.buildIndex();
timeTakenNanos += (System.nanoTime() - startTimeNanos);
}
timings.timeTakenPerCollection = (timeTakenNanos / repetitions);
timings.timeTakenPerObject = (timeTakenNanos / repetitions / collection.size());
return timings;
}
static void printResultsHeader(Appendable appendable) {
try {
appendable.append("Index\tNumObjects\tPerCollection\tPerObject\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
static void printTimings(IndexingTaskTimings timings, Appendable appendable) {
try {
appendable.append(timings.testName).append("\t");
appendable.append(timings.collectionSize.toString()).append("\t");
appendable.append(timings.timeTakenPerCollection.toString()).append("\t");
appendable.append(timings.timeTakenPerObject.toString()).append("\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
// Store dummy values in these public variables, so JIT compiler can't eliminate "redundant" benchmark code...
public static IndexingTaskTimings dummyTimingsHolder = new IndexingTaskTimings();
}
| 4,051 | 35.178571 | 121 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/IndexingTaskTimings.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.indexingbenchmark;
/**
* Time taken to perform each test *per-repetition*. I.e. if many iterations were performed, this is total time / reps.
*
* @author Niall Gallagher
*/
public class IndexingTaskTimings {
String testName;
Integer collectionSize;
Long timeTakenPerCollection;
Long timeTakenPerObject;
@Override
public String toString() {
return "IndexingTaskTimings{" +
"testName='" + testName + '\'' +
", collectionSize=" + collectionSize +
", timeTakenPerCollection=" + timeTakenPerCollection +
", timeTakenPerObject=" + timeTakenPerObject +
'}';
}
}
| 1,314 | 31.875 | 119 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/IndexingTask.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.indexingbenchmark;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* Defines the methods which all indexing tasks must implement,
* to measure the overhead of building indexes of various types.
*
* @author Niall Gallagher
*/
public interface IndexingTask {
/**
* Initializes the task with the given collection.
* Typically this will copy the collection into a new instance of CQEngine.
* <p/>
* Note that time taken by this method is NOT factored into the overhead to build the index.
* Applications should store objects in IndexedCollection in the first place.
*
* @param collection The collection of cars to be indexed
*/
void init(Collection<Car> collection);
/**
* Builds an in index on the collection, the type of index determined by the task implementation.
*/
void buildIndex();
}
| 1,531 | 32.304348 | 102 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/HashIndex_CarId.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class HashIndex_CarId implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(HashIndex.onAttribute(Car.CAR_ID));
}
}
| 1,492 | 32.177778 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/SuffixTreeIndex_Model.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class SuffixTreeIndex_Model implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(SuffixTreeIndex.onAttribute(Car.MODEL));
}
}
| 1,511 | 32.6 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/HashIndex_Manufacturer.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class HashIndex_Manufacturer implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
}
}
| 1,505 | 32.466667 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/RadixTreeIndex_Model.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.radix.RadixTreeIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class RadixTreeIndex_Model implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(RadixTreeIndex.onAttribute(Car.MODEL));
}
}
| 1,507 | 32.511111 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/Quantized_HashIndex_CarId.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.quantizer.IntegerQuantizer;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class Quantized_HashIndex_CarId implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(HashIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
}
}
| 1,618 | 34.195652 | 127 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/NavigableIndex_Price.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class NavigableIndex_Price implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(NavigableIndex.onAttribute(Car.PRICE));
}
}
| 1,511 | 32.6 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/CompoundIndex_ManufacturerColorDoors.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class CompoundIndex_ManufacturerColorDoors implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
this.indexedCollection.addIndex(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.COLOR, Car.DOORS));
}
}
| 1,559 | 33.666667 | 108 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/UniqueIndex_CarId.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.unique.UniqueIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class UniqueIndex_CarId implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(UniqueIndex.onAttribute(Car.CAR_ID));
}
}
| 1,500 | 32.355556 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/indexingbenchmark/task/HashIndex_Model.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.indexingbenchmark.task;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.indexingbenchmark.IndexingTask;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* @author Niall Gallagher
*/
public class HashIndex_Model implements IndexingTask {
private IndexedCollection<Car> indexedCollection;
@Override
public void init(Collection<Car> collection) {
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
indexedCollection = indexedCollection1;
}
@Override
public void buildIndex() {
indexedCollection.addIndex(HashIndex.onAttribute(Car.MODEL));
}
}
| 1,491 | 32.155556 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/BenchmarkTaskTimings.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.benchmark;
/**
* Time taken to perform each test *per-repetition*. I.e. if many iterations were performed, this is total time / reps.
*
* @author Niall Gallagher
*/
public class BenchmarkTaskTimings {
String testName;
Long timeTakenIterationNaive;
Long timeTakenIterationOptimized;
Long timeTakenCQEngine;
Long timeTakenCQEngineStatistics;
@Override
public String toString() {
return "BenchmarkTaskTimings{" +
"testName='" + testName + '\'' +
", runQueryCountResults_IterationNaive=" + timeTakenIterationNaive +
", timeTakenIterationOptimized=" + timeTakenIterationOptimized +
", timeTakenCQEngine=" + timeTakenCQEngine +
", timeTakenCQEngineStatistics=" + timeTakenCQEngineStatistics +
'}';
}
}
| 1,475 | 34.142857 | 119 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/BenchmarkRunner.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.benchmark;
import com.googlecode.cqengine.benchmark.tasks.*;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class BenchmarkRunner {
// TODO: Use Google Caliper?
static final int COLLECTION_SIZE = 100000;
static final int WARMUP_REPETITIONS = 10000;
static final int MEASUREMENT_REPETITIONS = 10000;
static final List<? extends BenchmarkTask> benchmarkTasks = Arrays.asList(
new UniqueIndex_CarId(),
new HashIndex_CarId(),
new HashIndex_ManufacturerFord(),
new HashIndex_ModelFocus(),
new NavigableIndex_PriceBetween(),
new Quantized_HashIndex_CarId(),
new Quantized_NavigableIndex_CarId(),
new CompoundIndex_ManufacturerToyotaColorBlueDoorsThree(),
new NoIndexes_ModelFocus(),
new NonOptimalIndexes_ManufacturerToyotaColorBlueDoorsThree(),
new StandingQueryIndex_ManufacturerToyotaColorBlueDoorsNotFive(),
new RadixTreeIndex_ModelStartsWithP(),
new SuffixTreeIndex_ModelContainsG(),
new MaterializedOrder_CardId()
);
public static void main(String[] args) {
Collection<Car> collection = CarFactory.createCollectionOfCars(COLLECTION_SIZE);
printResultsHeader(System.out);
for (BenchmarkTask task : benchmarkTasks) {
task.init(collection);
// Warmup...
dummyTimingsHolder = runBenchmarkTask(task, WARMUP_REPETITIONS);
// Run GC...
System.gc();
// Run the benchmark task...
BenchmarkTaskTimings results = runBenchmarkTask(task, MEASUREMENT_REPETITIONS);
// Print timings for this task...
printTimings(results, System.out);
}
}
static BenchmarkTaskTimings runBenchmarkTask(BenchmarkTask benchmarkTask, int repetitions) {
dummyValueHolder = new ArrayList<Integer>();
BenchmarkTaskTimings timings = new BenchmarkTaskTimings();
timings.testName = benchmarkTask.getClass().getSimpleName();
long startTimeNanos;
int dummy = 0;
startTimeNanos = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
dummy = benchmarkTask.runQueryCountResults_IterationNaive();
}
dummyValueHolder.add(dummy);
timings.timeTakenIterationNaive = ((System.nanoTime() - startTimeNanos) / repetitions);
startTimeNanos = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
dummy = benchmarkTask.runQueryCountResults_IterationOptimized();
}
dummyValueHolder.add(dummy);
timings.timeTakenIterationOptimized = ((System.nanoTime() - startTimeNanos) / repetitions);
startTimeNanos = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
dummy = benchmarkTask.runQueryCountResults_CQEngine();
}
dummyValueHolder.add(dummy);
timings.timeTakenCQEngine = ((System.nanoTime() - startTimeNanos) / repetitions);
startTimeNanos = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
dummy = benchmarkTask.runQueryCountResults_CQEngineStatistics();
}
dummyValueHolder.add(dummy);
timings.timeTakenCQEngineStatistics = ((System.nanoTime() - startTimeNanos) / repetitions);
return timings;
}
static void printResultsHeader(Appendable appendable) {
try {
appendable.append("TestName\tIterationNaive\tIterationOptimized\tCQEngine\tCQEngineStatistics\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
static void printTimings(BenchmarkTaskTimings timings, Appendable appendable) {
try {
appendable.append(timings.testName).append("\t");
appendable.append(timings.timeTakenIterationNaive.toString()).append("\t");
appendable.append(timings.timeTakenIterationOptimized.toString()).append("\t");
appendable.append(timings.timeTakenCQEngine.toString()).append("\t");
appendable.append(timings.timeTakenCQEngineStatistics.toString()).append("\n");
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
// Store dummy values in these public variables, so JIT compiler can't eliminate "redundant" benchmark code...
public static List<Integer> dummyValueHolder = new ArrayList<Integer>();
public static BenchmarkTaskTimings dummyTimingsHolder = new BenchmarkTaskTimings();
}
| 5,432 | 37.807143 | 114 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/BenchmarkUnitTest.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.benchmark;
import com.googlecode.cqengine.benchmark.tasks.*;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Test;
import java.util.Collection;
import static org.junit.Assert.*;
/**
* Tests for the benchmark itself.
*
* @author Niall Gallagher
*/
public class BenchmarkUnitTest {
private final Collection<Car> collection = CarFactory.createCollectionOfCars(1000);
@Test
public void testHashIndex_ModelFocus() {
BenchmarkTask task = new HashIndex_ModelFocus();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testHashIndex_ManufacturerFord() {
BenchmarkTask task = new HashIndex_ManufacturerFord();
task.init(collection);
assertEquals(300, task.runQueryCountResults_IterationNaive());
assertEquals(300, task.runQueryCountResults_IterationOptimized());
assertEquals(300, task.runQueryCountResults_CQEngine());
assertEquals(300, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testNavigableIndex_PriceBetween() {
BenchmarkTask task = new NavigableIndex_PriceBetween();
task.init(collection);
assertEquals(200, task.runQueryCountResults_IterationNaive());
assertEquals(200, task.runQueryCountResults_IterationOptimized());
assertEquals(200, task.runQueryCountResults_CQEngine());
assertEquals(200, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testCompoundIndex_ManufacturerToyotaColorBlueDoorsThree() {
BenchmarkTask task = new CompoundIndex_ManufacturerToyotaColorBlueDoorsThree();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testStandingQueryIndex_ManufacturerToyotaColorBlueDoorsNotFive() {
BenchmarkTask task = new StandingQueryIndex_ManufacturerToyotaColorBlueDoorsNotFive();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testRadixTreeIndex_ModelStartsWithF() {
BenchmarkTask task = new RadixTreeIndex_ModelStartsWithP();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testSuffixTreeIndex_ModelContainsI() {
BenchmarkTask task = new SuffixTreeIndex_ModelContainsG();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testHashIndex_CarId() {
BenchmarkTask task = new HashIndex_CarId();
task.init(collection);
assertEquals(1, task.runQueryCountResults_IterationNaive());
assertEquals(1, task.runQueryCountResults_IterationOptimized());
assertEquals(1, task.runQueryCountResults_CQEngine());
assertEquals(1, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testQuantized_HashIndex_CarId() {
BenchmarkTask task = new Quantized_HashIndex_CarId();
task.init(collection);
assertEquals(1, task.runQueryCountResults_IterationNaive());
assertEquals(1, task.runQueryCountResults_IterationOptimized());
assertEquals(1, task.runQueryCountResults_CQEngine());
assertEquals(1, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testQuantized_NavigableIndex_CarId() {
BenchmarkTask task = new Quantized_NavigableIndex_CarId();
task.init(collection);
assertEquals(3, task.runQueryCountResults_IterationNaive());
assertEquals(3, task.runQueryCountResults_IterationOptimized());
assertEquals(3, task.runQueryCountResults_CQEngine());
assertEquals(3, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testNonOptimalIndexes() {
BenchmarkTask task = new NonOptimalIndexes_ManufacturerToyotaColorBlueDoorsThree();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
@Test
public void testMaterializedOrder_CardId() {
BenchmarkTask task = new MaterializedOrder_CardId();
task.init(collection);
assertEquals(100, task.runQueryCountResults_IterationNaive());
assertEquals(100, task.runQueryCountResults_IterationOptimized());
assertEquals(100, task.runQueryCountResults_CQEngine());
assertEquals(100, task.runQueryCountResults_CQEngineStatistics());
}
}
| 6,571 | 38.119048 | 94 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/BenchmarkTask.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.benchmark;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
/**
* Defines the methods which all benchmark tasks must implement, to compare the performance of conventional iteration
* with CQEngine. Subclasses will implement particular queries, so that overall these results can be compared
* across various types of query.
*
* @author Niall Gallagher
*/
public interface BenchmarkTask {
/**
* Initializes the task to process the given collection of cars.
*
* @param collection The collection of cars to use for the benchmark
*/
void init(Collection<Car> collection);
/**
* Iterates the collection and assembles a list of cars matching the query.
* Then "processes" these results i.e. simply iterates them maintaining a count of the number of cars processed.
*
* @return The number of cars matching the query
*/
int runQueryCountResults_IterationNaive();
/**
* Iterates the collection and counts cars matching the query in a single pass.
*
* @return The number of cars matching the query
*/
int runQueryCountResults_IterationOptimized();
/**
* Gets a lazy ResultSet from CQEngine for cars matching the query, which CQEngine implements to use indexes
* during iteration.
* Then "processes" these results i.e. simply iterates them maintaining a count of the number of cars processed.
*
* @return The number of cars matching the query
*/
int runQueryCountResults_CQEngine();
/**
* Asks CQEngine to count cars matching the query, which it calculates from statistics stored in indexes.
*
* @return The number of cars matching the query
*/
int runQueryCountResults_CQEngineStatistics();
}
| 2,414 | 33.5 | 117 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/NoIndexes_ModelFocus.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* @author Niall Gallagher
*/
public class NoIndexes_ModelFocus implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.MODEL, "Focus");
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getModel().equals("Focus")) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getModel().equals("Focus")) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,655 | 31 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/RadixTreeIndex_ModelStartsWithP.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.radix.RadixTreeIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.startsWith;
/**
* @author Niall Gallagher
*/
public class RadixTreeIndex_ModelStartsWithP implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = startsWith(Car.MODEL, "P");
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(RadixTreeIndex.onAttribute(Car.MODEL));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getModel().startsWith("P")) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getModel().startsWith("P")) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,811 | 32.082353 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/NonOptimalIndexes_ManufacturerToyotaColorBlueDoorsThree.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.and;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* @author Niall Gallagher
*/
public class NonOptimalIndexes_ManufacturerToyotaColorBlueDoorsThree implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = and(
equal(Car.MANUFACTURER, "Toyota"),
equal(Car.COLOR, Car.Color.BLUE),
equal(Car.DOORS, 3)
);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(HashIndex.onAttribute(Car.DOORS));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() == 3) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() == 3) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 3,134 | 33.833333 | 121 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/Quantized_NavigableIndex_CarId.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.quantizer.IntegerQuantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.between;
/**
* @author Niall Gallagher
*/
public class Quantized_NavigableIndex_CarId implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = between(Car.CAR_ID, 500, 502);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(
NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(5), Car.CAR_ID)
);
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getCarId() >= 500 && car.getCarId() <= 502) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getCarId() >= 500 && car.getCarId() <= 502) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,988 | 32.965909 | 110 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/HashIndex_CarId.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.in;
/**
* @author Niall Gallagher
*/
public class HashIndex_CarId implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.CAR_ID, 500);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(
HashIndex.onAttribute(Car.CAR_ID)
);
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getCarId() == 500) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getCarId() == 500) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,845 | 31.340909 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/SuffixTreeIndex_ModelContainsG.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.contains;
/**
* @author Niall Gallagher
*/
public class SuffixTreeIndex_ModelContainsG implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = contains(Car.MODEL, "g");
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(SuffixTreeIndex.onAttribute(Car.MODEL));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getModel().contains("g")) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getModel().contains("g")) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,805 | 32.011765 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/MaterializedOrder_CardId.java | package com.googlecode.cqengine.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.ascending;
import static com.googlecode.cqengine.query.QueryFactory.orderBy;
import static com.googlecode.cqengine.query.QueryFactory.queryOptions;
public class MaterializedOrder_CardId implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Comparator<Car> carIdComparator = Comparator.comparingInt(Car::getCarId);
private final Query<Car> query = equal(Car.MODEL, "Focus");
private final QueryOptions queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)));
@Override
public void init(final Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>();
indexedCollection.addAll(collection);
this.indexedCollection = indexedCollection;
this.indexedCollection.addIndex(HashIndex.onAttribute(Car.MODEL));
}
/**
* Uses iteration with insertion sort.
*/
@Override
public int runQueryCountResults_IterationNaive() {
final TreeSet<Car> result = new TreeSet<>(carIdComparator);
for (final Car car : collection) {
if (car.getModel().equals("Focus")) {
result.add(car);
}
}
return result.size();
}
/**
* Uses iteration with merge sort.
*/
@Override
public int runQueryCountResults_IterationOptimized() {
final List<Car> result = new ArrayList<>();
for (final Car car : collection) {
if (car.getModel().equals("Focus")) {
result.add(car);
}
}
result.sort(carIdComparator);
return result.size();
}
@Override
public int runQueryCountResults_CQEngine() {
final ResultSet<Car> sortedResult = indexedCollection.retrieve(query, queryOptions);
return BenchmarkTaskUtil.countResultsViaIteration(sortedResult);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
final ResultSet<Car> result = indexedCollection.retrieve(query, queryOptions);
return result.size();
}
}
| 2,888 | 34.231707 | 92 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/NavigableIndex_PriceBetween.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.between;
/**
* @author Niall Gallagher
*/
public class NavigableIndex_PriceBetween implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = between(Car.PRICE, 3000.0, true, 4000.0, false); // price >= 3000.0, price < 4000.0
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(NavigableIndex.onAttribute(Car.PRICE));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getPrice() >= 3000.0 && car.getPrice() < 4000.0) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getPrice() >= 3000.0 && car.getPrice() < 4000.0) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,906 | 33.2 | 120 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/BenchmarkTaskUtil.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.benchmark.tasks;
import com.googlecode.cqengine.testutil.Car;
/**
* @author Niall Gallagher
*/
public class BenchmarkTaskUtil {
static int countResultsViaIteration(Iterable<Car> results) {
int count = 0;
for (Car car : results) {
count++;
}
return count;
}
}
| 952 | 27.878788 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/Quantized_HashIndex_CarId.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.quantizer.IntegerQuantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* @author Niall Gallagher
*/
public class Quantized_HashIndex_CarId implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.CAR_ID, 501);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(
HashIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(5), Car.CAR_ID)
);
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getCarId() == 501) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getCarId() == 501) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,905 | 32.022727 | 105 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/HashIndex_ManufacturerFord.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* @author Niall Gallagher
*/
public class HashIndex_ManufacturerFord implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.MANUFACTURER, "Ford");
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getManufacturer().equals("Ford")) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getManufacturer().equals("Ford")) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,814 | 32.117647 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/StandingQueryIndex_ManufacturerToyotaColorBlueDoorsNotFive.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.and;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.not;
/**
* @author Niall Gallagher
*/
public class StandingQueryIndex_ManufacturerToyotaColorBlueDoorsNotFive implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = and(
equal(Car.MANUFACTURER, "Toyota"),
equal(Car.COLOR, Car.Color.BLUE),
not(equal(Car.DOORS, 5))
);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(StandingQueryIndex.onQuery(query));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() != 5) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() != 5) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 3,223 | 34.428571 | 121 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/CompoundIndex_ManufacturerToyotaColorBlueDoorsThree.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* @author Niall Gallagher
*/
public class CompoundIndex_ManufacturerToyotaColorBlueDoorsThree implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = and(
equal(Car.MANUFACTURER, "Toyota"),
equal(Car.COLOR, Car.Color.BLUE),
equal(Car.DOORS, 3)
);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.COLOR, Car.DOORS));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() == 3) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getManufacturer().equals("Toyota") && car.getColor().equals(Car.Color.BLUE) && car.getDoors() == 3) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 3,106 | 33.910112 | 121 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/HashIndex_ModelFocus.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* @author Niall Gallagher
*/
public class HashIndex_ModelFocus implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.MODEL, "Focus");
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(HashIndex.onAttribute(Car.MODEL));
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getModel().equals("Focus")) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getModel().equals("Focus")) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,779 | 31.705882 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/benchmark/tasks/UniqueIndex_CarId.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.benchmark.tasks;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.benchmark.BenchmarkTask;
import com.googlecode.cqengine.index.unique.UniqueIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* @author Niall Gallagher
*/
public class UniqueIndex_CarId implements BenchmarkTask {
private Collection<Car> collection;
private IndexedCollection<Car> indexedCollection;
private final Query<Car> query = equal(Car.CAR_ID, 500);
@Override
public void init(Collection<Car> collection) {
this.collection = collection;
IndexedCollection<Car> indexedCollection1 = new ConcurrentIndexedCollection<Car>();
indexedCollection1.addAll(collection);
this.indexedCollection = indexedCollection1;
this.indexedCollection.addIndex(
UniqueIndex.onAttribute(Car.CAR_ID)
);
}
@Override
public int runQueryCountResults_IterationNaive() {
List<Car> results = new LinkedList<Car>();
for (Car car : collection) {
if (car.getCarId() == 500) {
results.add(car);
}
}
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_IterationOptimized() {
int count = 0;
for (Car car : collection) {
if (car.getCarId() == 500) {
count++;
}
}
return count;
}
@Override
public int runQueryCountResults_CQEngine() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return BenchmarkTaskUtil.countResultsViaIteration(results);
}
@Override
public int runQueryCountResults_CQEngineStatistics() {
ResultSet<Car> results = indexedCollection.retrieve(query);
return results.size();
}
}
| 2,792 | 31.103448 | 91 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/PersistenceIndexingBenchmark.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.index.sqlite.SQLitePersistence;
import com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import static com.googlecode.cqengine.query.QueryFactory.enableFlags;
/**
* @author niall.gallagher
*/
public class PersistenceIndexingBenchmark {
enum IndexType { ON_HEAP, OFF_HEAP, DISK }
static final IndexType INDEX_TYPE_TO_TEST = IndexType.DISK;
static final Long BYTES_TO_PREALLOCATE = null; //= 42693632L;
static final boolean BULK_IMPORT_FLAG = true;
static final int[] NUM_OBJECTS = {1000, 100000, 1000000};
static final int[] NUM_INDEXES = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
static final int BATCH_SIZE = 50000;
static final int NUM_RUNS = 2;
static class IndexedAttribute extends SimpleAttribute<Car, String> {
public IndexedAttribute(String attributeName) {
super(attributeName);
}
@Override
public String getValue(Car object, QueryOptions queryOptions) {
return object.getModel();
}
}
static final SimpleAttribute<Car, String> CAR_ID_STRING = new SimpleAttribute<Car, String>("carIdString") {
@Override
public String getValue(Car car, QueryOptions queryOptions) {
return String.valueOf(car.getCarId());
}
};
public static void main(String[] args) throws IOException {
for (int runNumber = 1; runNumber <= NUM_RUNS; runNumber++) {
long runStartTime = System.currentTimeMillis();
System.out.println("Run " + runNumber);
System.out.println("Objects\tIndexes\tSizeMB\tCreateMs\tInserts/sec\tDelta");
for (int numObjects : NUM_OBJECTS) {
System.gc();
double previousInsertsPerSecond = Double.NaN;
for (int numIndexes : NUM_INDEXES) {
IndexedCollection<Car> collection;
SQLitePersistence<Car, String> persistence;
switch (INDEX_TYPE_TO_TEST) {
case ON_HEAP: {
collection = new ConcurrentIndexedCollection<Car>();
addNavigableIndexes(collection, numIndexes);
persistence = null;
break;
}
case OFF_HEAP: {
OffHeapPersistence<Car, String> offHeapPersistence = OffHeapPersistence.onPrimaryKey(CAR_ID_STRING);
collection = new ConcurrentIndexedCollection<Car>(offHeapPersistence);
addOffHeapIndexes(offHeapPersistence, collection, numIndexes);
persistence = offHeapPersistence;
break;
}
case DISK: {
// File tempFile = File.createTempFile("cqengine_", ".db", new File("/Volumes/SATA_500GB"));
// DiskPersistence<Car, String> persistence = DiskPersistence.onPrimaryKeyInFile(new CarIdStringAttribute(), tempFile);
DiskPersistence<Car, String> diskPersistence = DiskPersistence.onPrimaryKey(CAR_ID_STRING);
collection = new ConcurrentIndexedCollection<Car>(diskPersistence);
addDiskIndexes(diskPersistence, collection, numIndexes);
persistence = diskPersistence;
break;
}
default: throw new IllegalStateException(String.valueOf(INDEX_TYPE_TO_TEST));
}
if (persistence != null && BYTES_TO_PREALLOCATE != null) {
persistence.expand(BYTES_TO_PREALLOCATE);
}
long start = System.nanoTime();
populateCollection(collection, numObjects, BATCH_SIZE);
double timeTakenMs = (System.nanoTime() - start) / 1000000.0;
System.gc();
Runtime runtime = Runtime.getRuntime();
final double megaBytesUsed;
if (persistence == null) {
double heapSizeInMegaBytes = megaBytes(runtime.totalMemory());
megaBytesUsed = heapSizeInMegaBytes - megaBytes(runtime.freeMemory());
}
else {
megaBytesUsed = megaBytes(persistence.getBytesUsed());
}
double insertsPerSecond = (1000 * numObjects) / timeTakenMs;
double costOfAdditionalIndex = (insertsPerSecond - previousInsertsPerSecond) / previousInsertsPerSecond;
previousInsertsPerSecond = insertsPerSecond;
System.out.println(numObjects + "\t" + numIndexes + "\t" + megaBytesUsed + "\t" + timeTakenMs + "\t" + insertsPerSecond + "\t" + costOfAdditionalIndex);
}
}
System.out.println("Run finished in: " + ((System.currentTimeMillis() - runStartTime) / 1000) + " secs");
System.out.println();
}
}
static void addOffHeapIndexes(OffHeapPersistence<Car, String> persistence, IndexedCollection<Car> collection, int numIndexesToAdd) {
for (int i = 0; i < numIndexesToAdd; i++) {
collection.addIndex(OffHeapIndex.onAttribute(new IndexedAttribute("attribute_" + (i + 1))));
}
}
static void addDiskIndexes(DiskPersistence<Car, String> persistence, IndexedCollection<Car> collection, int numIndexesToAdd) {
for (int i = 0; i < numIndexesToAdd; i++) {
collection.addIndex(DiskIndex.onAttribute(new IndexedAttribute("attribute_" + (i + 1))));
}
}
static void addNavigableIndexes(IndexedCollection<Car> collection, int numIndexesToAdd) {
for (int i = 0; i < numIndexesToAdd; i++) {
collection.addIndex(NavigableIndex.onAttribute(new IndexedAttribute("attribute_" + (i + 1))));
}
}
static void populateCollection(IndexedCollection<Car> collection, int total, int batchSize) {
int count = 0;
long start = System.currentTimeMillis();
Queue<Car> batch = new ArrayBlockingQueue<Car>(batchSize);
for (Car next : CarFactory.createIterableOfCars(total)) {
if (!batch.offer(next)) {
if (BULK_IMPORT_FLAG) {
collection.update(Collections.<Car>emptySet(), batch, QueryFactory.queryOptions(enableFlags(SQLiteIndexFlags.BULK_IMPORT)));
}
else {
collection.update(Collections.<Car>emptySet(), batch);
}
count += batchSize;
batch.clear();
batch.add(next);
// printProgress(start, count, total);
}
}
count += batch.size();
collection.addAll(batch);
// printProgress(start, count, total);
// System.out.println();
}
static void printProgress(long startTime, int objectsProcessed, int totalObjects) {
double elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000.0;
double objectsPerSecond = (((double) objectsProcessed) / elapsedSeconds);
double percentComplete = 100 * (((double) objectsProcessed) / totalObjects);
double etaSeconds = ((totalObjects - objectsProcessed) / objectsPerSecond);
System.out.printf("\rObjects processed: %8d, rate: %8.2f objects/sec, progress: %5.2f%%, elapsed: %4.2f secs, remaining: %4.2f secs", objectsProcessed, objectsPerSecond, percentComplete, elapsedSeconds, etaSeconds);
}
static void printHeapUsage() {
Runtime runtime = Runtime.getRuntime();
double heapSizeInMegaBytes = megaBytes(runtime.totalMemory());
double heapUsedInMegaBytes = heapSizeInMegaBytes - megaBytes(runtime.freeMemory());
System.out.printf("Heap size: %6.2f MB, heap used: %6.2f MB%n", heapSizeInMegaBytes, heapUsedInMegaBytes);
}
static double megaBytes(long bytes) {
return ((double)bytes) / 1024 / 1024;
}
}
| 9,613 | 47.80203 | 223 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/composite/CompositePersistenceTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.index.support.CloseableRequestResources;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.ConcurrentOnHeapObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author niall.gallagher
*/
public class CompositePersistenceTest {
/**
* Tests a configuration where the collection is stored off-heap, one index is on-disk, and one index is on-heap.
*/
@Test
public void testCompositePersistence_EndToEnd() {
OffHeapPersistence<Car, Integer> offHeapPersistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
DiskPersistence<Car, Integer> diskPersistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(CompositePersistence.of(
offHeapPersistence,
diskPersistence,
singletonList(OnHeapPersistence.onPrimaryKey(Car.CAR_ID))
));
collection.addIndex(DiskIndex.onAttribute(Car.MANUFACTURER));
collection.addIndex(OffHeapIndex.onAttribute(Car.MODEL));
collection.addIndex(NavigableIndex.onAttribute(Car.PRICE));
collection.addAll(CarFactory.createCollectionOfCars(1000));
ResultSet<Car> results = null;
try {
results = collection.retrieve(
and(
or(
equal(Car.MANUFACTURER, "Ford"),
equal(Car.MODEL, "Avensis")
),
lessThan(Car.PRICE, 6000.0)
)
);
Assert.assertEquals(300, results.size());
Assert.assertTrue(offHeapPersistence.getBytesUsed() > 4096); // example: 163840
Assert.assertTrue(diskPersistence.getBytesUsed() > 4096); // example: 30720
}
finally {
CloseableRequestResources.closeQuietly(results);
collection.clear();
offHeapPersistence.close();
diskPersistence.getFile().delete();
}
}
@Test
public void testGetPrimaryKeyAttribute() throws Exception {
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
CompositePersistence<Car, Integer> compositePersistence = new CompositePersistence<Car, Integer>(persistence1, persistence2, noAdditionalPersistences());
assertEquals(Car.CAR_ID, compositePersistence.getPrimaryKeyAttribute());
}
@Test
public void testSupportsIndex() throws Exception {
Index<Car> index1 = mockIndex("index1");
Index<Car> index2 = mockIndex("index2");
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence1.supportsIndex(index1)).thenReturn(true);
CompositePersistence<Car, Integer> compositePersistence = new CompositePersistence<Car, Integer>(persistence1, persistence2, noAdditionalPersistences());
assertTrue(compositePersistence.supportsIndex(index1));
assertFalse(compositePersistence.supportsIndex(index2));
}
@Test
public void testCreateObjectStore() throws Exception {
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
Persistence<Car, Integer> persistence3 = mockPersistence("persistence3");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
ObjectStore<Car> objectStore = new ConcurrentOnHeapObjectStore<Car>();
when(persistence1.createObjectStore()).thenReturn(objectStore);
CompositePersistence<Car, Integer> compositePersistence = new CompositePersistence<Car, Integer>(persistence1, persistence2, singletonList(persistence3));
ObjectStore<Car> result = compositePersistence.createObjectStore();
assertEquals(objectStore, result);
}
@Test(expected = IllegalStateException.class)
public void testGetPersistenceForIndex_NoPersistence() throws Exception {
Index<Car> index = mockIndex("index1");
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
Persistence<Car, Integer> persistence3 = mockPersistence("persistence3");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
CompositePersistence<Car, Integer> compositePersistence = CompositePersistence.of(persistence1, persistence2, singletonList(persistence3));
compositePersistence.getPersistenceForIndex(index);
}
@Test
public void testGetPersistenceForIndex_PrimaryPersistence() throws Exception {
Index<Car> index = mockIndex("index1");
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
Persistence<Car, Integer> persistence3 = mockPersistence("persistence3");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence1.supportsIndex(index)).thenReturn(true);
CompositePersistence<Car, Integer> compositePersistence = CompositePersistence.of(persistence1, persistence2, singletonList(persistence3));
Persistence<Car, Integer> result = compositePersistence.getPersistenceForIndex(index);
assertEquals(persistence1, result);
}
@Test
public void testGetPersistenceForIndex_SecondaryPersistence() throws Exception {
Index<Car> index = mockIndex("index1");
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
Persistence<Car, Integer> persistence3 = mockPersistence("persistence3");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.supportsIndex(index)).thenReturn(true);
CompositePersistence<Car, Integer> compositePersistence = CompositePersistence.of(persistence1, persistence2, singletonList(persistence3));
Persistence<Car, Integer> result = compositePersistence.getPersistenceForIndex(index);
assertEquals(persistence2, result);
}
@Test
public void testGetPersistenceForIndex_AdditionalPersistence() throws Exception {
Index<Car> index = mockIndex("index1");
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
Persistence<Car, Integer> persistence3 = mockPersistence("persistence3");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence3.supportsIndex(index)).thenReturn(true);
CompositePersistence<Car, Integer> compositePersistence = CompositePersistence.of(persistence1, persistence2, singletonList(persistence3));
Persistence<Car, Integer> result = compositePersistence.getPersistenceForIndex(index);
assertEquals(persistence3, result);
}
@Test
public void testValidateBackingPersistences_Success() throws Exception {
@SuppressWarnings("unchecked")
Persistence<Car, Integer> persistence1 = mock(Persistence.class);
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
CompositePersistence.validatePersistenceArguments(persistence1, persistence1, singletonList(persistence1));
}
@Test(expected = IllegalArgumentException.class)
public void testValidateBackingPersistences_NoPrimaryKey() throws Exception {
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
CompositePersistence.validatePersistenceArguments(persistence1, persistence2, noAdditionalPersistences());
}
@Test(expected = IllegalArgumentException.class)
public void testValidateBackingPersistences_DifferentPrimaryKeys1() throws Exception {
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.DOORS);
CompositePersistence.validatePersistenceArguments(persistence1, persistence2, noAdditionalPersistences());
}
@Test(expected = IllegalArgumentException.class)
public void testValidateBackingPersistences_DifferentPrimaryKeys2() throws Exception {
Persistence<Car, Integer> persistence1 = mockPersistence("persistence1");
Persistence<Car, Integer> persistence2 = mockPersistence("persistence2");
when(persistence1.getPrimaryKeyAttribute()).thenReturn(Car.CAR_ID);
when(persistence2.getPrimaryKeyAttribute()).thenReturn(Car.DOORS);
CompositePersistence.validatePersistenceArguments(persistence1, persistence1, singletonList(persistence2));
}
@SuppressWarnings("unchecked")
static Persistence<Car, Integer> mockPersistence(String name) {
return mock(Persistence.class, name);
}
@SuppressWarnings("unchecked")
static Index<Car> mockIndex(String name) {
return mock(Index.class, name);
}
static List<Persistence<Car, Integer>> noAdditionalPersistences() {
return Collections.emptyList();
}
} | 12,593 | 48.97619 | 162 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/wrapping/WrappingPersistenceTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.persistence.support.CollectionWrappingObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Test;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import static com.googlecode.cqengine.IndexedCollectionFunctionalTest.asSet;
import static com.googlecode.cqengine.IndexedCollectionFunctionalTest.extractCarIds;
import static com.googlecode.cqengine.query.QueryFactory.greaterThan;
import static org.junit.Assert.*;
/**
* Tests for {@link WrappingPersistence}.
*
* @author npgall
*/
public class WrappingPersistenceTest {
@Test
public void testWrappingPersistence() {
Collection<Car> backingCollection = new LinkedHashSet<Car>();
backingCollection.addAll(CarFactory.createCollectionOfCars(3)); // CarIds 0, 1, 2
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>(
WrappingPersistence.aroundCollection(backingCollection)
);
indexedCollection.addIndex(NavigableIndex.onAttribute(Car.CAR_ID));
ResultSet<Car> results = indexedCollection.retrieve(greaterThan(Car.CAR_ID, 0));
// Assert that the index will be used...
assertNotEquals(Integer.MAX_VALUE, results.getRetrievalCost());
// Assert correct results are returned...
Set<Integer> expectedCarIds, actualCarIds;
expectedCarIds = asSet(1, 2);
actualCarIds = extractCarIds(results, new HashSet<Integer>());
assertEquals(expectedCarIds, actualCarIds);
// Add that a new object added to the IndexedCollection...
indexedCollection.add(CarFactory.createCar(3));
// Assert the new object was added to the backing collection...
expectedCarIds = asSet(0, 1, 2, 3);
actualCarIds = extractCarIds(backingCollection, new HashSet<Integer>());
assertEquals(expectedCarIds, actualCarIds);
}
@Test
public void testGetPrimaryKeyAttribute() throws Exception {
WrappingPersistence<Car, Integer> wrappingPersistence =
WrappingPersistence.aroundCollectionOnPrimaryKey(new HashSet<Car>(), Car.CAR_ID);
assertEquals(Car.CAR_ID, wrappingPersistence.getPrimaryKeyAttribute());
}
@Test
public void testSupportsIndex() throws Exception {
WrappingPersistence<Car, Integer> wrappingPersistence =
WrappingPersistence.aroundCollectionOnPrimaryKey(new HashSet<Car>(), Car.CAR_ID);
assertTrue(wrappingPersistence.supportsIndex(NavigableIndex.onAttribute(Car.MANUFACTURER)));
assertFalse(wrappingPersistence.supportsIndex(DiskIndex.onAttribute(Car.MANUFACTURER)));
}
@Test
public void testCreateObjectStore() throws Exception {
HashSet<Car> backingCollection = new HashSet<Car>();
WrappingPersistence<Car, Integer> wrappingPersistence =
WrappingPersistence.aroundCollectionOnPrimaryKey(backingCollection, Car.CAR_ID);
ObjectStore<Car> objectStore = wrappingPersistence.createObjectStore();
assertTrue(objectStore instanceof CollectionWrappingObjectStore);
assertEquals(backingCollection, ((CollectionWrappingObjectStore)objectStore).getBackingCollection());
}
} | 4,335 | 39.523364 | 109 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/disk/DiskPersistenceTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static java.util.stream.Collectors.toSet;
/**
* @author niall.gallagher
*/
public class DiskPersistenceTest {
@Test
public void testGetBytesUsed() {
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(50));
long bytesUsed = persistence.getBytesUsed();
Assert.assertTrue("Bytes used should be greater than zero: " + bytesUsed, bytesUsed > 0);
Assert.assertTrue("Failed to delete temp file:" + persistence.getFile(), persistence.getFile().delete());
}
@Test
public void testCompact() {
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(100));
long bytesUsedWhenFullyPopulated = persistence.getBytesUsed();
Assert.assertTrue("Bytes used when fully populated should be greater than zero: " + bytesUsedWhenFullyPopulated, bytesUsedWhenFullyPopulated > 0);
cars.removeAll(CarFactory.createCollectionOfCars(100));
long bytesUsedWhenObjectsRemoved = persistence.getBytesUsed();
Assert.assertTrue("Bytes used when objects removed (" + bytesUsedWhenObjectsRemoved + ") should remain the same as when fully populated (" + bytesUsedWhenFullyPopulated + ")", bytesUsedWhenObjectsRemoved == bytesUsedWhenFullyPopulated);
persistence.compact(); // Truncates size of the database, but not to zero as the tables which were created remain (although empty)
long bytesUsedAfterCompaction = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after compaction (" + bytesUsedAfterCompaction + ") should be less than when fully populated (" + bytesUsedWhenFullyPopulated + ")", bytesUsedAfterCompaction < bytesUsedWhenFullyPopulated);
Assert.assertTrue("Failed to delete temp file:" + persistence.getFile(), persistence.getFile().delete());
}
@Test
public void testExpand() {
final long bytesToExpand = 102400; // Expand by 100KB;
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(50));
persistence.compact();
long initialBytesUsed = persistence.getBytesUsed();
Assert.assertTrue("Initial bytes used should be greater than zero: " + initialBytesUsed, initialBytesUsed > 0);
persistence.expand(bytesToExpand);
long bytesUsedAfterExpanding = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after expanding (" + bytesUsedAfterExpanding + ") should have been increased by at least bytes to expand (" + bytesToExpand + ") above initial bytes used (" + initialBytesUsed + ")", bytesUsedAfterExpanding >= (initialBytesUsed + bytesToExpand));
persistence.compact();
long bytesUsedAfterCompaction = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after compaction (" + bytesUsedAfterCompaction + ") should be equal to initial bytes used (" + initialBytesUsed + ")", bytesUsedAfterCompaction == initialBytesUsed);
Assert.assertTrue("Failed to delete temp file:" + persistence.getFile(), persistence.getFile().delete());
}
@Test
public void testSupportsIndex() {
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
Index<Car> diskIndex = DiskIndex.onAttribute(Car.MANUFACTURER);
Index<Car> offHeapIndex = OffHeapIndex.onAttribute(Car.MANUFACTURER);
Index<Car> navigableIndex = NavigableIndex.onAttribute(Car.MANUFACTURER);
Assert.assertTrue(persistence.supportsIndex(diskIndex));
Assert.assertFalse(persistence.supportsIndex(offHeapIndex));
Assert.assertFalse(persistence.supportsIndex(navigableIndex));
}
@Test
public void testEqualsAndHashCode() {
SQLiteDataSource ds1 = new SQLiteDataSource(new SQLiteConfig());
ds1.setUrl("foo");
SQLiteDataSource ds2 = new SQLiteDataSource(new SQLiteConfig());
ds2.setUrl("bar");
EqualsVerifier.forClass(DiskPersistence.class)
.withIgnoredFields("sqLiteDataSource", "persistentConnection", "closed", "useReadWriteLock", "readWriteLock")
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.withPrefabValues(SQLiteDataSource.class, ds1, ds2)
.verify();
}
@Test
public void testEndToEndDiskPersistence() {
Set<Integer> expectedCarIds = new HashSet<Integer>();
Set<Integer> actualCarIds = new HashSet<Integer>();
File persistenceFile;
{
// Create a collection of 50 cars persisted to disk...
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
persistenceFile = persistence.getFile();
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addIndex(DiskIndex.onAttribute(Car.MANUFACTURER));
cars.addAll(CarFactory.createCollectionOfCars(50));
// Record the carIds of all "Ford" cars...
try (ResultSet<Car> blueCars = cars.retrieve(equal(Car.MANUFACTURER, "Ford"))) {
for (Car car : blueCars) {
expectedCarIds.add(car.getCarId());
}
// At this point we discard collection but we leave the persistence file on disk.
}
}
{
// Create a new collection, whose data is retrieved from the persistence file created earlier...
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, persistenceFile);
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addIndex(DiskIndex.onAttribute(Car.MANUFACTURER));
// Record the carIds of all "Ford" cars, as loaded from the persistence file...
try (ResultSet<Car> blueCars = cars.retrieve(equal(Car.MANUFACTURER, "Ford"))) {
for (Car car : blueCars) {
actualCarIds.add(car.getCarId());
}
}
}
// Assert we got the same results both times...
Assert.assertEquals(expectedCarIds, actualCarIds);
Assert.assertTrue("Failed to delete temp file:" + persistenceFile, persistenceFile.delete());
}
// ================================================================================================
// === Manual tests, used to verify disk persistence compatibility between CQEngine versions... ===
// ================================================================================================
@Test @Ignore
public void testSaveToDisk() {
Set<Car> collectionOfCars = CarFactory.createCollectionOfCars(50);
Set<Integer> expectedCarIds = collectionOfCars.stream().map(Car::getCarId).collect(toSet());
File persistenceFile = new File("cqengine-persisted.dat");
System.out.println("Persistence file: " + persistenceFile.getAbsolutePath());
// Create a collection (it will initially be empty if the file does not exist)...
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, persistenceFile);
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
// Populate the collection (saving it to disk)...
cars.addAll(collectionOfCars);
// Sanity check that we saved the cars correctly...
Set<Integer> actualCarIds = cars.stream().map(Car::getCarId).collect(toSet());
Assert.assertEquals(expectedCarIds, actualCarIds);
System.out.println("Saved to disk: " + actualCarIds);
}
@Test @Ignore
public void testReadFromDisk() {
Set<Car> collectionOfCars = CarFactory.createCollectionOfCars(50);
Set<Integer> expectedCarIds = collectionOfCars.stream().map(Car::getCarId).collect(toSet());
File persistenceFile = new File("cqengine-persisted.dat");
System.out.println("Persistence file: " + persistenceFile.getAbsolutePath());
// Create a collection (it will read from the pre-existing file on disk)...
DiskPersistence<Car, Integer> persistence = DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, persistenceFile);
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
// Retrieve the cars from disk...
Set<Integer> actualCarIds = cars.stream().map(Car::getCarId).collect(toSet());
Assert.assertEquals(expectedCarIds, actualCarIds);
System.out.println("Loaded from disk: " + actualCarIds);
}
} | 10,777 | 51.57561 | 284 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/disk/DiskSharedCacheConcurrencyTest.java | package com.googlecode.cqengine.persistence.disk;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import static com.googlecode.cqengine.query.QueryFactory.attribute;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Unit tests for the {@code shared_cache} mode of {@link DiskPersistence}.
*/
public class DiskSharedCacheConcurrencyTest {
/**
* Unit test which demonstrates the value of using a read-write lock when {@code shared_cache} mode is enabled.
* <p>
* This fails if {@code shared_cache} is enabled while {@code use_read_write_lock} is disabled,
* and it passes when {@code shared_cache} is enabled and {@code use_read_write_lock} is also enabled.
*/
@Test
public void testDiskSharedCacheConcurrency() throws InterruptedException {
Properties properties = new Properties();
properties.setProperty("shared_cache", "true");
properties.setProperty("use_read_write_lock", "true");
final int NUM_BACKGROUND_THREADS = 4;
// Integer generator...
final AtomicInteger idCounter = new AtomicInteger(0);
// A POJO class, where every instance has a different id generated by the integer generator above...
class TestPojo {
Integer id = idCounter.incrementAndGet();
}
// An attribute which reads the id field of the POJO...
final SimpleAttribute<TestPojo, Integer> primaryKey = attribute(object -> object.id);
// Create a temp file...
File tempFile = DiskPersistence.createTempFile();
// Create a collection of TestPojo objects which persists to the temp file...
IndexedCollection<TestPojo> collection = new ConcurrentIndexedCollection<>(
DiskPersistence.onPrimaryKeyInFileWithProperties(primaryKey, tempFile, properties)
);
// Prepare a latch which will tell us when all background threads have finished executing...
final CountDownLatch latch = new CountDownLatch(NUM_BACKGROUND_THREADS);
// Start the background threads...
for (int i = 0; i < NUM_BACKGROUND_THREADS; i++) {
new Thread(() -> {
// In each background thread, add one new object to the collection...
try {
collection.add(new TestPojo());
}
catch (Exception ignore) { }
finally {
latch.countDown();
}
}).start();
}
// Wait for all background threads to finish...
latch.await(20, SECONDS);
// Assert that the same number of objects were inserted as there were background threads...
Assert.assertEquals(NUM_BACKGROUND_THREADS, collection.size());
// Delete the temp file...
Assert.assertEquals(true, tempFile.delete());
}
}
| 3,165 | 38.08642 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/disk/DiskPersistenceConcurrencyTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.googlecode.cqengine.query.QueryFactory.between;
/**
* A test of concurrent reads and writes to a collection using {@link DiskPersistence}
* with journam modes WAL and DELETE.
*/
public class DiskPersistenceConcurrencyTest {
@Test
public void testDiskPersistenceConcurrency_JournalModeWal() {
File tempFile = DiskPersistence.createTempFile();
final IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(
DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, tempFile)
);
collection.addAll(CarFactory.createCollectionOfCars(100));
final List<String> sequenceLog = Collections.synchronizedList(new ArrayList<String>());
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(new ReadingTask("ReadingTask 1", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new ReadingTask("ReadingTask 2", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new WritingTask("WritingTask 1", collection, sequenceLog)); // start this task after waiting 500ms
executorService.shutdown();
awaitTermination(executorService);
List<String> expected = Arrays.asList(
"ReadingTask 1 started and about to access collection",
"ReadingTask 1 pausing mid-read", // Successfully acquired the first read lock
"ReadingTask 2 started and about to access collection",
"ReadingTask 2 pausing mid-read", // Successfully acquired a second read lock concurrently
"WritingTask 1 started and about to access collection", // Should not block because WAL allows concurrent reads and writes
"WritingTask 1 finished removing 1 item", // Successfully acquired write lock even though reads are ongoing
"ReadingTask 1 resuming read",
"ReadingTask 1 finished reading 20 items",
"ReadingTask 2 resuming read",
"ReadingTask 2 finished reading 20 items"
);
Assert.assertEquals(expected, sequenceLog);
tempFile.delete();
}
@Test
public void testDiskPersistenceConcurrency_JournalModeDelete() {
File tempFile = DiskPersistence.createTempFile();
final IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(
DiskPersistence.onPrimaryKeyInFileWithProperties(
Car.CAR_ID,
tempFile,
new Properties() {{
setProperty("journal_mode", "DELETE");
}}
)
);
collection.addAll(CarFactory.createCollectionOfCars(100));
final List<String> sequenceLog = Collections.synchronizedList(new ArrayList<String>());
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(new ReadingTask("ReadingTask 1", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new ReadingTask("ReadingTask 2", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new WritingTask("WritingTask 1", collection, sequenceLog)); // start this task after waiting 500ms
executorService.shutdown();
awaitTermination(executorService);
List<String> expected = Arrays.asList(
"ReadingTask 1 started and about to access collection",
"ReadingTask 1 pausing mid-read", // Successfully acquired the first read lock
"ReadingTask 2 started and about to access collection",
"ReadingTask 2 pausing mid-read", // Successfully acquired a second read lock concurrently
"WritingTask 1 started and about to access collection", // Should block until both reads finish
"ReadingTask 1 resuming read",
"ReadingTask 1 finished reading 20 items",
"ReadingTask 2 resuming read",
"ReadingTask 2 finished reading 20 items",
"WritingTask 1 finished removing 1 item" // Finally was granted write lock
);
Assert.assertEquals(expected, sequenceLog);
tempFile.delete();
}
static class ReadingTask implements Runnable {
final String taskName;
final IndexedCollection<Car> collection;
final long millisecondsToPauseMidRequest;
final List<String> sequenceLog;
public ReadingTask(String taskName, IndexedCollection<Car> collection, long millisecondsToPauseMidRequest, List<String> sequenceLog) {
this.taskName = taskName;
this.collection = collection;
this.millisecondsToPauseMidRequest = millisecondsToPauseMidRequest;
this.sequenceLog = sequenceLog;
}
@Override
public void run() {
sequenceLog.add(taskName + " started and about to access collection");
ResultSet<Car> backgroundResults = collection.retrieve(between(Car.CAR_ID, 40, 59));
Iterator<Car> iterator = backgroundResults.iterator();
int count = 0;
for (; iterator.hasNext() && count < 5; count++) {
iterator.next();
}
sequenceLog.add(taskName + " pausing mid-read");
sleep(millisecondsToPauseMidRequest);
sequenceLog.add(taskName + " resuming read");
while (iterator.hasNext()) {
iterator.next();
count++;
}
backgroundResults.close();
sequenceLog.add(taskName + " finished reading " + count + " items");
}
}
static class WritingTask implements Runnable {
final String taskName;
final IndexedCollection<Car> indexedCollection;
final List<String> sequenceLog;
public WritingTask(String taskName, IndexedCollection<Car> indexedCollection, List<String> sequenceLog) {
this.taskName = taskName;
this.indexedCollection = indexedCollection;
this.sequenceLog = sequenceLog;
}
@Override
public void run() {
sequenceLog.add(taskName + " started and about to access collection");
indexedCollection.remove(CarFactory.createCar(71));
sequenceLog.add(taskName + " finished removing 1 item");
}
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
static void awaitTermination(ExecutorService executorService) {
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
| 8,312 | 42.52356 | 164 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/support/FilteredObjectStoreTest.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 com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.between;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* Tests for {@link FilteredObjectStore}.
*
* @author niall.gallagher
*/
public class FilteredObjectStoreTest {
final FilteredObjectStore<Car> filteredObjectStore = new FilteredObjectStore<Car>(
nonEmptyObjectStore(CarFactory.createCollectionOfCars(10)),
between(Car.CAR_ID, 2, 4)
);
final Car dummyCar = CarFactory.createCar(0);
@Test
public void testIterator_Filtering() {
Set<Integer> results = new HashSet<Integer>();
CloseableIterator<Car> iterator = filteredObjectStore.iterator(noQueryOptions());
while (iterator.hasNext()) {
results.add(iterator.next().getCarId());
}
assertEquals(new HashSet<Integer>(asList(2,3,4)), results);
}
@Test
@SuppressWarnings("unchecked")
public void testIterator_Close() {
CloseableIterator<Car> mockIterator = mock(CloseableIterator.class);
ObjectStore<Car> mockObjectStore = mock(ObjectStore.class);
Mockito.when(mockObjectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(mockIterator);
FilteredObjectStore<Car> filteredObjectStore = new FilteredObjectStore<Car>(
mockObjectStore,
between(Car.CAR_ID, 2, 4)
);
filteredObjectStore.iterator(noQueryOptions()).close();
verify(mockIterator, times(1)).close();
}
@Test(expected = UnsupportedOperationException.class)
public void testAddAll() {
filteredObjectStore.addAll(Collections.<Car>emptySet(), noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testClear() {
filteredObjectStore.clear(noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testContains() {
filteredObjectStore.contains(dummyCar, noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testRemove() {
filteredObjectStore.remove(dummyCar, noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testAdd() {
filteredObjectStore.add(dummyCar, noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testSize() {
filteredObjectStore.size(noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testContainsAll() {
filteredObjectStore.containsAll(Collections.singleton(dummyCar), noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testIsEmpty() {
filteredObjectStore.isEmpty(noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testRetainAll() {
filteredObjectStore.retainAll(Collections.singleton(dummyCar), noQueryOptions());
}
@Test(expected = UnsupportedOperationException.class)
public void testRemoveAll() {
filteredObjectStore.removeAll(Collections.singleton(dummyCar), noQueryOptions());
}
static ConcurrentOnHeapObjectStore<Car> nonEmptyObjectStore(Collection<Car> contents) {
ConcurrentOnHeapObjectStore<Car> objectStore = new ConcurrentOnHeapObjectStore<Car>();
objectStore.addAll(contents, noQueryOptions());
return objectStore;
}
} | 4,624 | 33.774436 | 101 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/support/ObjectSetTest.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 com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
/**
* Tests for {@link ObjectSet}.
*
* @author niall.gallagher
*/
public class ObjectSetTest {
// ====== Tests for ObjectStore-based implementation of ObjectSet... ======
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IteratorClose() throws Exception {
ObjectStore<Car> objectStore = mock(ObjectStore.class);
CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);
ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
CloseableIterator<Car> objectSetIterator = objectSet.iterator();
objectSetIterator.close();
Mockito.verify(closeableIterator, times(1)).close();
}
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IteratorRemove() throws Exception {
ObjectStore<Car> objectStore = mock(ObjectStore.class);
CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
when(closeableIterator.hasNext()).thenReturn(true);
when(closeableIterator.next()).thenReturn(CarFactory.createCar(1));
when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);
ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
CloseableIterator<Car> objectSetIterator = objectSet.iterator();
Assert.assertTrue(objectSetIterator.hasNext());
Assert.assertNotNull(objectSetIterator.next());
objectSetIterator.remove();
Mockito.verify(closeableIterator, times(1)).remove();
}
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_ObjectSetClose() throws Exception {
ObjectStore<Car> objectStore = mock(ObjectStore.class);
CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);
ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
objectSet.iterator();
objectSet.close(); // should close the iterator
objectSet.close(); // should have no effect as it was removed from openIterators
Mockito.verify(closeableIterator, times(1)).close();
}
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IsEmpty_True() throws Exception {
ObjectStore<Car> objectStore = mock(ObjectStore.class);
CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
when(closeableIterator.hasNext()).thenReturn(false);
when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);
ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
Assert.assertEquals(true, objectSet.isEmpty());
Mockito.verify(closeableIterator, times(1)).close();
}
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IsEmpty_False() throws Exception {
ObjectStore<Car> objectStore = mock(ObjectStore.class);
CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
when(closeableIterator.hasNext()).thenReturn(true);
when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);
ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
Assert.assertEquals(false, objectSet.isEmpty());
Mockito.verify(closeableIterator, times(1)).close();
}
// ====== Tests for Collection-based implementation of ObjectSet... ======
@Test
@SuppressWarnings("unchecked")
public void testFromCollection_IteratorClose() throws Exception {
ObjectSet<Car> objectSet = ObjectSet.fromCollection(Collections.<Car>emptySet());
objectSet.iterator().close(); // Can't really verify anything because close() is a no-op
}
@Test
@SuppressWarnings("unchecked")
public void testFromCollection_IteratorRemove() throws Exception {
Collection<Car> collection = mock(Collection.class);
Iterator<Car> iterator = mock(Iterator.class);
when(iterator.hasNext()).thenReturn(true);
when(iterator.next()).thenReturn(CarFactory.createCar(1));
when(collection.iterator()).thenReturn(iterator);
ObjectSet<Car> objectSet = ObjectSet.fromCollection(collection);
CloseableIterator<Car> objectSetIterator = objectSet.iterator();
Assert.assertTrue(objectSetIterator.hasNext());
Assert.assertNotNull(objectSetIterator.next());
objectSetIterator.remove();
Mockito.verify(iterator, times(1)).remove();
}
@Test
@SuppressWarnings("unchecked")
public void testFromCollection_IsEmpty_True() throws Exception {
Collection<Car> collection = mock(Collection.class);
when(collection.isEmpty()).thenReturn(true);
ObjectSet<Car> objectSet = ObjectSet.fromCollection(collection);
Assert.assertEquals(true, objectSet.isEmpty());
}
@Test
@SuppressWarnings("unchecked")
public void testFromCollection_IsEmpty_False() throws Exception {
Collection<Car> collection = mock(Collection.class);
when(collection.isEmpty()).thenReturn(false);
ObjectSet<Car> objectSet = ObjectSet.fromCollection(collection);
Assert.assertEquals(false, objectSet.isEmpty());
}
} | 6,810 | 40.785276 | 96 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/support/serialization/KryoSerializerTest.java | package com.googlecode.cqengine.persistence.support.serialization;
import org.junit.Test;
import java.lang.annotation.Annotation;
/**
* Unit tests for {@link KryoSerializer}.
*
* @author npgall
*/
public class KryoSerializerTest {
@Test
public void testPositiveSerializability() {
KryoSerializer.validateObjectIsRoundTripSerializable(new KryoSerializablePojo(1));
}
@Test(expected = IllegalStateException.class)
public void testNegativeSerializability() {
KryoSerializer.validateObjectIsRoundTripSerializable(new NonKryoSerializablePojo(1));
}
@Test(expected = IllegalStateException.class)
public void testValidateObjectEquality() {
KryoSerializer.validateObjectEquality(1, 2);
}
@Test(expected = IllegalStateException.class)
public void testValidateHashCodeEquality() {
KryoSerializer.validateHashCodeEquality(1, 2);
}
@Test(expected = IllegalStateException.class)
public void testPolymorphicSerialization_WithNonPolymorphicConfig() {
KryoSerializer.validateObjectIsRoundTripSerializable(1, Number.class, PersistenceConfig.DEFAULT_CONFIG);
}
@Test
public void testPolymorphicSerialization_WithPolymorphicConfig() {
KryoSerializer.validateObjectIsRoundTripSerializable(1, Number.class, POLYMORPHIC_CONFIG);
}
@SuppressWarnings("unused")
static class KryoSerializablePojo {
int i;
KryoSerializablePojo() {
}
KryoSerializablePojo(int i) {
this.i = i;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof KryoSerializablePojo)) return false;
KryoSerializablePojo that = (KryoSerializablePojo) o;
return i == that.i;
}
@Override
public int hashCode() {
return i;
}
}
@SuppressWarnings("unused")
static class NonKryoSerializablePojo {
int i;
NonKryoSerializablePojo() {
throw new IllegalStateException("Intentional exception");
}
NonKryoSerializablePojo(int i) {
this.i = i;
}
}
PersistenceConfig POLYMORPHIC_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 true;
}
};
} | 2,639 | 26.216495 | 112 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/offheap/OffHeapPersistenceTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Assert;
import org.junit.Test;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
/**
* @author niall.gallagher
*/
public class OffHeapPersistenceTest {
@Test
public void testGetBytesUsed() {
OffHeapPersistence<Car, Integer> persistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(50));
long bytesUsed = persistence.getBytesUsed();
Assert.assertTrue("Bytes used should be greater than zero: " + bytesUsed, bytesUsed > 0);
}
@Test
public void testCompact() {
OffHeapPersistence<Car, Integer> persistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(100));
long bytesUsedWhenFullyPopulated = persistence.getBytesUsed();
Assert.assertTrue("Bytes used when fully populated should be greater than zero: " + bytesUsedWhenFullyPopulated, bytesUsedWhenFullyPopulated > 0);
cars.removeAll(CarFactory.createCollectionOfCars(100));
long bytesUsedWhenObjectsRemoved = persistence.getBytesUsed();
Assert.assertTrue("Bytes used when objects removed (" + bytesUsedWhenObjectsRemoved + ") should remain the same as when fully populated (" + bytesUsedWhenFullyPopulated + ")", bytesUsedWhenObjectsRemoved == bytesUsedWhenFullyPopulated);
persistence.compact(); // Truncates size of the database, but not to zero as the tables which were created remain (although empty)
long bytesUsedAfterCompaction = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after compaction (" + bytesUsedAfterCompaction + ") should be less than when fully populated (" + bytesUsedWhenFullyPopulated + ")", bytesUsedAfterCompaction < bytesUsedWhenFullyPopulated);
}
@Test
public void testExpand() {
final long bytesToExpand = 102400; // Expand by 100KB;
OffHeapPersistence<Car, Integer> persistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(persistence);
cars.addAll(CarFactory.createCollectionOfCars(50));
persistence.compact();
long initialBytesUsed = persistence.getBytesUsed();
Assert.assertTrue("Initial bytes used should be greater than zero: " + initialBytesUsed, initialBytesUsed > 0);
persistence.expand(bytesToExpand);
long bytesUsedAfterExpanding = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after expanding (" + bytesUsedAfterExpanding + ") should have been increased by at least bytes to expand (" + bytesToExpand + ") above initial bytes used (" + initialBytesUsed + ")", bytesUsedAfterExpanding >= (initialBytesUsed + bytesToExpand));
persistence.compact();
long bytesUsedAfterCompaction = persistence.getBytesUsed();
Assert.assertTrue("Bytes used after compaction (" + bytesUsedAfterCompaction + ") should be equal to initial bytes used (" + initialBytesUsed + ")", bytesUsedAfterCompaction == initialBytesUsed);
}
@Test
public void testSupportsIndex() {
OffHeapPersistence<Car, Integer> persistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
Index<Car> offHeapIndex = OffHeapIndex.onAttribute(Car.MANUFACTURER);
Index<Car> diskIndex = DiskIndex.onAttribute(Car.MANUFACTURER);
Index<Car> navigableIndex = NavigableIndex.onAttribute(Car.MANUFACTURER);
Assert.assertTrue(persistence.supportsIndex(offHeapIndex));
Assert.assertFalse(persistence.supportsIndex(diskIndex));
Assert.assertFalse(persistence.supportsIndex(navigableIndex));
}
@Test
public void testEqualsAndHashCode() {
SQLiteDataSource ds1 = new SQLiteDataSource(new SQLiteConfig());
ds1.setUrl("foo");
SQLiteDataSource ds2 = new SQLiteDataSource(new SQLiteConfig());
ds2.setUrl("bar");
EqualsVerifier.forClass(OffHeapPersistence.class)
.withIgnoredFields("sqLiteDataSource", "persistentConnection", "closed", "readWriteLock")
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.withPrefabValues(SQLiteDataSource.class, ds1, ds2)
.verify();
}
} | 5,809 | 53.299065 | 284 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/persistence/offheap/OffHeapPersistenceConcurrencyTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.googlecode.cqengine.query.QueryFactory.between;
/**
* A test of concurrent reads and writes to a collection using {@link OffHeapPersistence}.
*/
public class OffHeapPersistenceConcurrencyTest {
@Test
public void testOffHeapPersistenceConcurrency() {
final IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(OffHeapPersistence.onPrimaryKey(Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
final List<String> sequenceLog = Collections.synchronizedList(new ArrayList<String>());
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(new ReadingTask("ReadingTask 1", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new ReadingTask("ReadingTask 2", collection, 1500, sequenceLog)); // start immediately, pause for 1 second, then resume to completion
sleep(500);
executorService.submit(new WritingTask("WritingTask 1", collection, sequenceLog)); // start this task after waiting 500ms
executorService.shutdown();
awaitTermination(executorService);
List<String> expected = Arrays.asList(
"ReadingTask 1 started and about to access collection",
"ReadingTask 1 pausing mid-read", // Successfully acquired the first read lock
"ReadingTask 2 started and about to access collection",
"ReadingTask 2 pausing mid-read", // Successfully acquired a second read lock concurrently
"WritingTask 1 started and about to access collection", // Should block until both reads finish
"ReadingTask 1 resuming read",
"ReadingTask 1 finished reading 20 items",
"ReadingTask 2 resuming read",
"ReadingTask 2 finished reading 20 items",
"WritingTask 1 finished removing 1 item" // Finally was granted write lock
);
Assert.assertEquals(expected, sequenceLog);
}
static class ReadingTask implements Runnable {
final String taskName;
final IndexedCollection<Car> collection;
final long millisecondsToPauseMidRequest;
final List<String> sequenceLog;
public ReadingTask(String taskName, IndexedCollection<Car> collection, long millisecondsToPauseMidRequest, List<String> sequenceLog) {
this.taskName = taskName;
this.collection = collection;
this.millisecondsToPauseMidRequest = millisecondsToPauseMidRequest;
this.sequenceLog = sequenceLog;
}
@Override
public void run() {
sequenceLog.add(taskName + " started and about to access collection");
ResultSet<Car> backgroundResults = collection.retrieve(between(Car.CAR_ID, 40, 59));
Iterator<Car> iterator = backgroundResults.iterator();
int count = 0;
for (; iterator.hasNext() && count < 5; count++) {
iterator.next();
}
sequenceLog.add(taskName + " pausing mid-read");
sleep(millisecondsToPauseMidRequest);
sequenceLog.add(taskName + " resuming read");
while (iterator.hasNext()) {
iterator.next();
count++;
}
backgroundResults.close();
sequenceLog.add(taskName + " finished reading " + count + " items");
}
}
static class WritingTask implements Runnable {
final String taskName;
final IndexedCollection<Car> indexedCollection;
final List<String> sequenceLog;
public WritingTask(String taskName, IndexedCollection<Car> indexedCollection, List<String> sequenceLog) {
this.taskName = taskName;
this.indexedCollection = indexedCollection;
this.sequenceLog = sequenceLog;
}
@Override
public void run() {
sequenceLog.add(taskName + " started and about to access collection");
indexedCollection.remove(CarFactory.createCar(71));
sequenceLog.add(taskName + " finished removing 1 item");
}
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
static void awaitTermination(ExecutorService executorService) {
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
| 5,834 | 39.804196 | 164 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/OffHeapConcurrentIndexedCollection.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.testutil;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.composite.CompositePersistence;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
/**
* For testing purposes - a {@link ConcurrentIndexedCollection} hard-wired to use off-heap persistence.
*
* @author niall.gallagher
*/
public class OffHeapConcurrentIndexedCollection extends ConcurrentIndexedCollection<Car> {
public OffHeapConcurrentIndexedCollection() {
this(OffHeapPersistence.onPrimaryKey(Car.CAR_ID));
}
public OffHeapConcurrentIndexedCollection(Persistence<Car, Integer> persistence) {
super(persistence);
boolean isOffHeapPersistence = persistence instanceof OffHeapPersistence;
boolean isCompositePersistenceWithOffHeapPrimary = persistence instanceof CompositePersistence && ((CompositePersistence) persistence).getPrimaryPersistence() instanceof OffHeapPersistence;
if (!isOffHeapPersistence && !isCompositePersistenceWithOffHeapPrimary) {
throw new IllegalStateException("Unexpected persistence implementation: " + persistence);
}
}
}
| 1,858 | 41.25 | 197 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/DiskConcurrentIndexedCollection.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.testutil;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.composite.CompositePersistence;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
/**
* For testing purposes - a {@link ConcurrentIndexedCollection} hard-wired to use disk persistence.
*
* @author niall.gallagher
*/
public class DiskConcurrentIndexedCollection extends ConcurrentIndexedCollection<Car> {
public DiskConcurrentIndexedCollection() {
super(DiskPersistence.onPrimaryKey(Car.CAR_ID));
}
public DiskConcurrentIndexedCollection(Persistence<Car, Integer> persistence) {
super(persistence);
boolean isDiskPersistence = persistence instanceof DiskPersistence;
boolean isCompositePersistenceWithDiskPrimary = persistence instanceof CompositePersistence && ((CompositePersistence) persistence).getPrimaryPersistence() instanceof DiskPersistence;
if (!isDiskPersistence && !isCompositePersistenceWithDiskPrimary) {
throw new IllegalStateException("Unexpected persistence implementation: " + persistence);
}
}
}
| 1,818 | 41.302326 | 191 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/MobileTerminating.java | package com.googlecode.cqengine.testutil;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
public class MobileTerminating {
private String prefix;
private String operatorName;
private String region;
private String zone;
public MobileTerminating(String prefix, String operatorName, String region, String zone) {
super();
this.prefix = prefix;
this.operatorName = operatorName;
this.region = region;
this.zone = zone;
}
/**
* @return the prefix
*/
public String getPrefix() {
return prefix;
}
/**
* @param prefix the prefix to set
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* @return the operatorName
*/
public String getOperatorName() {
return operatorName;
}
/**
* @param operatorName the operatorName to set
*/
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
/**
* @return the region
*/
public String getRegion() {
return region;
}
/**
* @param region the region to set
*/
public void setRegion(String region) {
this.region = region;
}
/**
* @return the zone
*/
public String getZone() {
return zone;
}
/**
* @param zone the zone to set
*/
public void setZone(String zone) {
this.zone = zone;
}
public static final SimpleAttribute<MobileTerminating, String> PREFIX = new SimpleAttribute<MobileTerminating, String>("prefix") {
@Override
public String getValue(MobileTerminating object, QueryOptions queryOptions) {
return object.getPrefix();
}
};
public static final SimpleAttribute<MobileTerminating, String> OPERATOR_NAME = new SimpleAttribute<MobileTerminating, String>("operatorName") {
@Override
public String getValue(MobileTerminating object, QueryOptions queryOptions) {
return object.getOperatorName();
}
};
public static final SimpleAttribute<MobileTerminating, String> REGION = new SimpleAttribute<MobileTerminating, String>("region") {
@Override
public String getValue(MobileTerminating object, QueryOptions queryOptions) {
return object.getRegion();
}
};
public static final SimpleAttribute<MobileTerminating, String> ZONE = new SimpleAttribute<MobileTerminating, String>("zone") {
@Override
public String getValue(MobileTerminating object, QueryOptions queryOptions) {
return object.getZone();
}
};
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MobileTerminating [prefix=" + prefix + ", operatorName=" + operatorName + ", region=" + region
+ ", zone=" + zone + "]";
}
}
| 3,040 | 27.157407 | 147 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/CarFactory.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.testutil;
import com.googlecode.concurrenttrees.common.LazyIterator;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.Arrays.asList;
/**
* @author Niall Gallagher
*/
public class CarFactory {
public static Set<Car> createCollectionOfCars(int numCars) {
Set<Car> cars = new LinkedHashSet<Car>(numCars);
for (int carId = 0; carId < numCars; carId++) {
cars.add(createCar(carId));
}
return cars;
}
public static Iterable<Car> createIterableOfCars(final int numCars) {
final AtomicInteger count = new AtomicInteger();
return new Iterable<Car>() {
@Override
public Iterator<Car> iterator() {
return new LazyIterator<Car>() {
@Override
protected Car computeNext() {
int carId = count.getAndIncrement();
return carId < numCars ? createCar(carId) : endOfData();
}
};
}
};
}
public static Car createCar(int carId) {
switch (carId % 10) {
case 0: return new Car(carId, "Ford", "Focus", Car.Color.RED, 5, 5000.00, noFeatures(), noKeywords());
case 1: return new Car(carId, "Ford", "Fusion", Car.Color.RED, 4, 3999.99, asList("hybrid"), asList("zulu"));
case 2: return new Car(carId, "Ford", "Taurus", Car.Color.GREEN, 4, 6000.00, asList("grade a"), asList("alpha"));
case 3: return new Car(carId, "Honda", "Civic", Car.Color.WHITE, 5, 4000.00, asList("grade b"), asList("bravo"));
case 4: return new Car(carId, "Honda", "Accord", Car.Color.BLACK, 5, 3000.00, asList("grade c"), asList("very-good"));
case 5: return new Car(carId, "Honda", "Insight", Car.Color.GREEN, 3, 5000.00, noFeatures(), asList("alpha"));
case 6: return new Car(carId, "Toyota", "Avensis", Car.Color.GREEN, 5, 5999.95, noFeatures(), asList("very-good-car"));
case 7: return new Car(carId, "Toyota", "Prius", Car.Color.BLUE, 3, 8500.00, asList("sunroof", "hybrid"), noKeywords());
case 8: return new Car(carId, "Toyota", "Hilux", Car.Color.RED, 5, 7800.55, noFeatures(), asList("very-good-car"));
case 9: return new Car(carId, "BMW", "M6", Car.Color.BLUE, 2, 9000.23, asList("coupe"), asList("zulu"));
default: throw new IllegalStateException();
}
}
static List<String> noFeatures() {
return Collections.<String>emptyList();
}
static List<String> noKeywords() {
return Collections.<String>emptyList();
}
}
| 3,342 | 41.858974 | 135 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/Car.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.testutil;
import com.googlecode.cqengine.attribute.MultiValueAttribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class Car {
public static final SimpleAttribute<Car, Integer> CAR_ID = new SimpleAttribute<Car, Integer>("carId") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car.carId; }
};
public static final SimpleAttribute<Car, String> MANUFACTURER = new SimpleAttribute<Car, String>("manufacturer") {
public String getValue(Car car, QueryOptions queryOptions) { return car.manufacturer; }
};
public static final SimpleAttribute<Car, String> MODEL = new SimpleAttribute<Car, String>("model") {
public String getValue(Car car, QueryOptions queryOptions) { return car.model; }
};
public static final SimpleAttribute<Car, Color> COLOR = new SimpleAttribute<Car, Color>("color") {
public Color getValue(Car car, QueryOptions queryOptions) { return car.color; }
};
public static final SimpleAttribute<Car, Integer> DOORS = new SimpleAttribute<Car, Integer>("doors") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car.doors; }
};
public static final SimpleAttribute<Car, Double> PRICE = new SimpleAttribute<Car, Double>("price") {
public Double getValue(Car car, QueryOptions queryOptions) { return car.price; }
};
public static final MultiValueAttribute<Car, String> FEATURES = new MultiValueAttribute<Car, String>("features") {
public Iterable<String> getValues(Car car, QueryOptions queryOptions) { return car.features; }
};
public static final MultiValueAttribute<Car, String> KEYWORDS = new MultiValueAttribute<Car, String>("keywords") {
public Iterable<String> getValues(Car car, QueryOptions queryOptions) { return car.keywords; }
};
public enum Color {RED, GREEN, BLUE, BLACK, WHITE}
final int carId;
final String manufacturer;
final String model;
final Color color;
final int doors;
final double price;
final List<String> features;
final List<String> keywords;
public Car(int carId, String manufacturer, String model, Color color, int doors, double price, List<String> features, List<String> keywords) {
this.carId = carId;
this.manufacturer = manufacturer;
this.model = model;
this.color = color;
this.doors = doors;
this.price = price;
this.features = features;
this.keywords = keywords;
}
public int getCarId() {
return carId;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public Color getColor() {
return color;
}
public int getDoors() {
return doors;
}
public double getPrice() {
return price;
}
public List<String> getFeatures() {
return features;
}
@Override
public String toString() {
return "Car{" +
"carId=" + carId +
", manufacturer='" + manufacturer + '\'' +
", model='" + model + '\'' +
", color=" + color +
", doors=" + doors +
", price=" + price +
", features=" + features +
", keywords=" + keywords +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Car)) return false;
Car car = (Car) o;
if (carId != car.carId) return false;
return true;
}
@Override
public int hashCode() {
return carId;
}
}
| 4,455 | 30.602837 | 146 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/TestUtil.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.testutil;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* Utility methods useful in unit tests.
*
* @author Niall Gallagher
*/
public class TestUtil {
/**
* Returns the values of the given attribute in objects returned by the given result set.
* <p/>
* The set returned preserves the order of objects returned by the result set, but eliminates duplicates.
*/
@SuppressWarnings({"JavaDoc"})
public static <O, A> Set<A> valuesOf(Attribute<O, A> attribute, ResultSet<O> resultSet) {
Set<A> attributeValues = new LinkedHashSet<A>();
for (O object : resultSet) {
for (A value : attribute.getValues(object, noQueryOptions())) {
attributeValues.add(value);
}
}
return attributeValues;
}
/**
* Returns a set of the given vararg values. The set preserves the order of values given, but eliminates duplicates.
*/
@SuppressWarnings({"JavaDoc"})
public static <A> Set<A> setOf(A... values) {
return new LinkedHashSet<A>(Arrays.asList(values));
}
public static <A> Set<A> setOf(Iterable<A> values) {
Set<A> result = new LinkedHashSet<A>();
for (A value : values) {
result.add(value);
}
return result;
}
}
| 2,148 | 31.074627 | 120 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/MobileTerminatingFactory.java | package com.googlecode.cqengine.testutil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class MobileTerminatingFactory {
public static Collection<MobileTerminating> getCollectionOfMobileTerminating() {
List<MobileTerminating> mobileTerminating = new ArrayList<>(
Arrays.asList(
new MobileTerminating("353", "na", "ireland", "emea"),
new MobileTerminating("35380", "op1", "ireland", "emea"),
new MobileTerminating("35381", "op2", "ireland", "emea"),
new MobileTerminating("35382", "op3", "ireland", "emea"),
new MobileTerminating("353822", "op4", "ireland", "emea"),
new MobileTerminating("35387", "op5", "ireland", "emea"),
new MobileTerminating("35387123", "op6", "ireland", "emea"),
new MobileTerminating("44123", "op7", "uk", "emea"),
new MobileTerminating("4480", "op8", "uk", "emea"),
new MobileTerminating("4480", "op9", "uk", "emea2"), //deliberate duplication of codes
new MobileTerminating("33380", "op10", "france", "emea"),
new MobileTerminating("33381", "op11", "france", "emea"),
new MobileTerminating("1234", "op12", "usa", "nar"),
new MobileTerminating("111", "op13", "usa", "nar")
));
return mobileTerminating;
}
}
| 1,512 | 42.228571 | 102 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/testutil/IterationCountingSet.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.testutil;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
/**
* A {@link Set} which wraps another set, and which counts the number of objects returned by the set.iterator() method.
*
* @author niall.gallagher
*/
public class IterationCountingSet<T> extends AbstractSet<T> {
final Set<T> backingSet;
int itemsIteratedCount;
public IterationCountingSet(Set<T> backingSet) {
this.backingSet = backingSet;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
final Iterator<T> backingIterator = backingSet.iterator();
@Override
public boolean hasNext() {
return backingIterator.hasNext();
}
@Override
public T next() {
T next = backingIterator.next();
itemsIteratedCount++;
return next;
}
@Override
public void remove() {
backingIterator.remove();
}
};
}
@Override
public int size() {
return backingSet.size();
}
public int getItemsIteratedCount() {
return itemsIteratedCount;
}
} | 1,863 | 26.411765 | 119 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/QueryFactoryTest.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.attribute.support.MultiValueFunction;
import com.googlecode.cqengine.attribute.support.SimpleFunction;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.query.option.*;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import net.jodah.typetools.TypeResolver;
import org.junit.Test;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests for methods in {@link QueryFactory} which are not covered by the functional test.
*
* @author niall.gallagher
*/
public class QueryFactoryTest {
@Test
@SuppressWarnings("unchecked")
public void testOrderByMethodOverloading() {
AttributeOrder<Car> o1 = descending(Car.CAR_ID);
AttributeOrder<Car> o2 = descending(Car.MANUFACTURER);
AttributeOrder<Car> o3 = descending(Car.MODEL);
AttributeOrder<Car> o4 = descending(Car.FEATURES);
AttributeOrder<Car> o5 = descending(Car.PRICE);
assertEquals(orderBy(o1), orderBy(asList(o1)));
assertEquals(orderBy(o1, o2), orderBy(asList(o1, o2)));
assertEquals(orderBy(o1, o2, o3), orderBy(asList(o1, o2, o3)));
assertEquals(orderBy(o1, o2, o3, o4), orderBy(asList(o1, o2, o3, o4)));
assertEquals(orderBy(o1, o2, o3, o4, o5), orderBy(asList(o1, o2, o3, o4, o5)));
assertEquals(orderBy(o1, o2, o3, o4, o5), orderBy(new AttributeOrder[]{o1, o2, o3, o4, o5}));
}
@Test
@SuppressWarnings("unchecked")
public void testAndMethodOverloading() {
Query<Car> q1 = has(Car.CAR_ID);
Query<Car> q2 = has(Car.MANUFACTURER);
Query<Car> q3 = has(Car.MODEL);
Query<Car> q4 = has(Car.FEATURES);
Query<Car> q5 = has(Car.PRICE);
assertEquals(and(q1, q2), new And<Car>(asList(q1, q2)));
assertEquals(and(q1, q2, q3), new And<Car>(asList(q1, q2, q3)));
assertEquals(and(q1, q2, q3, q4), new And<Car>(asList(q1, q2, q3, q4)));
assertEquals(and(q1, q2, q3, q4, q5), new And<Car>(asList(q1, q2, q3, q4, q5)));
assertEquals(and(q1, q2, q3, q4, q5), and(q1, q2, new Query[]{q3, q4, q5}));
}
@Test
@SuppressWarnings("unchecked")
public void testOrMethodOverloading() {
Query<Car> q1 = has(Car.CAR_ID);
Query<Car> q2 = has(Car.MANUFACTURER);
Query<Car> q3 = has(Car.MODEL);
Query<Car> q4 = has(Car.FEATURES);
Query<Car> q5 = has(Car.PRICE);
assertEquals(or(q1, q2), new Or<Car>(asList(q1, q2)));
assertEquals(or(q1, q2, q3), new Or<Car>(asList(q1, q2, q3)));
assertEquals(or(q1, q2, q3, q4), new Or<Car>(asList(q1, q2, q3, q4)));
assertEquals(or(q1, q2, q3, q4, q5), new Or<Car>(asList(q1, q2, q3, q4, q5)));
assertEquals(or(q1, q2, q3, q4, q5), or(q1, q2, new Query[]{q3, q4, q5}));
}
@Test
public void testQueryOptionsMethodOverloading() {
QueryOptions queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), deduplicate(DeduplicationStrategy.MATERIALIZE));
assertEquals(orderBy(descending(Car.CAR_ID)), queryOptions.get(OrderByOption.class));
assertEquals(deduplicate(DeduplicationStrategy.MATERIALIZE), queryOptions.get(DeduplicationOption.class));
assertEquals(queryOptions(new Object[] {"foo", "bar"}), queryOptions("foo", "bar"));
}
@Test
public void testMatchesRegexMethodOverloading() {
assertEquals(matchesRegex(Car.MODEL, "F.*"), matchesRegex(Car.MODEL, Pattern.compile("F.*")));
}
@Test
public void testPredicate() {
Car redCar = CarFactory.createCar(1);
Car blueCar = CarFactory.createCar(7);
Predicate<Car> predicate = predicate(equal(Car.COLOR, Car.Color.BLUE));
assertFalse(predicate.test(redCar));
assertTrue(predicate.test(blueCar));
}
@Test
public void testConstructor() {
assertNotNull(new QueryFactory());
}
// ===== Tests for validateSimpleFunctionGenericTypes()... =====
@Test
public void testValidateSimpleFunctionGenericTypes_Success() {
Class<?>[] typeArgs = new Class<?>[] {Car.class, Integer.class};
validateSimpleFunctionGenericTypes(typeArgs, SimpleFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateSimpleFunctionGenericTypes_NullTypeArgs() {
validateSimpleFunctionGenericTypes(null, SimpleFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateSimpleFunctionGenericTypes_IncorrectNumberOfTypeArgs() {
Class<?>[] typeArgs = new Class<?>[] {Car.class, Integer.class, Integer.class};
validateSimpleFunctionGenericTypes(typeArgs, SimpleFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateSimpleFunctionGenericTypes_InvalidTypeArgs1() {
Class<?>[] typeArgs = new Class<?>[] {TypeResolver.Unknown.class, Integer.class};
validateSimpleFunctionGenericTypes(typeArgs, SimpleFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateSimpleFunctionGenericTypes_InvalidTypeArgs2() {
Class<?>[] typeArgs = new Class<?>[] {Car.class, TypeResolver.Unknown.class};
validateSimpleFunctionGenericTypes(typeArgs, SimpleFunction.class);
}
// ===== Tests for validateMultiValueFunctionGenericTypes()... =====
@Test
public void testValidateMultiValueFunctionGenericTypes_Success() {
Class<?>[] typeArgs = new Class<?>[] {Car.class, Integer.class, List.class};
validateMultiValueFunctionGenericTypes(typeArgs, MultiValueFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateMultiValueFunctionGenericTypes_NullTypeArgs() {
validateMultiValueFunctionGenericTypes(null, MultiValueFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateMultiValueFunctionGenericTypes_IncorrectNumberOfTypeArgs() {
Class<?>[] typeArgs = new Class<?>[] {Car.class, Integer.class};
validateMultiValueFunctionGenericTypes(typeArgs, MultiValueFunction.class);
}
@Test(expected = IllegalStateException.class)
public void testValidateMultiValueFunctionGenericTypes_InvalidTypeArgs() {
Class<?>[] typeArgs = new Class<?>[] {TypeResolver.Unknown.class, Integer.class, List.class};
validateMultiValueFunctionGenericTypes(typeArgs, MultiValueFunction.class);
}
}
| 7,529 | 41.303371 | 130 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/QueriesEqualsAndHashCodeTest.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.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.LogicalQuery;
import com.googlecode.cqengine.query.logical.Not;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.query.simple.*;
import com.googlecode.cqengine.testutil.Car;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Collections.singletonList;
/**
* @author Niall Gallagher
*/
@RunWith(DataProviderRunner.class)
public class QueriesEqualsAndHashCodeTest {
/**
* Returns Query classes whose equals() and hashCode() methods can be validated by EqualsVerifier in a uniform way.
*/
@DataProvider
public static List<List<Class>> getQueryClassesForAutomatedValidation() {
return Arrays.asList(
singletonList(Equal.class),
singletonList(In.class),
singletonList(Has.class),
singletonList(LessThan.class),
singletonList(GreaterThan.class),
singletonList(Between.class),
singletonList(StringStartsWith.class),
singletonList(StringEndsWith.class),
singletonList(StringContains.class),
singletonList(StringIsContainedIn.class),
singletonList(StringMatchesRegex.class),
singletonList(LongestPrefix.class),
singletonList(Min.class),
singletonList(Max.class)
);
}
/**
* Parameterized test which validates a Query class using EqualsVerifier.
*/
@Test
@UseDataProvider(value = "getQueryClassesForAutomatedValidation")
public void testQueryClass(Class<? extends Query> queryClass) {
EqualsVerifier.forClass(queryClass)
.withIgnoredFields("attributeIsSimple", "simpleAttribute")
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
@Test
public void testAnd() {
EqualsVerifier.forClass(And.class)
.withIgnoredFields("logicalQueries", "simpleQueries", "comparativeQueries", "hasLogicalQueries", "hasSimpleQueries", "hasComparativeQueries", "size")
.withPrefabValues(And.class, and(equal(Car.CAR_ID, 1), equal(Car.CAR_ID, 2)), and(equal(Car.CAR_ID, 3), equal(Car.CAR_ID, 4)))
.withPrefabValues(LogicalQuery.class, and(equal(Car.CAR_ID, 1), equal(Car.CAR_ID, 2)), and(equal(Car.CAR_ID, 3), equal(Car.CAR_ID, 4)))
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
@Test
public void testOr() {
EqualsVerifier.forClass(Or.class)
.withIgnoredFields("logicalQueries", "simpleQueries", "comparativeQueries", "hasLogicalQueries", "hasSimpleQueries", "hasComparativeQueries", "size")
.withPrefabValues(Or.class, or(equal(Car.CAR_ID, 1), equal(Car.CAR_ID, 2)), or(equal(Car.CAR_ID, 3), equal(Car.CAR_ID, 4)))
.withPrefabValues(LogicalQuery.class, or(equal(Car.CAR_ID, 1), equal(Car.CAR_ID, 2)), or(equal(Car.CAR_ID, 3), equal(Car.CAR_ID, 4)))
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
@Test
public void testNot() {
EqualsVerifier.forClass(Not.class)
.withIgnoredFields("logicalQueries", "childQueries", "simpleQueries", "comparativeQueries", "hasLogicalQueries", "hasSimpleQueries", "hasComparativeQueries", "size")
.withPrefabValues(Not.class, not(equal(Car.CAR_ID, 1)), not(equal(Car.CAR_ID, 2)))
.withPrefabValues(LogicalQuery.class, not(equal(Car.CAR_ID, 1)), not(equal(Car.CAR_ID, 2)))
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
@Test
public void testExistsIn() {
EqualsVerifier.forClass(ExistsIn.class)
.withIgnoredFields("attributeIsSimple", "simpleAttribute", "attribute")
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
/**
* Query class {@link All} has a non-standard hashCode implementation.
*/
@Test
public void testAll() {
Query<String> allStrings1 = QueryFactory.all(String.class);
Query<String> allStrings2 = QueryFactory.all(String.class);
Query<Integer> allIntegers1 = QueryFactory.all(Integer.class);
Query<Integer> allIntegers2 = QueryFactory.all(Integer.class);
Assert.assertEquals(allStrings1, allStrings1);
Assert.assertEquals(allStrings1, allStrings2);
Assert.assertEquals(allIntegers1, allIntegers1);
Assert.assertEquals(allIntegers1, allIntegers2);
Assert.assertNotEquals(allStrings1, allIntegers1);
// HashCode is a constant in All...
Assert.assertEquals(765906512, allStrings1.hashCode());
Assert.assertEquals(765906512, allStrings2.hashCode());
Assert.assertEquals(765906512, allIntegers1.hashCode());
Assert.assertEquals(765906512, allIntegers2.hashCode());
}
/**
* Query class {@link None} has a non-standard hashCode implementation.
*/
@Test
public void testNone() {
Query<String> noneStrings1 = QueryFactory.none(String.class);
Query<String> noneStrings2 = QueryFactory.none(String.class);
Query<Integer> noneIntegers1 = QueryFactory.none(Integer.class);
Query<Integer> noneIntegers2 = QueryFactory.none(Integer.class);
Assert.assertEquals(noneStrings1, noneStrings1);
Assert.assertEquals(noneStrings1, noneStrings2);
Assert.assertEquals(noneIntegers1, noneIntegers1);
Assert.assertEquals(noneIntegers1, noneIntegers2);
Assert.assertNotEquals(noneStrings1, noneIntegers1);
// HashCode is a constant in None...
Assert.assertEquals(1357656699, noneStrings1.hashCode());
Assert.assertEquals(1357656699, noneStrings2.hashCode());
Assert.assertEquals(1357656699, noneIntegers1.hashCode());
Assert.assertEquals(1357656699, noneIntegers2.hashCode());
}
}
| 7,946 | 44.672414 | 181 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/QueryToStringTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.join.Garage;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Assert;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* @author ngallagher
* @since 2013-08-27 12:09
*/
public class QueryToStringTest {
@Test
public void testQueryToString1() {
Query<Car> query = and(
equal(Car.MANUFACTURER, "Toyota"),
equal(Car.COLOR, Car.Color.BLUE),
equal(Car.DOORS, 3)
);
Assert.assertEquals(
"and(" +
"equal(\"manufacturer\", \"Toyota\"), " +
"equal(\"color\", BLUE), " +
"equal(\"doors\", 3)" +
")",
query.toString()
);
}
@Test
public void testQueryToString2() {
IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
Query<Car> query = and(
in(Car.DOORS, 2, 4),
existsIn(garages,
Car.MANUFACTURER,
Garage.BRANDS_SERVICED,
equal(Garage.LOCATION, "Dublin")
)
);
// Note: QueryFactory expands 'in' queries to an 'or' of multiple 'equals' queries (logically equivalent)...
Assert.assertEquals(
"and(" +
"in(\"doors\", [2, 4]), " +
"existsIn(IndexedCollection<Garage>, " +
"\"manufacturer\", " +
"\"brandsServiced\", " +
"equal(\"location\", \"Dublin\")" +
")" +
")",
query.toString()
);
}
}
| 2,513 | 32.52 | 116 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/QueryOptionsTest.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 nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class QueryOptionsTest {
@Test
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(QueryOptions.class)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.verify();
}
} | 1,005 | 33.689655 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/OrderByOptionTest.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 nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class OrderByOptionTest {
@Test
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(OrderByOption.class)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.verify();
}
} | 1,007 | 33.758621 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/FlagsDisabledTest.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 org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.queryOptions;
import static com.googlecode.cqengine.query.QueryFactory.disableFlags;
import static com.googlecode.cqengine.query.option.FlagsDisabled.isFlagDisabled;
import static org.junit.Assert.*;
/**
* @author niall.gallagher
*/
public class FlagsDisabledTest {
@Test
public void testFlagsDisabled() {
QueryOptions queryOptions = queryOptions(disableFlags("a", "b"));
assertTrue(isFlagDisabled(queryOptions, "a"));
assertTrue(isFlagDisabled(queryOptions, "b"));
assertFalse(isFlagDisabled(queryOptions, "c"));
}
} | 1,297 | 34.081081 | 80 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/AttributeOrderTest.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 nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class AttributeOrderTest {
@Test
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(AttributeOrder.class)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.verify();
}
} | 1,011 | 31.645161 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/DeduplicationOptionTest.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 nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class DeduplicationOptionTest {
@Test
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(DeduplicationOption.class)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
.verify();
}
} | 1,019 | 34.172414 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/option/FlagsEnabledTest.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 org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.queryOptions;
import static com.googlecode.cqengine.query.QueryFactory.enableFlags;
import static com.googlecode.cqengine.query.option.FlagsEnabled.isFlagEnabled;
import static org.junit.Assert.*;
/**
* @author niall.gallagher
*/
public class FlagsEnabledTest {
@Test
public void testFlagsEnabled() {
QueryOptions queryOptions = queryOptions(enableFlags("a", "b"));
assertTrue(isFlagEnabled(queryOptions, "a"));
assertTrue(isFlagEnabled(queryOptions, "b"));
assertFalse(isFlagEnabled(queryOptions, "c"));
}
} | 1,288 | 33.837838 | 78 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/comparative/LongestPrefixTest.java | package com.googlecode.cqengine.query.comparative;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.radixinverted.InvertedRadixTreeIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.MobileTerminating;
import com.googlecode.cqengine.testutil.MobileTerminatingFactory;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SelfAttribute;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Iterator;
/**
* Unit tests for {@link LongestPrefix} query.
* <p>
* This class contains regular unit tests, AND parameterized tests for the longest prefix matching.
* <p>
* These tests are based on a use case of finding the longest matching mobile phone number, which is a more
* typical use case for prefix matching than the car examples used in other tests.
* <p>
* These tests and the support for the {@link LongestPrefix} query, were contributed by Glen Lockhart of Openet-Labs.
*/
@RunWith(DataProviderRunner.class)
public class LongestPrefixTest {
private static IndexedCollection<MobileTerminating> mobileTerminatingCache;
private static IndexedCollection<MobileTerminating> mobileTerminatingCacheNoIndex;
@DataProvider
public static Object[][] mobileTerminatingScenarios() {
return new Object[][] {
{"35380", "op1", 1},
{"35380123", "op1", 1},
{"3538123", "op2", 1},
{"35382", "op3", 1},
{"353822", "op4", 1},
{"35387", "op5", 1},
{"3538712345", "op6", 1},
{"44123", "op7", 1},
{"4480", "op8,op9", 2},
{"33380", "op10", 1},
{"33381", "op11", 1},
{"1234", "op12", 1},
{"111", "op13", 1},
{"777", "", 0},
{"353", "na", 1},
{"354", "", 0},
};
}
@BeforeClass
public static void setupMTCache() {
mobileTerminatingCache = new ConcurrentIndexedCollection<MobileTerminating>();
mobileTerminatingCache.addIndex(InvertedRadixTreeIndex.onAttribute(MobileTerminating.PREFIX));
mobileTerminatingCache.addAll(MobileTerminatingFactory.getCollectionOfMobileTerminating());
mobileTerminatingCacheNoIndex = new ConcurrentIndexedCollection<MobileTerminating>();
mobileTerminatingCacheNoIndex.addAll(MobileTerminatingFactory.getCollectionOfMobileTerminating());
}
@Test
@UseDataProvider(value = "mobileTerminatingScenarios")
public void testLongestPrefix(String prefix, String expectedOperator, Integer expectedCount) {
Query<MobileTerminating> q = longestPrefix(MobileTerminating.PREFIX, prefix);
validateLongestPrefixWithCache(q, mobileTerminatingCache, expectedOperator, expectedCount);
}
@Test
@UseDataProvider(value = "mobileTerminatingScenarios")
public void testLongestPrefixWithoutIndex(String prefix, String expectedOperator, Integer expectedCount) {
Query<MobileTerminating> q = longestPrefix(MobileTerminating.PREFIX, prefix);
validateLongestPrefixWithCache(q, mobileTerminatingCacheNoIndex, expectedOperator, expectedCount);
}
public void validateLongestPrefixWithCache(Query<MobileTerminating> q, IndexedCollection<MobileTerminating> cache, String expectedOperator, Integer expectedCount) {
ResultSet<MobileTerminating> res = cache.retrieve(q, queryOptions(orderBy(ascending(MobileTerminating.OPERATOR_NAME))));
assertEquals(expectedCount, (Integer)res.size());
Iterator<String> expectedOperators = Arrays.asList(expectedOperator.split(",")).iterator();
for (MobileTerminating mt : res) {
assertEquals(expectedOperators.next(), mt.getOperatorName());
}
}
@Test
public void testLongestPrefix() {
Attribute<String, String> stringIdentity = new SelfAttribute<String>(String.class, "identity");
assertTrue(LongestPrefix.countPrefixChars( "35387123456", "35387") > 0);
assertEquals(5, LongestPrefix.countPrefixChars( "35387123456", "35387"));
assertTrue(LongestPrefix.countPrefixChars("35387", "35387") > 0);
assertEquals(5, LongestPrefix.countPrefixChars("35387", "35387"));
assertFalse(LongestPrefix.countPrefixChars("35386123456", "35387") > 0);
assertEquals(0, LongestPrefix.countPrefixChars("35386123456", "35387"));
assertFalse(LongestPrefix.countPrefixChars("35386123456", "35387") > 0);
assertEquals(0, LongestPrefix.countPrefixChars("35386123456", "35387"));
assertFalse(LongestPrefix.countPrefixChars("3538", "35387") > 0);
assertEquals(0, LongestPrefix.countPrefixChars("3538", "35387"));
}
@Test
public void testConstructor_ArgumentValidation() {
{
IllegalArgumentException expectedIAE = null;
try {
new LongestPrefix<>(null, "");
} catch (IllegalArgumentException e) {
expectedIAE = e;
}
assertNotNull(expectedIAE);
}
{
NullPointerException expectedNPE = null;
try {
new LongestPrefix<>(QueryFactory.selfAttribute(String.class), null);
} catch (NullPointerException e) {
expectedNPE = e;
}
assertNotNull(expectedNPE);
}
}
@Test
public void testGetAttributeType() {
Class<String> attributeType = new LongestPrefix<>(selfAttribute(String.class), "").getAttributeType();
assertEquals(String.class, attributeType);
}
}
| 6,478 | 43.07483 | 168 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/StringEndsWithTest.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 org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.endsWith;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Niall Gallagher
*/
public class StringEndsWithTest {
@Test
public void testStringEndsWith() {
Attribute<String, String> stringIdentity = new SelfAttribute<String>(String.class, "identity");
assertTrue(endsWith(stringIdentity, "TEST").matches("THIS IS A TEST", noQueryOptions()));
assertFalse(endsWith(stringIdentity, "THIS").matches("THIS IS A TEST", noQueryOptions()));
assertFalse(endsWith(stringIdentity, "TES").matches("THIS IS A TEST", noQueryOptions()));
assertTrue(endsWith(stringIdentity, "").matches("THIS IS A TEST", noQueryOptions()));
assertTrue(endsWith(stringIdentity, "").matches("", noQueryOptions()));
assertFalse(endsWith(stringIdentity, "TEST").matches("", noQueryOptions()));
}
}
| 1,797 | 39.863636 | 103 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/InTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.in;
/**
* @author Kevin Minder
* @author Niall Gallagher
*/
public class InTest {
@Test
public void testInMany() {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) {
return car.name;
}
};
cars.addIndex(NavigableIndex.onAttribute(NAME));
// Add some objects to the collection...
cars.add(new Car(1, "ford", null, null));
cars.add(new Car(2, "honda", null, null));
cars.add(new Car(3, "toyota", null, null));
Assert.assertEquals(cars.retrieve(in(NAME, "ford", "honda")).size(), 2);
Assert.assertEquals(cars.retrieve(in(NAME, Arrays.asList("ford", "honda"))).size(), 2);
}
@Test
public void testInOne() {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) {
return car.name;
}
};
cars.addIndex(NavigableIndex.onAttribute(NAME));
// Add some objects to the collection...
cars.add(new Car(1, "ford", null, null));
cars.add(new Car(2, "honda", null, null));
cars.add(new Car(3, "toyota", null, null));
Assert.assertEquals(cars.retrieve(in(NAME, "ford")).size(), 1);
Assert.assertEquals(cars.retrieve(in(NAME, Collections.singletonList("ford"))).size(), 1);
}
@Test
public void testInNone() {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) {
return car.name;
}
};
cars.addIndex(NavigableIndex.onAttribute(NAME));
// Add some objects to the collection...
cars.add(new Car(1, "ford", null, null));
cars.add(new Car(2, "honda", null, null));
cars.add(new Car(3, "toyota", null, null));
Assert.assertEquals(cars.retrieve(in(NAME)).size(), 0);
Assert.assertEquals(cars.retrieve(in(NAME, new ArrayList<String>())).size(), 0);
}
@Test(expected = NullPointerException.class)
public void testInNull() {
Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) {
return car.name;
}
};
in(NAME, (Collection<String>) null);
}
}
| 4,294 | 37.693694 | 114 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/StringIsPrefixOfTest.java | package com.googlecode.cqengine.query.simple;
import static com.googlecode.cqengine.query.QueryFactory.isPrefixOf;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SelfAttribute;
public class StringIsPrefixOfTest {
Attribute<String, String> stringIdentity = new SelfAttribute<String>(String.class, "identity");
@Test
public void testMatchesSimpleAttribute() throws Exception {
assertTrue(isPrefixOf(stringIdentity, "FOO").matches("F", noQueryOptions()));
assertTrue(isPrefixOf(stringIdentity, "FOO").matches("FO", noQueryOptions()));
assertTrue(isPrefixOf(stringIdentity, "FOO").matches("FOO", noQueryOptions()));
assertFalse(isPrefixOf(stringIdentity, "FOO").matches("OO", noQueryOptions()));
assertFalse(isPrefixOf(stringIdentity, "FOO").matches("BOO", noQueryOptions()));
assertFalse(isPrefixOf(stringIdentity, "FOO").matches("FOOOD", noQueryOptions()));
}
@Test
public void testGetValue() throws Exception {
StringIsPrefixOf<String, String> query = new StringIsPrefixOf<>(stringIdentity, "FOO");
assertEquals("FOO", query.getValue());
}
}
| 1,452 | 35.325 | 99 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/StringContainsTest.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 org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Niall Gallagher
*/
public class StringContainsTest {
@Test
public void testStringContains() {
assertTrue(StringContains.containsFragment("THIS IS A TEST", "THIS"));
assertTrue(StringContains.containsFragment("THIS IS A TEST", "TEST"));
assertTrue(StringContains.containsFragment("THIS IS A TEST", "IS A"));
assertFalse(StringContains.containsFragment("THIS IS A TEST", "FOO"));
assertTrue(StringContains.containsFragment("THIS IS A TEST", ""));
assertTrue(StringContains.containsFragment("", ""));
assertFalse(StringContains.containsFragment("", "TEST"));
}
}
| 1,354 | 35.621622 | 78 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/StringStartsWithTest.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 org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.query.QueryFactory.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Niall Gallagher
*/
public class StringStartsWithTest {
@Test
public void testStringStartsWith() {
Attribute<String, String> stringIdentity = new SelfAttribute<String>(String.class, "identity");
assertTrue(startsWith(stringIdentity, "THIS").matches("THIS IS A TEST", noQueryOptions()));
assertFalse(startsWith(stringIdentity, "TEST").matches("THIS IS A TEST", noQueryOptions()));
assertFalse(startsWith(stringIdentity, "HIS").matches("THIS IS A TEST", noQueryOptions()));
assertTrue(startsWith(stringIdentity, "").matches("THIS IS A TEST", noQueryOptions()));
assertTrue(startsWith(stringIdentity, "").matches("", noQueryOptions()));
assertFalse(startsWith(stringIdentity, "TEST").matches("", noQueryOptions()));
}
}
| 1,815 | 40.272727 | 103 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/NoneTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.resultset.ResultSet;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
public class NoneTest {
@Test
public void testNone() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
Query<Integer> query = none(Integer.class);
ResultSet<Integer> results = collection.retrieve(query);
assertEquals(0, results.size());
assertFalse(results.iterator().hasNext());
}
@Test
public void testNoneAnd() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
final And<Integer> query = and(
none(Integer.class),
lessThan(selfAttribute(Integer.class), 3)
);
ResultSet<Integer> results = collection.retrieve(query);
assertEquals(0, results.size());
assertFalse(results.iterator().hasNext());
}
@Test
public void testNoneOr() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
final Or<Integer> query = or(
none(Integer.class),
lessThan(selfAttribute(Integer.class), 3)
);
ResultSet<Integer> results = collection.retrieve(query);
assertEquals(2, results.size());
assertTrue(results.iterator().hasNext());
}
} | 2,764 | 37.943662 | 98 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/StringMatchesRegexTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class StringMatchesRegexTest {
@Test
public void testStringMatchesRegex() {
Query<String> query = matchesRegex(selfAttribute(String.class), "f.*");
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(asList("foo1", "foo2", "bar", "baz", "car"));
IndexedCollection<String> collection = indexedCollection;
ResultSet<String> results = collection.retrieve(query);
assertEquals(2, results.size());
assertTrue(results.iterator().hasNext());
}
@Test
public void testStringMatchesRegexWithIndex() {
Query<String> query = matchesRegex(selfAttribute(String.class), "f.*");
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(asList("foo1", "foo2", "bar", "baz", "car"));
IndexedCollection<String> collection = indexedCollection;
collection.addIndex(StandingQueryIndex.onQuery(query));
ResultSet<String> results = collection.retrieve(query);
assertEquals(2, results.size());
assertTrue(results.iterator().hasNext());
}
@Test
public void testStringMatchesRegexNegatedWithIndex() {
Query<String> query = not(matchesRegex(selfAttribute(String.class), "[fb].*"));
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(asList("foo1", "foo2", "bar", "baz", "car"));
IndexedCollection<String> collection = indexedCollection;
collection.addIndex(StandingQueryIndex.onQuery(query));
ResultSet<String> results = collection.retrieve(query);
assertEquals(1, results.size());
assertTrue(results.iterator().hasNext());
}
} | 2,942 | 43.590909 | 96 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/AllTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.logical.And;
import com.googlecode.cqengine.query.logical.Or;
import com.googlecode.cqengine.resultset.ResultSet;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.QueryFactory.lessThan;
import static com.googlecode.cqengine.query.QueryFactory.all;
import static com.googlecode.cqengine.query.option.DeduplicationStrategy.LOGICAL_ELIMINATION;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class AllTest {
@Test
public void testAll() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
Query<Integer> query = all(Integer.class);
ResultSet<Integer> results = collection.retrieve(query);
assertEquals(5, results.size());
assertTrue(results.iterator().hasNext());
}
@Test
public void testAllAnd() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
final And<Integer> query = and(
all(Integer.class),
lessThan(selfAttribute(Integer.class), 3)
);
ResultSet<Integer> results = collection.retrieve(query);
assertEquals(2, results.size());
assertTrue(results.iterator().hasNext());
}
@Test
public void testAllOr() {
IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
indexedCollection.addAll(asList(1, 2, 3, 4, 5));
IndexedCollection<Integer> collection = indexedCollection;
final Or<Integer> query = or(
all(Integer.class),
lessThan(selfAttribute(Integer.class), 3)
);
ResultSet<Integer> results = collection.retrieve(query, queryOptions(deduplicate(LOGICAL_ELIMINATION)));
assertEquals(5, results.size());
assertTrue(results.iterator().hasNext());
}
} | 3,070 | 40.5 | 112 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/ExistsInTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.examples.join.Garage;
import com.googlecode.cqengine.query.Query;
import org.junit.Assert;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.existsIn;
public class ExistsInTest {
@Test
public void testToString1() throws Exception {
IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
Query<Car> existsIn = existsIn(garages, Car.NAME, Garage.BRANDS_SERVICED);
Assert.assertEquals("existsIn(IndexedCollection<Garage>, \"name\", \"brandsServiced\")", existsIn.toString());
}
@Test
public void testToString2() throws Exception {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
Query<Car> existsIn = existsIn(garages, Car.NAME, Garage.BRANDS_SERVICED, equal(Garage.LOCATION, "Dublin"));
Assert.assertEquals("existsIn(IndexedCollection<Garage>, \"name\", \"brandsServiced\", equal(\"location\", \"Dublin\"))", existsIn.toString());
}
} | 1,987 | 41.297872 | 151 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/simple/HasTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.index.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.junit.Assert;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
import java.util.Arrays;
/**
* @author Niall Gallagher
*/
public class HasTest {
@Test
public void testExists() {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) { return car.name; }
};
// Add some indexes...
cars.addIndex(StandingQueryIndex.onQuery(has(NAME)));
cars.addIndex(StandingQueryIndex.onQuery(not(has(NAME))));
// Add some objects to the collection...
cars.add(new Car(1, "ford focus", "great condition, low mileage", Arrays.asList("spare tyre", "sunroof")));
cars.add(new Car(2, null, "dirty and unreliable, flat tyre", Arrays.asList("spare tyre", "radio")));
cars.add(new Car(3, "honda civic", "has a flat tyre and high mileage", Arrays.asList("radio")));
Assert.assertEquals(cars.retrieve(has(NAME)).size(), 2);
Assert.assertEquals(cars.retrieve(not(has(NAME))).size(), 1);
}
}
| 2,371 | 40.614035 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/parser/cqn/CQNParserTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.parser.common.InvalidQueryException;
import com.googlecode.cqengine.query.parser.common.ParseResult;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import com.googlecode.cqengine.testutil.MobileTerminating;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import static com.googlecode.cqengine.IndexedCollectionFunctionalTest.asSet;
import static com.googlecode.cqengine.IndexedCollectionFunctionalTest.extractCarIds;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
/**
* @author Niall Gallagher
*/
public class CQNParserTest {
final CQNParser<Car> parser = new CQNParser<Car>(Car.class){{
registerAttribute(Car.CAR_ID);
registerAttribute(Car.MANUFACTURER);
registerAttribute(Car.MODEL);
registerAttribute(Car.COLOR);
registerAttribute(Car.DOORS);
registerAttribute(Car.PRICE);
registerAttribute(Car.FEATURES);
}};
final CQNParser<MobileTerminating> mtParser = new CQNParser<MobileTerminating>(MobileTerminating.class) {{
registerAttribute(MobileTerminating.PREFIX);
registerAttribute(MobileTerminating.OPERATOR_NAME);
registerAttribute(MobileTerminating.REGION);
registerAttribute(MobileTerminating.ZONE);
}};
@Test
public void testValidQueries() {
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parser.query("equal(\"manufacturer\", \"Ford\")"));
assertQueriesEquals(lessThanOrEqualTo(Car.PRICE, 1000.0), parser.query("lessThanOrEqualTo(\"price\", 1000.0)"));
assertQueriesEquals(lessThan(Car.PRICE, 1000.0), parser.query("lessThan(\"price\", 1000.0)"));
assertQueriesEquals(greaterThanOrEqualTo(Car.PRICE, 1000.0), parser.query("greaterThanOrEqualTo(\"price\", 1000.0)"));
assertQueriesEquals(greaterThan(Car.PRICE, 1000.0), parser.query("greaterThan(\"price\", 1000.0)"));
assertQueriesEquals(between(Car.PRICE, 1000.0, 2000.0), parser.query("between(\"price\", 1000.0, 2000.0)"));
assertQueriesEquals(between(Car.PRICE, 1000.0, false, 2000.0, true), parser.query("between(\"price\", 1000.0, false, 2000.0, true)"));
assertQueriesEquals(in(Car.MANUFACTURER, "Ford", "Honda"), parser.query("in(\"manufacturer\", \"Ford\", \"Honda\")"));
assertQueriesEquals(startsWith(Car.MODEL, "Fo"), parser.query("startsWith(\"model\", \"Fo\")"));
assertQueriesEquals(endsWith(Car.MODEL, "rd"), parser.query("endsWith(\"model\", \"rd\")"));
assertQueriesEquals(contains(Car.MODEL, "or"), parser.query("contains(\"model\", \"or\")"));
assertQueriesEquals(isContainedIn(Car.MODEL, "a b c"), parser.query("isContainedIn(\"model\", \"a b c\")"));
assertQueriesEquals(matchesRegex(Car.MODEL, "Fo.*"), parser.query("matchesRegex(\"model\", \"Fo.*\")"));
assertQueriesEquals(has(Car.FEATURES), parser.query("has(\"features\")"));
assertQueriesEquals(all(Car.class), parser.query("all(Car.class)"));
assertQueriesEquals(none(Car.class), parser.query("none(Car.class)"));
assertQueriesEquals(and(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Focus")), parser.query("and(equal(\"manufacturer\", \"Ford\"), equal(\"model\", \"Focus\"))"));
assertQueriesEquals(or(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Focus")), parser.query("or(equal(\"manufacturer\", \"Ford\"), equal(\"model\", \"Focus\"))"));
assertQueriesEquals(not(equal(Car.MANUFACTURER, "Ford")), parser.query("not(equal(\"manufacturer\", \"Ford\"))"));
assertQueriesEquals(equal(Car.CAR_ID, -1), parser.query("equal(\"carId\", -1)"));
assertQueriesEquals(equal(Car.PRICE, -1.5), parser.query("equal(\"price\", -1.5)"));
assertQueriesEquals(isPrefixOf(Car.MANUFACTURER, "Ford"), parser.query("isPrefixOf(\"manufacturer\", \"Ford\")"));
assertQueriesEquals(longestPrefix(MobileTerminating.PREFIX, "12345"), mtParser.query("longestPrefix(\"prefix\", \"12345\")"));
assertQueriesEquals(
or(
and( // Cars less than 5K which have at least 4 doors
lessThan(Car.PRICE, 5000.0),
greaterThanOrEqualTo(Car.DOORS, 4)
),
and( // OR cars less than 8K which have at least 4 doors and are a hybrid, but are not blue or green
lessThan(Car.PRICE, 8000.0),
greaterThanOrEqualTo(Car.DOORS, 4),
equal(Car.FEATURES, "hybrid"),
not(in(Car.COLOR, Car.Color.BLUE, Car.Color.GREEN))
)
),
parser.query(
"or(" +
"and(" +
"lessThan(\"price\", 5000.0), " +
"greaterThanOrEqualTo(\"doors\", 4)" +
"), " +
"and(" +
"lessThan(\"price\", 8000.0), " +
"greaterThanOrEqualTo(\"doors\", 4), " +
"equal(\"features\", \"hybrid\"), " +
"not(in(\"color\", BLUE, GREEN))" +
")" +
")"
)
);
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_DuplicateQueries() {
parser.query("all(Car.class)all(Car.class)");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_TrailingGibberish() {
parser.query("all(Car.class)abc");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_LeadingGibberish() {
parser.query("abc all(Car.class)");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_UnclosedQuery() {
parser.query("all(Car.class");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_InvalidParameters1() {
parser.query("equal(\"manufacturer\", x, \"Ford\")");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_InvalidParameters2() {
parser.query("equal(\"manufacturer\", 1, \"Ford\")");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_InvalidParameterType() {
parser.query("equal(\"doors\", \"foo\")");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_NullQuery() {
parser.query(null);
}
@Test
public void testOrderBy_NoOrdering() {
ParseResult<Car> parseResult = parser.parse("equal(\"manufacturer\", \"Ford\")");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(noQueryOptions(), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_SimpleOrdering() {
ParseResult<Car> parseResult = parser.parse("equal(\"manufacturer\", \"Ford\"), queryOptions(orderBy(ascending(\"manufacturer\")))");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER))), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_ComplexOrdering() {
ParseResult<Car> parseResult = parser.parse("equal(\"manufacturer\", \"Ford\"), queryOptions(orderBy(ascending(\"manufacturer\"), descending(\"carId\")))");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.CAR_ID))), parseResult.getQueryOptions());
}
static <T> void assertQueriesEquals(Query<T> expected, Query<T> actual) {
Assert.assertEquals(expected, actual);
Assert.assertEquals(expected.toString(), actual.toString());
}
@Test
public void testRetrieve() {
// CQN syntax does not yet support ordering, so here we just test parsing a query without ordering...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(10));
ResultSet<Car> results = parser.retrieve(cars, "and(equal(\"manufacturer\", \"Honda\"), not(equal(\"color\", \"WHITE\")))");
Assert.assertEquals(2, results.size());
Assert.assertEquals(asSet(5, 4), extractCarIds(results, new HashSet<Integer>()));
}
}
| 9,646 | 48.219388 | 178 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/parser/cqn/CQNDateMathTest.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.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.parser.cqn.support.DateMathParser;
import com.googlecode.cqengine.resultset.ResultSet;
import org.junit.Assert;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.googlecode.cqengine.codegen.AttributeBytecodeGenerator.createAttributes;
/**
* @author niall.gallagher
*/
public class CQNDateMathTest {
@Test
public void testDateMath() {
// Create a collection of Order objects, with shipDates 2015-08-01, 2015-08-02 and 2015-08-03...
IndexedCollection<Order> collection = new ConcurrentIndexedCollection<Order>();
collection.add(createOrder("2015-08-01"));
collection.add(createOrder("2015-08-02"));
collection.add(createOrder("2015-08-03"));
// Create a parser for CQN queries on Order objects...
CQNParser<Order> parser = CQNParser.forPojoWithAttributes(Order.class, createAttributes(Order.class));
// Register a DateMathParser which can parse date math expressions
// relative to the given date value for "now" ("2015-08-04").
// The custom value for "now" can be omitted to have it always calculate relative to the current time...
parser.registerValueParser(Date.class, new DateMathParser(createDate("2015-08-04")));
// Retrieve orders whose ship date is between 3 days ago and 2 days ago...
ResultSet<Order> results = parser.retrieve(collection, "between(\"shipDate\", \"-3DAYS\", \"-2DAYS\")");
// Assert that the following two orders are returned...
Assert.assertTrue(results.contains(createOrder("2015-08-01")));
Assert.assertTrue(results.contains(createOrder("2015-08-02")));
Assert.assertEquals(2, results.size());
}
/* The Order POJO */
static class Order {
final Date shipDate;
public Order(Date shipDate) {
this.shipDate = shipDate;
}
@Override
public String toString() {
return "Order{" +
"shipDate=" + shipDate +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Order)) {
return false;
}
Order order = (Order) o;
return shipDate.equals(order.shipDate);
}
@Override
public int hashCode() {
return shipDate.hashCode();
}
}
static Order createOrder(String date) {
return new Order(createDate(date));
}
static Date createDate(String date) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.parse(date);
}
catch (Exception e) {
throw new IllegalStateException("Failed to parse date: " + date);
}
}
}
| 3,695 | 33.542056 | 112 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/parser/sql/SQLParserTest.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.sql;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
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.query.parser.common.InvalidQueryException;
import com.googlecode.cqengine.query.parser.common.ParseResult;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import static com.googlecode.cqengine.IndexedCollectionFunctionalTest.extractCarIds;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
public class SQLParserTest {
static final Attribute<Car, Boolean> IS_BLUE = new SimpleAttribute<Car, Boolean>("is_blue") {
@Override
public Boolean getValue(Car object, QueryOptions queryOptions) {
return object.getColor().equals(Car.Color.BLUE);
}
};
final SQLParser<Car> parser = new SQLParser<Car>(Car.class){{
registerAttribute(Car.CAR_ID);
registerAttribute(Car.MANUFACTURER);
registerAttribute(Car.MODEL);
registerAttribute(Car.COLOR);
registerAttribute(Car.DOORS);
registerAttribute(Car.PRICE);
registerAttribute(Car.FEATURES);
registerAttribute(IS_BLUE);
}};
@Test
public void testValidQueries() {
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parser.query("SELECT * FROM cars WHERE 'manufacturer' = 'Ford'"));
assertQueriesEquals(lessThanOrEqualTo(Car.PRICE, 1000.0), parser.query("SELECT * FROM cars WHERE 'price' <= 1000.0"));
assertQueriesEquals(lessThan(Car.PRICE, 1000.0), parser.query("SELECT * FROM cars WHERE 'price' < 1000.0"));
assertQueriesEquals(greaterThanOrEqualTo(Car.PRICE, 1000.0), parser.query("SELECT * FROM cars WHERE 'price' >= 1000.0"));
assertQueriesEquals(greaterThan(Car.PRICE, 1000.0), parser.query("SELECT * FROM cars WHERE 'price' > 1000.0"));
assertQueriesEquals(between(Car.PRICE, 1000.0, 2000.0), parser.query("SELECT * FROM cars WHERE 'price' BETWEEN 1000.0 AND 2000.0"));
assertQueriesEquals(not(between(Car.PRICE, 1000.0, 2000.0)), parser.query("SELECT * FROM cars WHERE 'price' NOT BETWEEN 1000.0 AND 2000.0"));
assertQueriesEquals(in(Car.MANUFACTURER, "Ford", "Honda"), parser.query("SELECT * FROM cars WHERE 'manufacturer' IN ('Ford', 'Honda')"));
assertQueriesEquals(not(in(Car.MANUFACTURER, "Ford", "Honda")), parser.query("SELECT * FROM cars WHERE 'manufacturer' NOT IN ('Ford', 'Honda')"));
assertQueriesEquals(startsWith(Car.MODEL, "Fo"), parser.query("SELECT * FROM cars WHERE 'model' LIKE 'Fo%'"));
assertQueriesEquals(endsWith(Car.MODEL, "rd"), parser.query("SELECT * FROM cars WHERE 'model' LIKE '%rd'"));
assertQueriesEquals(contains(Car.MODEL, "or"), parser.query("SELECT * FROM cars WHERE 'model' LIKE '%or%'"));
assertQueriesEquals(has(Car.FEATURES), parser.query("SELECT * FROM cars WHERE 'features' IS NOT NULL"));
assertQueriesEquals(all(Car.class), parser.query("SELECT * FROM cars"));
assertQueriesEquals(and(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Focus")), parser.query("SELECT * FROM cars WHERE ('manufacturer' = 'Ford' AND 'model' = 'Focus')"));
assertQueriesEquals(or(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Focus")), parser.query("SELECT * FROM cars WHERE ('manufacturer' = 'Ford' OR 'model' = 'Focus')"));
assertQueriesEquals(not(equal(Car.MANUFACTURER, "Ford")), parser.query("SELECT * FROM cars WHERE 'manufacturer' <> 'Ford'"));
assertQueriesEquals(not(equal(Car.MANUFACTURER, "Ford")), parser.query("SELECT * FROM cars WHERE NOT ('manufacturer' = 'Ford')"));
assertQueriesEquals(not(equal(Car.MANUFACTURER, "Ford")), parser.query("SELECT * FROM cars WHERE (NOT ('manufacturer' = 'Ford'))"));
assertQueriesEquals(equal(IS_BLUE, true), parser.query("SELECT * FROM cars WHERE (is_blue = true)"));
assertQueriesEquals(equal(IS_BLUE, false), parser.query("SELECT * FROM cars WHERE (is_blue = false)"));
assertQueriesEquals(equal(Car.DOORS, 3), parser.query("SELECT * FROM cars WHERE 'doors' = 3"));
assertQueriesEquals(equal(Car.DOORS, 3), parser.query("SELECT * FROM cars WHERE 'doors' = +3"));
assertQueriesEquals(equal(Car.DOORS, -3), parser.query("SELECT * FROM cars WHERE 'doors' = -3"));
assertQueriesEquals(equal(Car.PRICE, 3.0), parser.query("SELECT * FROM cars WHERE 'price' = 3"));
assertQueriesEquals(equal(Car.PRICE, -3.0), parser.query("SELECT * FROM cars WHERE 'price' = -3"));
assertQueriesEquals(equal(Car.PRICE, 3.1), parser.query("SELECT * FROM cars WHERE 'price' = 3.1"));
assertQueriesEquals(equal(Car.PRICE, 3.1), parser.query("SELECT * FROM cars WHERE 'price' = +3.1"));
assertQueriesEquals(equal(Car.PRICE, -3.1), parser.query("SELECT * FROM cars WHERE 'price' = -3.1"));
assertQueriesEquals(equal(Car.MODEL, "Sam's car"), parser.query("SELECT * FROM cars WHERE 'model' = 'Sam''s car'"));
assertQueriesEquals(isPrefixOf(Car.MANUFACTURER, "Ford"), parser.query("SELECT * from cars WHERE 'Ford' LIKE manufacturer || '%'"));
assertQueriesEquals(
or(
and( // Cars less than 5K which have at least 4 doors
lessThan(Car.PRICE, 5000.0),
greaterThanOrEqualTo(Car.DOORS, 4)
),
and( // OR cars less than 8K which have at least 4 doors and are a hybrid, but are not blue or green
lessThan(Car.PRICE, 8000.0),
greaterThanOrEqualTo(Car.DOORS, 4),
equal(Car.FEATURES, "hybrid"),
not(in(Car.COLOR, Car.Color.BLUE, Car.Color.GREEN))
)
),
parser.query(
"SELECT * FROM cars WHERE " +
"(" +
"(" +
"'price' < 5000.0" +
" AND " +
"'doors' >= 4" +
")" +
" OR " +
"(" +
"'price' < 8000.0" +
" AND " +
"'doors' >= 4" +
" AND " +
"'features' = 'hybrid'" +
" AND " +
"'color' NOT IN ('BLUE', 'GREEN')" +
")" +
")"
)
);
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_DuplicateQueries() {
parser.query("SELECT * FROM cars WHERE 'price' < 1000.0 SELECT * FROM cars WHERE 'price' < 1000.0");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_TrailingGibberish() {
parser.query("SELECT * FROM cars WHERE 'price' < 1000.0 abc");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_LeadingGibberish() {
parser.query("abc SELECT * FROM cars WHERE 'price' < 1000.0");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_UnclosedQuery() {
parser.query("SELECT * FROM cars WHERE 'price' < 1000.0 AND ");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_InvalidParameterType() {
parser.query("SELECT * FROM cars WHERE 'doors' = 'foo'");
}
@Test(expected = InvalidQueryException.class)
public void testInvalidQuery_NullQuery() {
parser.query(null);
}
static void assertQueriesEquals(Query<Car> expected, Query<Car> actual) {
Assert.assertEquals(expected, actual);
Assert.assertEquals(expected.toString(), actual.toString());
}
@Test
public void testOrderBy_NoOrdering() {
ParseResult<Car> parseResult = parser.parse("SELECT * FROM cars WHERE 'manufacturer' = 'Ford'");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(noQueryOptions(), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_SimpleOrdering1() {
ParseResult<Car> parseResult = parser.parse("SELECT * FROM cars WHERE 'manufacturer' = 'Ford' ORDER BY manufacturer ASC");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER))), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_SimpleOrdering2() {
ParseResult<Car> parseResult = parser.parse("SELECT * FROM cars WHERE 'manufacturer' = 'Ford' ORDER BY manufacturer asc");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER))), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_ComplexOrdering() {
ParseResult<Car> parseResult = parser.parse("SELECT * FROM cars WHERE 'manufacturer' = 'Ford' ORDER BY manufacturer ASC, carId DESC");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.CAR_ID))), parseResult.getQueryOptions());
}
@Test
public void testOrderBy_AscIsOptional() {
ParseResult<Car> parseResult = parser.parse("SELECT * FROM cars WHERE 'manufacturer' = 'Ford' ORDER BY manufacturer, carId DESC");
assertQueriesEquals(equal(Car.MANUFACTURER, "Ford"), parseResult.getQuery());
Assert.assertEquals(queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.CAR_ID))), parseResult.getQueryOptions());
}
@Test
public void testRetrieve() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(10));
ResultSet<Car> results = parser.retrieve(cars, "SELECT * FROM cars WHERE (manufacturer = 'Honda' AND color <> 'WHITE') ORDER BY carId DESC");
Assert.assertEquals(2, results.size());
Assert.assertEquals(asList(5, 4), extractCarIds(results, new ArrayList<Integer>()));
}
} | 11,491 | 54.516908 | 183 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/query/parser/sql/SQLDateMathTest.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.sql;
import com.googlecode.cqengine.query.parser.sql.support.DateMathParser;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.assertNotNull;
/**
* Unit tests for {@link DateMathParser}.
*
* @author npgall
*/
public class SQLDateMathTest {
@Test
public void testSQLDateMath() {
DateMathParser dateMathParser = new DateMathParser();
Date parsedDate = dateMathParser.validatedParse(Date.class, "'+0DAY'");
assertNotNull(parsedDate);
}
}
| 1,156 | 28.666667 | 79 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/metadata/MetadataEngineTest.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.metadata;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import org.mockito.Mockito;
import static com.googlecode.cqengine.metadata.AttributeMetadataTest.createIndexedCollectionOfCars;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Unit tests for {@link MetadataEngine}.
*/
public class MetadataEngineTest {
@Test
public void testAttemptToAccessMetadataWithoutIndex() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(5);
@SuppressWarnings("unchecked") Attribute<Car, Integer> ATTRIBUTE = Mockito.mock(SimpleAttribute.class);
Mockito.when(ATTRIBUTE.toString()).thenReturn("ATTRIBUTE");
IllegalStateException expected = null;
try {
cars.getMetadataEngine().getAttributeMetadata(ATTRIBUTE);
}
catch (IllegalStateException e) {
expected = e;
}
assertNotNull(expected);
assertEquals("A KeyStatisticsAttributeIndex has not been added to the collection, and must be added first, to enable metadata to be examined for attribute: ATTRIBUTE", expected.getMessage());
}
@Test
public void testAttemptToAccessMetadataWithIndexOnDifferentAttribute() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(5);
// Add an index on a different attribute...
cars.addIndex(HashIndex.onAttribute(Car.MODEL));
// Create a mock (different) attribute we will query...
@SuppressWarnings("unchecked") Attribute<Car, Integer> ATTRIBUTE = Mockito.mock(SimpleAttribute.class);
Mockito.when(ATTRIBUTE.toString()).thenReturn("ATTRIBUTE");
IllegalStateException expected = null;
try {
cars.getMetadataEngine().getAttributeMetadata(ATTRIBUTE);
}
catch (IllegalStateException e) {
expected = e;
}
assertNotNull(expected);
assertEquals("A KeyStatisticsAttributeIndex has not been added to the collection, and must be added first, to enable metadata to be examined for attribute: ATTRIBUTE", expected.getMessage());
}
@Test
public void testAttemptToAccessMetadataWithoutSortedIndex() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(5);
@SuppressWarnings("unchecked") Attribute<Car, Integer> ATTRIBUTE = Mockito.mock(SimpleAttribute.class);
Mockito.when(ATTRIBUTE.toString()).thenReturn("ATTRIBUTE");
IllegalStateException expected = null;
try {
cars.getMetadataEngine().getSortedAttributeMetadata(ATTRIBUTE);
}
catch (IllegalStateException e) {
expected = e;
}
assertNotNull(expected);
assertEquals("A SortedKeyStatisticsAttributeIndex has not been added to the collection, and must be added first, to enable metadata to be examined for attribute: ATTRIBUTE", expected.getMessage());
}
} | 3,785 | 43.541176 | 205 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/metadata/AttributeMetadataTest.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.metadata;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.index.support.KeyStatistics;
import com.googlecode.cqengine.index.support.KeyValue;
import com.googlecode.cqengine.index.support.KeyValueMaterialized;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Test;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.*;
/**
* Unit tests for {@link AttributeMetadata}.
*/
public class AttributeMetadataTest {
@Test
public void testGetFrequencyDistribution() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20);
// Add an unsorted index on Car.MANUFACTURER (a HashIndex)...
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MANUFACTURER attribute.
// Because we call getAttributeMetadata() (and not getSortedAttributeMetadata()),
// values will be returned in no particular order...
AttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getAttributeMetadata(Car.MANUFACTURER);
// Call AttributeMetadata.getFrequencyDistribution() to retrieve distinct keys and counts in no particular order.
// We retrieve into a Set (not a List), to assert the expected values were returned, without asserting any order...
assertEquals(
asSet(frequency("Ford", 6), frequency("BMW", 2), frequency("Toyota", 6), frequency("Honda", 6)),
sortedAttributeMetadata.getFrequencyDistribution().collect(toSet())
);
}
@Test
public void testGetDistinctKeys() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20); // the 20 cars will contain 10 distinct models
// Add an unsorted index on Car.MODEL (a HashIndex)...
cars.addIndex(HashIndex.onAttribute(Car.MODEL));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MODEL attribute.
// Because we call getAttributeMetadata() (and not getSortedAttributeMetadata()),
// values will be returned in no particular order...
AttributeMetadata<String, Car> attributeMetadata = metadataEngine.getAttributeMetadata(Car.MODEL);
// Call AttributeMetadata.getDistinctKeys() to retrieve distinct keys in no particular order.
// We retrieve into a Set (not a List), to assert the expected values were returned, without asserting any order...
assertEquals(
asSet("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus"),
attributeMetadata.getDistinctKeys().collect(toSet())
);
}
@Test
public void testGetCountOfDistinctKeys() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20); // the 20 cars will contain 4 distinct manufacturers
// Add an unsorted index on Car.MANUFACTURER (a HashIndex)...
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Count the distinct manufacturers...
AttributeMetadata<String, Car> attributeMetadata = metadataEngine.getAttributeMetadata(Car.MANUFACTURER);
assertEquals(Integer.valueOf(4), attributeMetadata.getCountOfDistinctKeys());
}
@Test
public void testGetCountForKey() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20);
// Add an unsorted index on Car.MANUFACTURER (a HashIndex)...
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Count the number of cars manufactured by BMW...
AttributeMetadata<String, Car> attributeMetadata = metadataEngine.getAttributeMetadata(Car.MANUFACTURER);
assertEquals(Integer.valueOf(2), attributeMetadata.getCountForKey("BMW"));
}
@Test
public void testGetKeysAndValues() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
Car car1 = new Car(1, "Ford", "Taurus", Car.Color.GREEN, 4, 1000.0, emptyList(), Collections.emptyList());
Car car2 = new Car(2, "Honda", "Civic", Car.Color.BLUE, 4, 2000.0, emptyList(), Collections.emptyList());
Car car3 = new Car(3, "Honda", "Accord", Car.Color.RED, 4, 3000.0, emptyList(), Collections.emptyList());
cars.addAll(asList(car1, car2, car3));
// Add an unsorted index on Car.MANUFACTURER (a HashIndex)...
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MODEL attribute.
// Because we call getAttributeMetadata() (and not getSortedAttributeMetadata()),
// values will be returned in no particular order...
AttributeMetadata<String, Car> attributeMetadata = metadataEngine.getAttributeMetadata(Car.MANUFACTURER);
// Call AttributeMetadata.getDistinctKeys() to retrieve distinct keys in no particular order.
// We retrieve into a Set (not a List), to assert the expected values were returned, without asserting any order...
assertEquals(
asSet(keyValue("Ford", car1), keyValue("Honda", car2), keyValue("Honda", car3)),
attributeMetadata.getKeysAndValues().collect(toSet())
);
}
// ==============================
// === Test helper methods... ===
// ==============================
static IndexedCollection<Car> createIndexedCollectionOfCars(int numCars) {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<>();
collection.addAll(CarFactory.createCollectionOfCars(numCars));
return collection;
}
static <T> Set<T> asSet(T... elements) {
return new LinkedHashSet<>(asList(elements));
}
static <A> KeyFrequency<A> frequency(A value, int count) {
return new KeyStatistics<>(value, count);
}
static <A, O> KeyValue<A, O> keyValue(A key, O value) {
return new KeyValueMaterialized<>(key, value);
}
} | 7,176 | 45.00641 | 125 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/metadata/SortedAttributeMetadataTest.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.metadata;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.Collections;
import static com.googlecode.cqengine.metadata.AttributeMetadataTest.*;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
/**
* Unit tests for {@link SortedAttributeMetadata}.
*/
public class SortedAttributeMetadataTest {
@Test
public void testGetFrequencyDistribution() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20);
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MANUFACTURER attribute.
// Because we call getSortedAttributeMetadata() values will be returned in ascending order...
SortedAttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
// Call AttributeMetadata.getFrequencyDistribution() to retrieve distinct keys and counts in ascending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList(frequency("BMW", 2), frequency("Ford", 6), frequency("Honda", 6), frequency("Toyota", 6)),
sortedAttributeMetadata.getFrequencyDistribution().collect(toList())
);
}
@Test
public void testGetFrequencyDistributionDescending() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20);
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MANUFACTURER attribute.
// Because we call getSortedAttributeMetadata() values will be returned in ascending order...
SortedAttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
// Call AttributeMetadata.getFrequencyDistribution() to retrieve distinct keys and counts in ascending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList(frequency("Toyota", 6), frequency("Honda", 6), frequency("Ford", 6), frequency("BMW", 2)),
sortedAttributeMetadata.getFrequencyDistributionDescending().collect(toList())
);
}
@Test
public void testGetDistinctKeys() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20); // the 20 cars will contain 10 distinct models
// Add a sorted index on Car.MODEL (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MODEL));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MODEL attribute.
// Because we call getSortedAttributeMetadata(), values will be returned in sorted order...
SortedAttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MODEL);
// Call SortedAttributeMetadata.getDistinctKeys() to retrieve distinct keys in ascending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus"),
sortedAttributeMetadata.getDistinctKeys().collect(toList())
);
// Test specifying range explicitly...
assertEquals(
asList("Civic", "Focus", "Fusion", "Hilux", "Insight"),
sortedAttributeMetadata.getDistinctKeys("Civic", true, "Insight", true).collect(toList())
);
assertEquals(
asList("Focus", "Fusion", "Hilux"),
sortedAttributeMetadata.getDistinctKeys("Civic", false, "Insight", false).collect(toList())
);
assertEquals(
asList("Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius"),
sortedAttributeMetadata.getDistinctKeys("Alpha", false, "Tango", false).collect(toList())
);
}
@Test
public void testGetDistinctKeysDescending() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20); // the 20 cars will contain 10 distinct models
// Add a sorted index on Car.MODEL (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MODEL));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MODEL attribute.
// Because we call getSortedAttributeMetadata(), values will be returned in sorted order...
SortedAttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MODEL);
// Call SortedAttributeMetadata.getDistinctKeysDescending() to retrieve distinct keys in descending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList("Taurus", "Prius", "M6", "Insight", "Hilux", "Fusion", "Focus", "Civic", "Avensis", "Accord"),
sortedAttributeMetadata.getDistinctKeysDescending().collect(toList())
);
// Test specifying range explicitly...
assertEquals(
asList("Hilux", "Fusion", "Focus"),
sortedAttributeMetadata.getDistinctKeysDescending("Civic", false, "Insight", false).collect(toList())
);
assertEquals(
asList("Prius", "M6", "Insight", "Hilux", "Fusion", "Focus", "Civic", "Avensis"),
sortedAttributeMetadata.getDistinctKeysDescending("Alpha", false, "Tango", false).collect(toList())
);
}
@Test
public void testGetCountOfDistinctKeys() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20); // the 20 cars will contain 4 distinct manufacturers
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Count the distinct manufacturers...
SortedAttributeMetadata<String, Car> sortedAttributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
assertEquals(Integer.valueOf(4), sortedAttributeMetadata.getCountOfDistinctKeys());
}
@Test
public void testGetCountForKey() {
IndexedCollection<Car> cars = createIndexedCollectionOfCars(20);
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Count the number of cars manufactured by BMW...
SortedAttributeMetadata<String, Car> attributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
assertEquals(Integer.valueOf(2), attributeMetadata.getCountForKey("BMW"));
}
@Test
public void testGetKeysAndValues() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
Car car1 = new Car(1, "Ford", "Taurus", Car.Color.GREEN, 4, 1000.0, emptyList(), Collections.emptyList());
Car car2 = new Car(2, "Toyota", "Prius", Car.Color.BLUE, 4, 2000.0, emptyList(), Collections.emptyList());
Car car3 = new Car(3, "Honda", "Civic", Car.Color.BLUE, 4, 2000.0, emptyList(), Collections.emptyList());
cars.addAll(asList(car1, car2, car3));
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MANUFACTURER attribute.
SortedAttributeMetadata<String, Car> attributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
// Call SortedAttributeMetadata.getKeysAndValues() to retrieve keys and values in ascending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList(keyValue("Ford", car1), keyValue("Honda", car3), keyValue("Toyota", car2)),
attributeMetadata.getKeysAndValues().collect(toList())
);
// Test specifying range explicitly...
assertEquals(
asList(keyValue("Ford", car1), keyValue("Honda", car3)),
attributeMetadata.getKeysAndValues("Alpha", true, "Toyota", false).collect(toList())
);
}
@Test
public void testGetKeysAndValuesDescending() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
Car car1 = new Car(1, "Ford", "Taurus", Car.Color.GREEN, 4, 1000.0, emptyList(), Collections.emptyList());
Car car2 = new Car(2, "Toyota", "Prius", Car.Color.BLUE, 4, 2000.0, emptyList(), Collections.emptyList());
Car car3 = new Car(3, "Honda", "Civic", Car.Color.BLUE, 4, 2000.0, emptyList(), Collections.emptyList());
cars.addAll(asList(car1, car2, car3));
// Add a sorted index on Car.MANUFACTURER (a NavigableIndex)...
cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER));
MetadataEngine<Car> metadataEngine = cars.getMetadataEngine();
// Access metadata for Car.MANUFACTURER attribute.
SortedAttributeMetadata<String, Car> attributeMetadata = metadataEngine.getSortedAttributeMetadata(Car.MANUFACTURER);
// Call SortedAttributeMetadata.getKeysAndValuesDescending() to retrieve keys and values in descending order.
// We retrieve into a List in order to assert the ordering of values returned...
assertEquals(
asList(keyValue("Toyota", car2), keyValue("Honda", car3), keyValue("Ford", car1)),
attributeMetadata.getKeysAndValuesDescending().collect(toList())
);
// Test specifying range explicitly...
assertEquals(
asList(keyValue("Honda", car3), keyValue("Ford", car1)),
attributeMetadata.getKeysAndValuesDescending("Alpha", true, "Toyota", false).collect(toList())
);
}
} | 11,311 | 49.053097 | 131 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/functional/DeduplicationTest.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.functional;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.DeduplicationOption;
import com.googlecode.cqengine.query.option.DeduplicationStrategy;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.Collections;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.testutil.Car.COLOR;
import static com.googlecode.cqengine.testutil.Car.Color.BLUE;
import static com.googlecode.cqengine.testutil.Car.MANUFACTURER;
import static org.junit.Assert.assertEquals;
/**
* @author Niall Gallagher
*/
public class DeduplicationTest {
@Test
public void testDeduplication_Materialize() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.add(new Car(1, "Ford", "Focus", BLUE, 5, 1000.0, Collections.<String>emptyList(), Collections.emptyList()));
cars.addIndex(HashIndex.onAttribute(Car.COLOR));
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
Query<Car> query = or(
equal(COLOR, BLUE),
equal(MANUFACTURER, "Ford")
);
ResultSet<Car> results;
results = cars.retrieve(query);
assertEquals(2, results.size());
DeduplicationOption deduplicate = deduplicate(DeduplicationStrategy.MATERIALIZE);
results = cars.retrieve(query, queryOptions(deduplicate));
assertEquals(1, results.size());
}
@Test
public void testDeduplication_Logical() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.add(new Car(1, "Ford", "Focus", BLUE, 5, 1000.0, Collections.<String>emptyList(), Collections.emptyList()));
cars.addIndex(HashIndex.onAttribute(Car.COLOR));
cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));
Query<Car> query = or(
equal(COLOR, BLUE),
equal(MANUFACTURER, "Ford")
);
ResultSet<Car> results;
results = cars.retrieve(query);
assertEquals(2, results.size());
DeduplicationOption deduplicate = deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION);
results = cars.retrieve(query, queryOptions(deduplicate));
assertEquals(1, results.size());
}
}
| 3,151 | 38.4 | 121 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/functional/JoinTest.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.functional;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.examples.join.Garage;
import com.googlecode.cqengine.query.Query;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Niall Gallagher
*/
public class JoinTest {
// Create an indexed collection of cars...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
Car car1 = new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof"));
Car car2 = new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio"));
Car car3 = new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio"));
Car car4 = new Car(4, "BMW M3", "2013 model", asList("radio", "convertible"));
Car car5 = new Car(5, "BMW M6", "2014 model", asList("radio", "convertible"));
{ cars.addAll(asList(car1, car2, car3, car4, car5)); }
// Create an indexed collection of garages...
final IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
Garage garage1 = new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic"));
Garage garage2 = new Garage(2, "Jane's garage", "Dublin", asList("BMW M3"));
Garage garage3 = new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus"));
Garage garage4 = new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus"));
Garage garage5 = new Garage(5, "Sam's garage", "Dubai", asList("BMW M3", "BMW M6"));
Garage garage6 = new Garage(6, "Jen's garage", "Galway", asList("Bat Mobile", "Golf Cart"));
{ garages.addAll(asList(garage1, garage2, garage3, garage4, garage5, garage6)); }
/**
* Find cars which are convertible or which have a sunroof, which can be serviced in Dublin.
*/
@Test
public void testSqlExistsWithForeignRestriction() {
Query<Car> carsQuery = and(
in(Car.FEATURES, "sunroof", "convertible"),
existsIn(garages,
Car.NAME,
Garage.BRANDS_SERVICED,
equal(Garage.LOCATION, "Dublin")
)
);
Set<Car> results = asSet(cars.retrieve(carsQuery));
assertEquals("should have 2 results", 2, results.size());
assertTrue("results should contain car1", results.contains(car1));
assertTrue("results should contain car4", results.contains(car4));
}
/**
* Find cars which are convertible or which have a sunroof,
* which can be serviced by any garage which we have on file.
*/
@Test
public void testSqlExistsNoForeignRestriction() {
Query<Car> carsQuery = and(
in(Car.FEATURES, "sunroof", "convertible"),
existsIn(garages,
Car.NAME,
Garage.BRANDS_SERVICED
)
);
Set<Car> results = asSet(cars.retrieve(carsQuery));
assertEquals("should have 3 results", 3, results.size());
assertTrue("results should contain car1", results.contains(car1));
assertTrue("results should contain car4", results.contains(car4));
assertTrue("results should contain car5", results.contains(car5));
}
/**
* Find garages which can service any type of convertible car.
*/
@Test
public void testSqlExistsMultiValuedWithForeignRestriction() {
Query<Garage> garagesQuery = existsIn(cars,
Garage.BRANDS_SERVICED,
Car.NAME,
equal(Car.FEATURES, "convertible")
);
Set<Garage> results = asSet(garages.retrieve(garagesQuery));
assertEquals("should have 2 results", 2, results.size());
assertTrue("results should contain garage2", results.contains(garage2));
assertTrue("results should contain garage5", results.contains(garage5));
}
/**
* Find garages which can service cars which we do not have on file.
*/
@Test
public void testSqlExistsMultiValuedNoForeignRestriction() {
Query<Garage> garagesQuery = not(
existsIn(cars,
Garage.BRANDS_SERVICED,
Car.NAME
)
);
Set<Garage> results = asSet(garages.retrieve(garagesQuery));
assertEquals("should have 1 result", 1, results.size());
assertTrue("results should contain garage6", results.contains(garage6));
}
/**
* Find cars which are convertible or which have a sunroof,
* which can be serviced in Dublin, and find those Garages which can service them.
*/
@Test
public void testSqlExistsBasedJoin() {
Query<Car> carsQuery = and(
in(Car.FEATURES, "sunroof", "convertible"),
existsIn(garages,
Car.NAME,
Garage.BRANDS_SERVICED,
equal(Garage.LOCATION, "Dublin")
)
);
Map<Car, Set<Garage>> results = new LinkedHashMap<Car, Set<Garage>>();
for (Car car : cars.retrieve(carsQuery)) {
Query<Garage> garagesWhichServiceThisCarInDublin
= and(equal(Garage.BRANDS_SERVICED, car.name), equal(Garage.LOCATION, "Dublin"));
for (Garage garage : garages.retrieve(garagesWhichServiceThisCarInDublin)) {
Set<Garage> garagesWhichCanServiceThisCar = results.get(car);
if (garagesWhichCanServiceThisCar == null) {
garagesWhichCanServiceThisCar = new LinkedHashSet<Garage>();
results.put(car, garagesWhichCanServiceThisCar);
}
garagesWhichCanServiceThisCar.add(garage);
}
}
assertEquals("join results should contain 2 cars", 2, results.size());
Assert.assertTrue("join results should contain car1", results.containsKey(car1));
Assert.assertTrue("join results should contain car4", results.containsKey(car4));
assertEquals("join results for car1", asSet(garage3, garage4), results.get(car1));
assertEquals("join results for car4", asSet(garage2), results.get(car4));
}
static <T> Set<T> asSet(T... objects) {
return asSet(asList(objects));
}
static <T> Set<T> asSet(Iterable<T> objects) {
Set<T> results = new LinkedHashSet<T>();
for (T object : objects) {
results.add(object);
}
return results;
}
}
| 7,489 | 38.840426 | 107 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/functional/GeneralFunctionalTest.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.functional;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.radix.RadixTreeIndex;
import com.googlecode.cqengine.index.radixinverted.InvertedRadixTreeIndex;
import com.googlecode.cqengine.index.radixreversed.ReversedRadixTreeIndex;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.Collections;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.testutil.TestUtil.setOf;
import static com.googlecode.cqengine.testutil.TestUtil.valuesOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Validates general functionality - indexes, query engine, ordering results.
*
* @author Niall Gallagher
*/
public class GeneralFunctionalTest {
@Test
public void testGeneralFunctionality() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addIndex(HashIndex.onAttribute(Car.MODEL));
cars.addIndex(HashIndex.onAttribute(Car.COLOR));
cars.addIndex(NavigableIndex.onAttribute(Car.DOORS));
cars.addIndex(RadixTreeIndex.onAttribute(Car.MODEL));
cars.addIndex(ReversedRadixTreeIndex.onAttribute(Car.MODEL));
cars.addIndex(InvertedRadixTreeIndex.onAttribute(Car.MODEL));
cars.addIndex(SuffixTreeIndex.onAttribute(Car.MODEL));
cars.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(2, "Ford", "Fiesta", Car.Color.BLUE, 2, 5000.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(3, "Ford", "F-150", Car.Color.RED, 2, 9500.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(4, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(5, "Toyota", "Prius", Car.Color.BLACK, 3, 9700.00, Collections.<String>emptyList(), Collections.emptyList()));
// Ford cars...
assertThat(carIdsIn(cars.retrieve(equal(Car.MANUFACTURER, "Ford"))), is(setOf(1, 2, 3)));
// 3-door cars...
assertThat(carIdsIn(cars.retrieve(equal(Car.DOORS, 3))), is(setOf(5)));
// 2 or 3-door cars...
assertThat(carIdsIn(cars.retrieve(between(Car.DOORS, 2, 3))), is(setOf(2, 3, 5)));
// 2 or 5-door cars...
assertThat(carIdsIn(cars.retrieve(in(Car.DOORS, 2, 5))), is(setOf(1, 2, 3, 4)));
// Blue Ford cars...
assertThat(carIdsIn(cars.retrieve(and(equal(Car.COLOR, Car.Color.BLUE), equal(Car.MANUFACTURER, "Ford")))), is(setOf(1, 2)));
// NOT 3-door cars...
assertThat(carIdsIn(cars.retrieve(not(equal(Car.DOORS, 3)))), is(setOf(1, 2, 3, 4)));
// Cars which have 5 doors and which are not red...
assertThat(carIdsIn(cars.retrieve(and(equal(Car.DOORS, 5), not(equal(Car.COLOR, Car.Color.RED))))), is(setOf(1)));
// Cars whose model starts with 'F'...
assertThat(carIdsIn(cars.retrieve(startsWith(Car.MODEL, "F"))), is(setOf(1, 2, 3)));
// Cars whose model ends with 's'...
assertThat(carIdsIn(cars.retrieve(endsWith(Car.MODEL, "s"))), is(setOf(1, 5)));
// Cars whose model contains 'i'...
assertThat(carIdsIn(cars.retrieve(contains(Car.MODEL, "i"))), is(setOf(2, 4, 5)));
// Cars whose model is contained in 'Banana, Focus, Civic, Foobar'...
assertThat(carIdsIn(cars.retrieve(isContainedIn(Car.MODEL, "Banana, Focus, Civic, Foobar"))), is(setOf(1, 4)));
// NOT 3-door cars, sorted by doors ascending...
assertThat(
carIdsIn(cars.retrieve(not(equal(Car.DOORS, 3)), queryOptions(orderBy(ascending(Car.DOORS))))).toString(),
is(equalTo(setOf(2, 3, 1, 4).toString()))
);
// NOT 3-door cars, sorted by doors ascending then price descending...
assertThat(
carIdsIn(
cars.retrieve(
not(equal(Car.DOORS, 3)),
queryOptions(
orderBy(ascending(Car.DOORS),
descending(Car.PRICE))
)
)
).toString(),
is(equalTo(setOf(3, 2, 1, 4).toString()))
);
}
static Set<Integer> carIdsIn(ResultSet<Car> resultSet) {
return valuesOf(Car.CAR_ID, resultSet);
}
}
| 5,581 | 44.016129 | 136 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/functional/IndexOrderingTest.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.functional;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.persistence.disk.DiskPersistence;
import com.googlecode.cqengine.query.option.EngineThresholds;
import com.googlecode.cqengine.query.option.QueryLog;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.option.EngineThresholds.*;
/**
* TODO - remove this temporary test (functionality is tested in IndexedCollectionFunctionalTest).
*
* Created by npgall on 27/07/2015.
*/
public class IndexOrderingTest {
public static void main(String[] args) {
final int NUM_ITERATIONS = 1000;
final int[] numObjects = {10000, 10000, 100000};
final double[] selectivityThreshold = {0.0, 0.5, 1.0};
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(1000000));
cars.addIndex(NavigableIndex.onAttribute(Car.CAR_ID));
cars.addIndex(NavigableIndex.onAttribute(Car.COLOR));
for (int n : numObjects) {
for (double s : selectivityThreshold) {
long start = System.currentTimeMillis();
long count = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
count = countRetrievedResults(cars, n, s);
}
long timeTaken = System.currentTimeMillis() - start;
System.out.println("Number: " + n + ", selectivity threshold: " + s + ", time taken per iteration: " + (timeTaken / (double)NUM_ITERATIONS) + " (count=" + count + ")");
}
}
}
static long countRetrievedResults(IndexedCollection<Car> cars, int numObjects, double indexOrderingSelectivityThreshold) {
ResultSet<Car> resultSet = cars.retrieve(and(lessThan(Car.CAR_ID, numObjects), equal(Car.COLOR, Car.Color.BLUE)), queryOptions(
orderBy(descending(Car.CAR_ID)),
applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, indexOrderingSelectivityThreshold))
));
int count = 0;
for (Car c : resultSet) {
count++;
if (count>= 10) {
break;
}
}
return count;
}
}
| 3,222 | 40.320513 | 184 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/TransactionalIndexedCollection.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;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.ArgumentValidationOption;
import com.googlecode.cqengine.query.option.FlagsEnabled;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.closeable.CloseableFilteringResultSet;
import com.googlecode.cqengine.resultset.closeable.CloseableResultSet;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.option.IsolationLevel.READ_UNCOMMITTED;
import static com.googlecode.cqengine.query.option.IsolationOption.isIsolationLevel;
/**
* Extends {@link ConcurrentIndexedCollection} with support for READ_COMMITTED transaction isolation using
* <a href="http://en.wikipedia.org/wiki/Multiversion_concurrency_control">Multiversion concurrency control</a>
* (MVCC).
* <p/>
* A transaction is composed of a set of objects to be added to the collection, and a set of objects to be removed from
* the collection. Either one of those sets can be empty, so this supports bulk <i>atomic addition</i> and <i>atomic
* removal</i> of objects from the collection. But if both sets are non-empty then it allows bulk
* <i>atomic replacement</i> of objects in the collection.
* <p/>
* <b>Atomically replacing objects</b><br/>
* A restriction is that if you want to replace objects in the collection, then for each object to be removed,
* {@code objectToRemove.equals(objectToAdd)} should return {@code false}. That is, the sets of objects to be removed
* and added must be <i>disjoint</i>. You can achieve that by adding a hidden version field in your object as follows:
* <pre>
* <code>
*
* public class Car {
*
* static final AtomicLong VERSION_GENERATOR = new AtomicLong();
*
* final int carId;
* final String name;
* final long version = VERSION_GENERATOR.incrementAndGet();
*
* public Car(int carId, String name) {
* this.carId = carId;
* this.name = name;
* }
*
* {@literal @Override}
* public int hashCode() {
* return carId;
* }
*
* {@literal @Override}
* public boolean equals(Object o) {
* if (this == o) return true;
* if (o == null || getClass() != o.getClass()) return false;
* Car other = (Car) o;
* if (this.carId != other.carId) return false;
* if (this.version != other.version) return false;
* return true;
* }
* }
* </code>
* </pre>
* <b>Argument validation</b><br/>
* By default this class will <b>validate</b> that objects to be replaced adhere to the requirement above, which adds
* some overhead to query processing. Therefore once applications are confirmed as being compliant, this validation
* can be switched off by supplying a QueryOption. See the JavaDoc on the {@code update()} method for details.
* @see #update(Iterable, Iterable, com.googlecode.cqengine.query.option.QueryOptions)
*
* @author Niall Gallagher
*/
public class TransactionalIndexedCollection<O> extends ConcurrentIndexedCollection<O> {
/**
* A query option flag which can be supplied to the update method to control the replacement behaviour.
*/
public static final String STRICT_REPLACEMENT = "STRICT_REPLACEMENT";
final Class<O> objectType;
volatile Version currentVersion;
final Object writeMutex = new Object();
final AtomicLong versionNumberGenerator = new AtomicLong();
class Version {
// New reading threads acquire read locks from the current Version.
// Writing threads create a new Version at each step of the MVCC algorithm,
// then acquire write locks from the previous Version before moving onto the next step.
// Therefore reading threads always acquire read locks from an uncontended Version,
// and writing threads wait for threads reading the previous version to finish before
// moving onto the next step.
final ReadWriteLock lock = new ReentrantReadWriteLock();
final Iterable<O> objectsToExclude;
// versionNumber is not actually used by the MVCC algorithm,
// it is only useful when debugging and for unit tests...
final long versionNumber = versionNumberGenerator.incrementAndGet();
Version(Iterable<O> objectsToExclude) {
this.objectsToExclude = objectsToExclude;
}
}
/**
* Creates a new {@link TransactionalIndexedCollection} with default settings, using {@link OnHeapPersistence}.
*
* @param objectType The type of objects which will be stored in the collection
*/
@SuppressWarnings("unchecked")
public TransactionalIndexedCollection(Class<O> objectType) {
this(objectType, OnHeapPersistence.<O>withoutPrimaryKey());
}
/**
* Creates a new {@link TransactionalIndexedCollection} which will use the given factory to create the backing set.
*
* @param objectType The type of objects which will be stored in the collection
* @param persistence The {@link Persistence} implementation which will create a concurrent {@link java.util.Set}
* in which objects added to the indexed collection will be stored, and which will provide
* access to the underlying storage of indexes.
*/
public <A extends Comparable<A>> TransactionalIndexedCollection(Class<O> objectType, Persistence<O, A> persistence) {
super(persistence);
this.objectType = objectType;
// Set up initial version...
this.currentVersion = new Version(Collections.<O>emptySet());
}
/**
* Creates a new Version and sets it as the current version and configures that version to exclude the given
* objects from results returned to threads which will read that version.
* Then, acquires the write lock on the previous Version, which will cause this (writing) thread
* to block until all threads reading the previous version have finished reading that version.
* @param objectsToExcludeFromNextVersion Objects to exclude from the next version
*/
void incrementVersion(Iterable<O> objectsToExcludeFromNextVersion) {
Version previousVersion = this.currentVersion;
this.currentVersion = new Version(objectsToExcludeFromNextVersion);
previousVersion.lock.writeLock().lock();
}
/**
* Acquires the (uncontended) read lock for the current version and returns the current Version object,
* while handling an edge case that a writing thread might be in the middle of incrementing the version,
* in which case this method will refresh the current version until successful.
*/
Version acquireReadLockForCurrentVersion() {
Version currentVersion;
do {
currentVersion = this.currentVersion;
} while (!currentVersion.lock.readLock().tryLock());
return currentVersion;
}
/**
* This is the same as calling without any query options:
* {@link #update(Iterable, Iterable, com.googlecode.cqengine.query.option.QueryOptions)}.
* <p/>
* @see #update(Iterable, Iterable, com.googlecode.cqengine.query.option.QueryOptions)
*/
@Override
public boolean update(Iterable<O> objectsToRemove, Iterable<O> objectsToAdd) {
return update(objectsToRemove, objectsToAdd, noQueryOptions());
}
/**
* {@inheritDoc}
* <p/>
* This method applies multi-version concurrency control by default such that the update is seen to occur
* <i>atomically</i> with {@code READ_COMMITTED} transaction isolation by reading threads.
* <p/>
* For performance reasons, transaction isolation may (optionally) be overridden on a case-by-case basis by
* supplying an {@link com.googlecode.cqengine.query.option.IsolationOption} query option to this method requesting
* {@link com.googlecode.cqengine.query.option.IsolationLevel#READ_UNCOMMITTED} transaction isolation instead.
* In that case the modifications will be made directly to the collection, bypassing multi-version concurrency
* control. This might be useful when making some modifications to the collection which do not need to be viewed
* atomically.
* <p/>
* <b>Atomically replacing objects and argument validation</b><br/>
* As discussed in this class' JavaDoc, the sets of objects to be removed and objects to be added supplied to this
* method as arguments, must be <i>disjoint</i> and <i>this method will validate that this is the case by
* default</i>.
* <p/>
* To disable this validation for performance reasons, supply QueryOption: <code>argumentValidation(SKIP)</code>.
* <p/>
* Note that if the application disables this validation and proceeds to call this method with non-compliant
* arguments anyway, then indexes may become inconsistent. Validation should only be skipped when it is certain that
* the application will be compliant.
* <p/>
* <b>Atomically replacing objects with STRICT_REPLACEMENT</b><br/>
* By default, this method will not check if the objects to be removed are actually contained in the collection.
* If any objects to be removed are not actually contained, then the objects to be added will be added anyway.
* <p/>
* Applications requiring "strict" object replacement, can supply QueryOption:
* <code>enableFlags(TransactionalIndexedCollection.STRICT_REPLACEMENT))</code>.
* If this query option is supplied, then a check will be performed to ensure that all of the objects to be removed
* are actually contained in the collection. If any objects to be removed are not contained, then the collection
* will not be modified and this method will return false.
*/
@Override
public boolean update(final Iterable<O> objectsToRemove, final Iterable<O> objectsToAdd, QueryOptions queryOptions) {
if (isIsolationLevel(queryOptions, READ_UNCOMMITTED)) {
// Write directly to the collection with no MVCC overhead...
return super.update(objectsToRemove, objectsToAdd, queryOptions);
}
// By default, validate that the sets of objectsToRemove and objectsToAdd are disjoint...
if (!ArgumentValidationOption.isSkip(queryOptions)) {
ensureUpdateSetsAreDisjoint(objectsToRemove, objectsToAdd);
}
// Otherwise apply MVCC to support READ_COMMITTED isolation...
synchronized (writeMutex) {
queryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
try {
Iterator<O> objectsToRemoveIterator = objectsToRemove.iterator();
Iterator<O> objectsToAddIterator = objectsToAdd.iterator();
if (!objectsToRemoveIterator.hasNext() && !objectsToAddIterator.hasNext()) {
return false;
}
if (FlagsEnabled.isFlagEnabled(queryOptions, STRICT_REPLACEMENT)) {
if (!objectStoreContainsAllIterable(objectStore, objectsToRemove, queryOptions)) {
return false;
}
}
boolean modified = false;
if (objectsToAddIterator.hasNext()) {
// Configure new reading threads to exclude the objects we will add,
// and then wait for threads reading previous versions to finish...
incrementVersion(objectsToAdd);
// Now add the given objects...
modified = doAddAll(objectsToAdd, queryOptions);
}
if (objectsToRemoveIterator.hasNext()) {
// Configure (or reconfigure) new reading threads to (instead) exclude the objects we will remove,
// and then wait for threads reading previous versions to finish...
incrementVersion(objectsToRemove);
// Now remove the given objects...
modified = doRemoveAll(objectsToRemove, queryOptions) || modified;
}
// Finally, remove the exclusion,
// and then wait for this to take effect across all threads...
incrementVersion(Collections.<O>emptySet());
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
}
@Override
public boolean add(O o) {
return update(Collections.<O>emptySet(), Collections.singleton(o));
}
@Override
@SuppressWarnings({"unchecked"})
public boolean remove(Object object) {
return update(Collections.singleton((O) object), Collections.<O>emptySet());
}
@Override
@SuppressWarnings({"unchecked"})
public boolean addAll(Collection<? extends O> c) {
return update(Collections.<O>emptySet(), (Collection<O>) c);
}
@Override
@SuppressWarnings({"unchecked"})
public boolean removeAll(Collection<?> c) {
return update((Collection<O>) c, Collections.<O>emptySet());
}
@Override
public boolean retainAll(final Collection<?> c) {
synchronized (writeMutex) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
// Copy objects into a new set removing nulls.
// CQEngine does not permit nulls in queries, but the spec of {@link Collection#retainAll} does.
Set<O> objectsToRetain = new HashSet<O>(c.size());
for (Object object : c) {
if (object != null) {
@SuppressWarnings("unchecked") O o = (O)object;
objectsToRetain.add(o);
}
}
// Prepare a query which will match objects in the collection which are not contained in the given
// collection of objects to retain and therefore which need to be removed from the collection...
// We prepare the query to use the same QueryOptions as above.
// Any resources opened for the query which need to be closed,
// will be added to the QueryOptions and closed at the end of this method.
@SuppressWarnings("unchecked")
ResultSet<O> objectsToRemove = super.retrieve(not(in(selfAttribute(objectType), objectsToRetain)), queryOptions);
Iterator<O> objectsToRemoveIterator = objectsToRemove.iterator();
if (!objectsToRemoveIterator.hasNext()) {
return false;
}
// Configure new reading threads to exclude the objects we will remove,
// then wait for this to take effect across all threads...
incrementVersion(objectsToRemove);
// Now remove the given objects...
boolean modified = doRemoveAll(objectsToRemove, queryOptions);
// Finally, remove the exclusion,
// then wait for this to take effect across all threads...
incrementVersion(Collections.<O>emptySet());
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
}
@Override
public synchronized void clear() {
retainAll(Collections.emptySet());
}
@Override
public ResultSet<O> retrieve(Query<O> query) {
return retrieve(query, noQueryOptions());
}
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
if (isIsolationLevel(queryOptions, READ_UNCOMMITTED)) {
// Allow the query to read directly from the collection with no filtering overhead...
return super.retrieve(query, queryOptions);
}
// Otherwise apply READ_COMMITTED isolation...
// Get the current Version and acquire an (uncontended) read lock on it...
final Version thisVersion = acquireReadLockForCurrentVersion();
try {
// Return the results matching the query such that:
// - STEP 1: When the ResultSet.close() method is called, we decrement the readers count
// to record that this thread is no longer reading this version.
// - STEP 2: We filter out from the results any objects which might not be fully committed yet
// (as configured by writing threads for this version of the collection).
ResultSet<O> results = super.retrieve(query, queryOptions);
// STEP 1: Wrap the results to intercept ResultSet.close()...
CloseableResultSet<O> versionReadingResultSet = new CloseableResultSet<O>(results, query, queryOptions) {
@Override
public void close() {
super.close();
// Release the read lock for this version when ResultSet.close() is called...
thisVersion.lock.readLock().unlock();
}
};
// STEP 2: Apply filtering as necessary...
if (thisVersion.objectsToExclude.iterator().hasNext()) {
// Apply the filtering to omit uncommitted objects...
return new CloseableFilteringResultSet<O>(versionReadingResultSet, query, queryOptions) {
@Override
public boolean isValid(O object, QueryOptions queryOptions) {
@SuppressWarnings("unchecked")
Iterable<O> objectsToExclude = (Iterable<O>) thisVersion.objectsToExclude;
return !iterableContains(objectsToExclude, object);
}
};
} else {
// As there were no objects to exclude, then we can return the results directly without filtering...
return versionReadingResultSet;
}
}
catch (RuntimeException e) {
// Release the read lock we acquired above, because due to throwing an exception,
// we will not be returning a CloseableResultSet which otherwise would allow it to be released later...
thisVersion.lock.readLock().unlock();
throw e;
}
}
static <O> boolean iterableContains(Iterable<O> objects, O o) {
if (objects instanceof Collection) {
return ((Collection<?>)objects).contains(o);
}
else if (objects instanceof ResultSet) {
return ((ResultSet<O>)objects).contains(o);
}
else {
return IteratorUtil.iterableContains(objects, o);
}
}
static <O> boolean objectStoreContainsAllIterable(ObjectStore<O> objectStore, Iterable<O> candidates, QueryOptions queryOptions) {
if (candidates instanceof Collection) {
return objectStore.containsAll((Collection<?>) candidates, queryOptions);
}
for (O candidate : candidates) {
if (!objectStore.contains(candidate, queryOptions)) {
return false;
}
}
return true;
}
static <O> void ensureUpdateSetsAreDisjoint(final Iterable<O> objectsToRemove, final Iterable<O> objectsToAdd) {
for (O objectToRemove : objectsToRemove) {
if (iterableContains(objectsToAdd, objectToRemove)) {
throw new IllegalArgumentException("The sets of objectsToRemove and objectsToAdd are not disjoint [for all objectsToRemove, objectToRemove.equals(objectToAdd) must return false].");
}
}
}
} | 20,823 | 46.327273 | 197 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/ConcurrentIndexedCollection.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;
import com.googlecode.cqengine.engine.QueryEngineInternal;
import com.googlecode.cqengine.engine.CollectionQueryEngine;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.index.support.CloseableRequestResources;
import com.googlecode.cqengine.metadata.MetadataEngine;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStoreAsSet;
import com.googlecode.cqengine.persistence.support.PersistenceFlags;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.FlagsEnabled;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.closeable.CloseableResultSet;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.queryOptions;
import static java.util.Collections.singleton;
/**
* An implementation of {@link java.util.Set} and {@link com.googlecode.cqengine.engine.QueryEngine}, thus providing
* {@link #retrieve(com.googlecode.cqengine.query.Query)} methods for performing queries on the collection to retrieve
* matching objects, and {@link #addIndex(com.googlecode.cqengine.index.Index)} methods allowing indexes to be
* added to the collection to improve query performance.
* <p/>
* This collection takes care of automatically updating any indexes with objects added to/from the collection.
* <p/>
* This collection is thread-safe for concurrent reads in all cases.
* <p/>
* This collection is thread-safe for concurrent writes in cases where multiple threads might try to add/remove
* <i>different</i> objects to/from the collection concurrently.
* <p/>
* This collection is <b>not</b> thread-safe in cases where two or more threads might try to add or remove the
* <i>same</i> object to/from the collection concurrently. There is a risk that indexes might get out of sync causing
* inconsistent results in that scenario with this implementation.
* <p/>
* In applications where multiple threads might add/remove the same object concurrently, then the subclass
* {@link ObjectLockingIndexedCollection} should be used instead. That subclass allows concurrent writes, but with
* additional safeguards against concurrent modification for the same object, with some additional overhead.
* <p/>
* Note that in this context the <i>same object</i> refers to either the same object instance, OR two object instances
* having the same hash code and being equal according to their {@link #equals(Object)} methods.
*
* @author Niall Gallagher
*/
public class ConcurrentIndexedCollection<O> implements IndexedCollection<O> {
protected final Persistence<O, ?> persistence;
protected final ObjectStore<O> objectStore;
protected final QueryEngineInternal<O> indexEngine;
protected final MetadataEngine<O> metadataEngine;
/**
* Creates a new {@link ConcurrentIndexedCollection} with default settings, using {@link OnHeapPersistence}.
*/
@SuppressWarnings("unchecked")
public ConcurrentIndexedCollection() {
this(OnHeapPersistence.<O>withoutPrimaryKey());
}
/**
* Creates a new {@link ConcurrentIndexedCollection} which will use the given persistence to create the backing set.
*
* @param persistence The {@link Persistence} implementation which will create a concurrent {@link java.util.Set}
* in which objects added to the indexed collection will be stored, and which will provide
* access to the underlying storage of indexes.
*/
public ConcurrentIndexedCollection(Persistence<O, ? extends Comparable> persistence) {
this.persistence = persistence;
this.objectStore = persistence.createObjectStore();
QueryEngineInternal<O> queryEngine = new CollectionQueryEngine<O>();
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
queryEngine.init(objectStore, queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
this.indexEngine = queryEngine;
this.metadataEngine = new MetadataEngine<>(
this,
() -> openRequestScopeResourcesIfNecessary(null),
this::closeRequestScopeResourcesIfNecessary
);
}
/**
* {@inheritDoc}
*/
@Override
public Persistence<O, ?> getPersistence() {
return persistence;
}
@Override
public MetadataEngine<O> getMetadataEngine() {
return metadataEngine;
}
// ----------- Query Engine Methods -------------
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(Query<O> query) {
return retrieve(query, null);
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions) {
final QueryOptions finalQueryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
flagAsReadRequest(finalQueryOptions);
ResultSet<O> results = indexEngine.retrieve(query, finalQueryOptions);
return new CloseableResultSet<O>(results, query, finalQueryOptions) {
@Override
public void close() {
super.close();
closeRequestScopeResourcesIfNecessary(finalQueryOptions);
}
};
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Iterable<O> objectsToRemove, Iterable<O> objectsToAdd) {
return update(objectsToRemove, objectsToAdd, null);
}
/**
* {@inheritDoc}
*/
@Override
public boolean update(Iterable<O> objectsToRemove, Iterable<O> objectsToAdd, QueryOptions queryOptions) {
queryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
try {
boolean modified = doRemoveAll(objectsToRemove, queryOptions);
return doAddAll(objectsToAdd, queryOptions) || modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public void addIndex(Index<O> index) {
addIndex(index, null);
}
/**
* {@inheritDoc}
*/
@Override
public void addIndex(Index<O> index, QueryOptions queryOptions) {
queryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
try {
indexEngine.addIndex(index, queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public void removeIndex(Index<O> index) {
removeIndex(index, null);
}
/**
* {@inheritDoc}
*/
@Override
public void removeIndex(Index<O> index, QueryOptions queryOptions) {
queryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
try {
indexEngine.removeIndex(index, queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
@Override
public Iterable<Index<O>> getIndexes() {
return indexEngine.getIndexes();
}
// ----------- Collection Accessor Methods -------------
/**
* {@inheritDoc}
*/
@Override
public int size() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return objectStore.size(queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return objectStore.isEmpty(queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(Object o) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return objectStore.contains(o, queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public Object[] toArray() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return getObjectStoreAsSet(queryOptions).toArray();
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> T[] toArray(T[] a) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
//noinspection SuspiciousToArrayCall
return getObjectStoreAsSet(queryOptions).toArray(a);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsAll(Collection<?> c) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return objectStore.containsAll(c, queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
// ----------- Collection Mutator Methods -------------
/**
* {@inheritDoc}
*/
@Override
public CloseableIterator<O> iterator() {
return new CloseableIterator<O>() {
final QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
private final CloseableIterator<O> collectionIterator = objectStore.iterator(queryOptions);
boolean autoClosed = false;
@Override
public boolean hasNext() {
boolean hasNext = collectionIterator.hasNext();
if (!hasNext) {
close();
autoClosed = true;
}
return hasNext;
}
private O currentObject = null;
@Override
public O next() {
O next = collectionIterator.next();
currentObject = next;
return next;
}
@Override
public void remove() {
if (currentObject == null) {
throw new IllegalStateException();
}
// Handle an edge case where we might have retrieved the last object and called close() automatically,
// but then the application calls remove() so we have to reopen request-scope resources temporarily
// to remove the last object...
if (autoClosed) {
ConcurrentIndexedCollection.this.remove(currentObject); // reopens resources temporarily
}
else {
doRemoveAll(Collections.singleton(currentObject), queryOptions); // uses existing resources
}
currentObject = null;
}
@Override
public void close() {
CloseableRequestResources.closeQuietly(collectionIterator);
closeRequestScopeResourcesIfNecessary(queryOptions);
}
};
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(O o) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
// Add the object to the index.
// Indexes handle gracefully the case that the objects supplied already exist in the index...
boolean modified = objectStore.add(o, queryOptions);
indexEngine.addAll(ObjectSet.fromCollection(singleton(o)), queryOptions);
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object object) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
@SuppressWarnings({"unchecked"})
O o = (O) object;
boolean modified = objectStore.remove(o, queryOptions);
indexEngine.removeAll(ObjectSet.fromCollection(singleton(o)), queryOptions);
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(Collection<? extends O> c) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
@SuppressWarnings({"unchecked"})
Collection<O> objects = (Collection<O>) c;
boolean modified = objectStore.addAll(objects, queryOptions);
indexEngine.addAll(ObjectSet.fromCollection(objects), queryOptions);
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(Collection<?> c) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
@SuppressWarnings({"unchecked"})
Collection<O> objects = (Collection<O>) c;
boolean modified = objectStore.removeAll(objects, queryOptions);
indexEngine.removeAll(ObjectSet.fromCollection(objects), queryOptions);
return modified;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean retainAll(Collection<?> c) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
CloseableIterator<O> iterator = null;
try {
boolean modified = false;
iterator = objectStore.iterator(queryOptions);
while (iterator.hasNext()) {
O next = iterator.next();
if (!c.contains(next)) {
doRemoveAll(Collections.singleton(next), queryOptions);
modified = true;
}
}
return modified;
}
finally {
CloseableRequestResources.closeQuietly(iterator);
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
objectStore.clear(queryOptions);
indexEngine.clear(queryOptions);
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
boolean doAddAll(Iterable<O> objects, QueryOptions queryOptions) {
if (objects instanceof Collection) {
Collection<O> c = (Collection<O>) objects;
boolean modified = objectStore.addAll(c, queryOptions);
indexEngine.addAll(ObjectSet.fromCollection(c), queryOptions);
return modified;
}
else {
boolean modified = false;
for (O object : objects) {
boolean added = objectStore.add(object, queryOptions);
indexEngine.addAll(ObjectSet.fromCollection(singleton(object)), queryOptions);
modified = added || modified;
}
return modified;
}
}
boolean doRemoveAll(Iterable<O> objects, QueryOptions queryOptions) {
if (objects instanceof Collection) {
Collection<O> c = (Collection<O>) objects;
boolean modified = objectStore.removeAll(c, queryOptions);
indexEngine.removeAll(ObjectSet.fromCollection(c), queryOptions);
return modified;
} else {
boolean modified = false;
for (O object : objects) {
boolean removed = objectStore.remove(object, queryOptions);
indexEngine.removeAll(ObjectSet.fromCollection(singleton(object)), queryOptions);
modified = removed || modified;
}
return modified;
}
}
protected QueryOptions openRequestScopeResourcesIfNecessary(QueryOptions queryOptions) {
if (queryOptions == null) {
queryOptions = new QueryOptions();
}
if (!(persistence instanceof OnHeapPersistence)) {
persistence.openRequestScopeResources(queryOptions);
}
queryOptions.put(Persistence.class, persistence);
return queryOptions;
}
protected void closeRequestScopeResourcesIfNecessary(QueryOptions queryOptions) {
if (!(persistence instanceof OnHeapPersistence)) {
persistence.closeRequestScopeResources(queryOptions);
}
}
protected ObjectStoreAsSet<O> getObjectStoreAsSet(QueryOptions queryOptions) {
return new ObjectStoreAsSet<O>(objectStore, queryOptions);
}
@Override
public boolean equals(Object o) {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
if (this == o) return true;
if (!(o instanceof Set)) return false;
Set that = (Set) o;
if (!getObjectStoreAsSet(queryOptions).equals(that)) return false;
return true;
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
@Override
public int hashCode() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return getObjectStoreAsSet(queryOptions).hashCode();
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
@Override
public String toString() {
QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
try {
return getObjectStoreAsSet(queryOptions).toString();
}
finally {
closeRequestScopeResourcesIfNecessary(queryOptions);
}
}
/**
* Sets a flag into the given query options to record that this request will read from the collection
* but will not modify it.
* This is used to facilitate locking in some persistence implementations.
*
* @param queryOptions The query options for the request
*/
protected static void flagAsReadRequest(QueryOptions queryOptions) {
FlagsEnabled.forQueryOptions(queryOptions).add(PersistenceFlags.READ_REQUEST);
}
}
| 19,766 | 33.022375 | 120 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/ObjectLockingIndexedCollection.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;
import com.googlecode.cqengine.index.support.CloseableIterator;
import com.googlecode.cqengine.index.support.CloseableRequestResources;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Extends {@link ConcurrentIndexedCollection} with some specialized locking for applications in
* which multiple threads might try to add or remove the <b>same object</b> to/from an indexed collection
* <i>concurrently</i>. In this context the <i>same object</i> refers to either the same object instance, OR two object
* instances having the same hash code and being equal according to their {@link #equals(Object)} methods.
* <p/>
* The {@link ConcurrentIndexedCollection} superclass is thread-safe in cases where the application will add/remove
* <i>different</i> objects concurrently. This implementation adds safeguards around adding/removing the <i>same</i>
* object concurrently, with some additional overhead.
* <p/>
* Reading threads are never blocked; reads remain lock-free as in the superclass.
* <p/>
* This class is currently implemented with a
* <a href="http://code.google.com/p/guava-libraries/wiki/StripedExplained">striped lock</a> (although not the Guava
* implementation). As such, the hash code of an object is not assigned a unique lock, but there is instead a
* many-to-fewer association between hash codes and locks. Some different objects will therefore contend for the same
* lock. The number of stripes (locks) is configurable, allowing this ratio and likelihood of contention to be
* controlled, trading memory overhead of a large number of locks, against likelihood of contention. Two or more
* modifications for the same object, will always block each other. Two or more modifications for different objects
* will <i>usually not</i> block each other, but occasionally might.
* <p/>
* Although this class is currently implemented with a striped lock, this might be replaced with a
* <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/StampedLock.html">stamped lock</a>.
* Applications should not rely on the locking behaviour of this class, except to guard against the concurrent
* access scenario stated above.
*
* @author Niall Gallagher
*/
public class ObjectLockingIndexedCollection<O> extends ConcurrentIndexedCollection<O> {
final StripedLock stripedLock;
/**
* Creates a new {@link ObjectLockingIndexedCollection} with default settings, using {@link OnHeapPersistence}
* and a default concurrency level 64.
*/
@SuppressWarnings("unchecked")
public ObjectLockingIndexedCollection() {
this(OnHeapPersistence.<O>withoutPrimaryKey(), 64);
}
/**
* Creates a new {@link ObjectLockingIndexedCollection} which will use the given persistence to create the backing
* set, and a default concurrency level 64.
*
* @param persistence The {@link Persistence} implementation which will create a concurrent {@link java.util.Set}
* in which objects added to the indexed collection will be stored, and which will provide
* access to the underlying storage of indexes.
*/
public <A extends Comparable<A>> ObjectLockingIndexedCollection(Persistence<O, A> persistence) {
this(persistence, 64);
}
/**
* Creates a new {@link ObjectLockingIndexedCollection} using {@link OnHeapPersistence} and the given concurrency
* level.
*
* @param concurrencyLevel The estimated number of concurrently updating threads
*/
@SuppressWarnings("unchecked")
public <A extends Comparable<A>> ObjectLockingIndexedCollection(int concurrencyLevel) {
this(OnHeapPersistence.<O>withoutPrimaryKey(), concurrencyLevel);
}
/**
* Creates a new {@link ObjectLockingIndexedCollection}, which will use the given persistence to create the backing
* set, and the given concurrency level.
*
* @param persistence The {@link Persistence} implementation which will create a concurrent {@link java.util.Set}
* in which objects added to the indexed collection will be stored, and which will provide
* access to the underlying storage of indexes.
* @param concurrencyLevel The estimated number of concurrently updating threads
*/
public <A extends Comparable<A>> ObjectLockingIndexedCollection(Persistence<O, A> persistence, int concurrencyLevel) {
super(persistence);
this.stripedLock = new StripedLock(concurrencyLevel);
}
static class StripedLock {
final int concurrencyLevel;
final ReentrantLock[] locks;
StripedLock(int concurrencyLevel) {
this.concurrencyLevel = concurrencyLevel;
this.locks = new ReentrantLock[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++) {
locks[i] = new ReentrantLock();
}
}
ReentrantLock getLockForObject(Object object) {
int hashCode = object.hashCode();
return locks[Math.abs(hashCode % concurrencyLevel)];
}
}
// ----------- Collection Mutator Methods -------------
/**
* {@inheritDoc}
*/
@Override
public CloseableIterator<O> iterator() {
return new CloseableIterator<O>() {
final QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
private final CloseableIterator<O> collectionIterator = objectStore.iterator(queryOptions);
boolean autoClosed = false;
@Override
public boolean hasNext() {
boolean hasNext = collectionIterator.hasNext();
if (!hasNext) {
close();
autoClosed = true;
}
return hasNext;
}
private O currentObject = null;
@Override
public O next() {
O next = collectionIterator.next();
currentObject = next;
return next;
}
@Override
public void remove() {
if (currentObject == null) {
throw new IllegalStateException();
}
Lock lock = stripedLock.getLockForObject(currentObject);
lock.lock();
try {
// Handle an edge case where we might have retrieved the last object and called close() automatically,
// but then the application calls remove() so we have to reopen request-scope resources temporarily
// to remove the last object...
if (autoClosed) {
ObjectLockingIndexedCollection.this.remove(currentObject); // reopens resources temporarily
}
else {
doRemoveAll(Collections.singleton(currentObject), queryOptions); // uses existing resources
}
currentObject = null;
}
finally {
lock.unlock();
}
}
@Override
public void close() {
CloseableRequestResources.closeQuietly(collectionIterator);
closeRequestScopeResourcesIfNecessary(queryOptions);
}
};
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(O o) {
Lock lock = stripedLock.getLockForObject(o);
lock.lock();
try {
return super.add(o);
}
finally {
lock.unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object object) {
Lock lock = stripedLock.getLockForObject(object);
lock.lock();
try {
return super.remove(object);
}
finally {
lock.unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(Collection<? extends O> c) {
boolean modified = false;
for (O object : c) {
modified = add(object) || modified;
}
return modified;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object object : c) {
modified = remove(object) || modified;
}
return modified;
}
/**
* {@inheritDoc}
*/
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(c); // Delegates to superclass implementation, which delegates to iterator() method above
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void clear() {
super.clear();
}
}
| 9,814 | 36.75 | 122 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/IndexedCollection.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;
import com.googlecode.cqengine.engine.QueryEngine;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.metadata.MetadataEngine;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.AbstractCollection;
import java.util.Set;
/**
* A Java collection which can maintain indexes on the objects it contains, allowing objects matching complex queries
* to be retrieved with very low latency.
* <p/>
* The {@link #retrieve(com.googlecode.cqengine.query.Query)} methods accept a {@link com.googlecode.cqengine.query.Query}
* and return a {@link com.googlecode.cqengine.resultset.ResultSet} of objects matching that query.
* <p/>
* The {@link #addIndex(com.googlecode.cqengine.index.Index)} methods allowing indexes to be added to the collection to
* improve query performance.
* <p/>
* Several implementations of this interface exist each with different performance or transaction isolation
* characteristics. See documentation on the implementations for further details.
*
* @author Niall Gallagher
*/
public interface IndexedCollection<O> extends Set<O>, QueryEngine<O> {
/**
* Shortcut for calling {@link #retrieve(Query, QueryOptions)} without supplying any query options.
*/
ResultSet<O> retrieve(Query<O> query);
/**
* {@inheritDoc}
*/
@Override
ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions);
/**
* Removes or adds objects to/from the collection and indexes in bulk.
* <p/>
* Note that although this method accepts either {@code Iterable}s or {@code Collection}s for its
* {@code objectsToRemove} and {@code objectsToAdd} parameters, there are pros and cons of each:
* <ul>
* <li>
* If an {@code Iterable} is supplied, updates to indexes will be applied in a streaming fashion. This
* allows the application and CQEngine to avoid buffering many updates in memory as a batch, but requires
* more round trips to update indexes, which might hurt performance for indexes where making many round
* trips is expensive. This is typically fine for on-heap indexes, but less so for off-heap or on-disk
* indexes.
* </li>
* <li>
* If a {@code Collection} is supplied, updates to indexes will be applied as a single batch. This might
* improve performance for indexes where making many round trips is expensive. Ordinarily this implies that
* the application needs to assemble a batch into a collection before calling this method. However for
* applications where the source of updates is computed lazily or originates from a stream, but yet where
* it is desirable to apply the updates as a batch anyway, the application can wrap the stream as a lazy
* collection (extend {@link AbstractCollection}) so that CQEngine will behave as above.
* <ul><li>
* Note also that some off-heap and on-disk indexes support a fast "bulk import" feature which can be used
* in conjunction with this. For details on how to perform a bulk import, see
* {@link com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags#BULK_IMPORT}.
* </li></ul>
* </li>
* </ul>
*
* @param objectsToRemove The objects to remove from the collection
* @param objectsToAdd The objects to add to the collection
* @return True if the collection was modified as a result, false if it was not
*/
boolean update(Iterable<O> objectsToRemove, Iterable<O> objectsToAdd);
/**
* Removes or adds objects to/from the collection and indexes in bulk.
* <p/>
* Note that although this method accepts either {@code Iterable}s or {@code Collection}s for its
* {@code objectsToRemove} and {@code objectsToAdd} parameters, there are pros and cons of each:
* <ul>
* <li>
* If an {@code Iterable} is supplied, updates to indexes will be applied in a streaming fashion. This
* allows the application and CQEngine to avoid buffering many updates in memory as a batch, but requires
* more round trips to update indexes, which might hurt performance for indexes where making many round
* trips is expensive. This is typically fine for on-heap indexes, but less so for off-heap or on-disk
* indexes.
* </li>
* <li>
* If a {@code Collection} is supplied, updates to indexes will be applied as a single batch. This might
* improve performance for indexes where making many round trips is expensive. Ordinarily this implies that
* the application needs to assemble a batch into a collection before calling this method. However for
* applications where the source of updates is computed lazily or originates from a stream, but yet where
* it is desirable to apply the updates as a batch anyway, the application can wrap the stream as a lazy
* collection (extend {@link AbstractCollection}) so that CQEngine will behave as above.
* <ul><li>
* Note also that some off-heap and on-disk indexes support a fast "bulk import" feature which can be used
* in conjunction with this. For details on how to perform a bulk import, see
* {@link com.googlecode.cqengine.index.sqlite.support.SQLiteIndexFlags#BULK_IMPORT}.
* </li></ul>
* </li>
* </ul>
*
* @param objectsToRemove The objects to remove from the collection
* @param objectsToAdd The objects to add to the collection
* @param queryOptions Optional parameters for the update
* @return True if the collection was modified as a result, false if it was not
*/
boolean update(Iterable<O> objectsToRemove, Iterable<O> objectsToAdd, QueryOptions queryOptions);
/**
* @see #addIndex(Index, QueryOptions)
*/
void addIndex(Index<O> index);
/**
* {@inheritDoc}
*/
@Override
void addIndex(Index<O> index, QueryOptions queryOptions);
/**
* @see #removeIndex(Index, QueryOptions)
*/
void removeIndex(Index<O> index);
/**
* {@inheritDoc}
*/
@Override
void removeIndex(Index<O> index, QueryOptions queryOptions);
/**
* Returns the {@link Persistence} used by the the collection.
*
* @return The {@link Persistence} used by the the collection
*/
Persistence<O, ?> getPersistence();
/**
* Returns the {@link MetadataEngine}, which can retrieve metadata and statistics from indexes
* on the distribution of attribute values in the collection.
*/
MetadataEngine<O> getMetadataEngine();
}
| 7,608 | 46.26087 | 122 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/AttributeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.engine.ModificationListener;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* @author Niall Gallagher
*/
public interface AttributeIndex<A, O> extends Index<O> {
/**
* Returns the attribute indexed by this index.
*
* @return The attribute indexed by this index
*/
Attribute<O, A> getAttribute();
}
| 1,110 | 30.742857 | 75 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/Index.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index;
import com.googlecode.cqengine.engine.ModificationListener;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
/**
* @author Niall Gallagher
*/
public interface Index<O> extends ModificationListener<O> {
/**
* Indicates if objects can be added to or removed from the index after the index has been built.
*
* @return True if objects can be added to or removed from the index after the index has been built, false if
* the index cannot be modified after it is built
*/
public boolean isMutable();
/**
* Indicates if the index can perform retrievals for the type of query supplied.
*
*
* @param query A query to check
* @param queryOptions Optional parameters for the query
* @return True if the index can perform retrievals for the type of query supplied, false if it does not
* support this type of query
*/
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions);
/**
* Indicates if the index is quantized, using a {@link com.googlecode.cqengine.quantizer.Quantizer}.
* @return True if the index is quantized, false if not.
*/
public boolean isQuantized();
/**
* Returns a {@link ResultSet} which when iterated will return objects from the index matching the query
* supplied.
* <p/>
* Usually {@code ResultSet}s are <i>lazy</i> which means that they don't actually do any work, or encapsulate or
* <i>materialize</i> matching objects, but rather they encapsulate logic to fetch matching objects from the index
* on-the-fly as the application iterates through the {@code ResultSet}.
*
* @param query An object which specifies some restriction on an attribute of an object
* @param queryOptions Optional parameters for the query
* @return A set of objects with attributes matching the restriction imposed by the query
* @throws IllegalArgumentException if the index does not support the given query
* @see #supportsQuery(Query, QueryOptions)
*/
public ResultSet<O> retrieve(Query<O> query, QueryOptions queryOptions);
/**
* Returns the effective index, which Persistence objects will use to determine the identity of the index making
* persistence requests. Most Index implementations will typically return a reference to themselves ('this').
* However in advanced cases when one index delegates to another, the implementation of the wrapping index will
* create a subclass the delegate index, and override this method in the delegate index so that when the delegate
* index interacts with the persistence, it will identify itself as the outer or "effective" index.
*
* @return The effective index, in the case that this index is wrapped by another index.
*/
public Index<O> getEffectiveIndex();
}
| 3,599 | 43.444444 | 118 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/hash/HashIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.hash;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.cqengine.TransactionalIndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.index.unique.UniqueIndex;
import com.googlecode.cqengine.quantizer.Quantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.Has;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.QuantizedResultSet;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
/**
* An index backed by a {@link ConcurrentHashMap}.
* <p/>
* Supports query types:
* <ul>
* <li>{@link Equal}</li>
* <li>{@link In}</li>
* <li>{@link Has}</li>
* </ul>
* </ul>
* The constructor of this index accepts {@link Factory} objects, from which it will create the map and value sets it
* uses internally. This allows the application to "tune" the construction parameters of these maps/sets,
* by supplying custom factories.
* For default settings, supply {@link DefaultIndexMapFactory} and {@link DefaultValueSetFactory}.
*
* @author Niall Gallagher
*/
public class HashIndex<A, O> extends AbstractMapBasedAttributeIndex<A, O, ConcurrentMap<A, StoredResultSet<O>>> implements KeyStatisticsAttributeIndex<A, O>, OnHeapTypeIndex {
protected static final int INDEX_RETRIEVAL_COST = 30;
/**
* Package-private constructor, used by static factory methods. Creates a new HashIndex initialized to index the
* supplied attribute.
*
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built
*/
protected HashIndex(Factory<ConcurrentMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute) {
super(indexMapFactory, valueSetFactory, attribute, new HashSet<Class<? extends Query>>() {{
add(Equal.class);
add(In.class);
add(Has.class);
}});
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
*
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions);
}
else if (queryClass.equals(In.class)) {
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions);
}
else if (queryClass.equals(Has.class)) {
return deduplicateIfNecessary(indexMap.values(), query, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? Collections.<O>emptySet().iterator() : filterForQuantization(rs, equal, queryOptions).iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs != null && filterForQuantization(rs, equal, queryOptions).contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? 0 : filterForQuantization(rs, equal, queryOptions).size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = indexMap.get(getQuantizedValue(equal.getValue()));
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
// ---------- Hook methods which can be overridden by subclasses using a Quantizer ----------
/**
* A no-op method which can be overridden by a subclass to return a {@link ResultSet} which filters objects from the
* given {@link ResultSet}, to return only those objects matching the query, for the case that the index is using a
* {@link com.googlecode.cqengine.quantizer.Quantizer}.
* <p/>
* <b>This default implementation simply returns the given {@link ResultSet} unmodified.</b>
*
* @param storedResultSet A {@link com.googlecode.cqengine.resultset.ResultSet} stored against a quantized key in the index
* @param query The query against which results should be matched
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} which filters objects from the given {@link ResultSet},
* to return only those objects matching the query
*/
protected ResultSet<O> filterForQuantization(ResultSet<O> storedResultSet, Query<O> query, QueryOptions queryOptions) {
return storedResultSet;
}
@Override
public Integer getCountForKey(A key, QueryOptions queryOptions) {
return super.getCountForKey(key);
}
@Override
public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions) {
return super.getDistinctKeys();
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return super.getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return super.getStatisticsForDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions) {
return super.getKeysAndValues();
}
// ---------- Static factory methods to create HashIndexes ----------
/**
* Creates a new {@link HashIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link HashIndex} on this attribute
*/
public static <A, O> HashIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return onAttribute(new DefaultIndexMapFactory<A, O>(), new DefaultValueSetFactory<O>(), attribute);
}
/**
* Creates a new {@link HashIndex} on the specified attribute, where the attribute is expected to uniquely identify
* an object in the collection <i>most of the time</i>.
* <p/>
* This can be used as a less-strict alternative to {@link UniqueIndex}, especially when used with a
* {@link TransactionalIndexedCollection} which implements an MVCC algorithm. The MVCC algorithm sometimes needs
* to store multiple versions of the same object in the collection at the same time, which would violate the
* constraints of that index.
* <p/>
* This configures the {@link HashIndex} with {@link CompactValueSetFactory}, and as such it will use less memory
* than the default configuration of {@link HashIndex}. However it will use somewhat more memory than
* {@link UniqueIndex}.
*
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link HashIndex} on this attribute
*/
public static <A, O> HashIndex<A, O> onSemiUniqueAttribute(Attribute<O, A> attribute) {
return onAttribute(new DefaultIndexMapFactory<A, O>(), new CompactValueSetFactory<O>(), attribute);
}
/**
* Creates a new {@link HashIndex} on the specified attribute.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link HashIndex} on this attribute
*/
public static <A, O> HashIndex<A, O> onAttribute(Factory<ConcurrentMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, A> attribute) {
return new HashIndex<A, O>(indexMapFactory, valueSetFactory, attribute);
}
/**
* Creates a {@link HashIndex} on the given attribute using the given {@link Quantizer}.
* <p/>
* @param quantizer A {@link Quantizer} to use in this index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link HashIndex} on the given attribute using the given {@link Quantizer}
*/
public static <A, O> HashIndex<A, O> withQuantizerOnAttribute(final Quantizer<A> quantizer, Attribute<O, A> attribute) {
return withQuantizerOnAttribute(new DefaultIndexMapFactory<A, O>(), new DefaultValueSetFactory<O>(), quantizer, attribute);
}
/**
* Creates a {@link HashIndex} on the given attribute using the given {@link Quantizer}.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param quantizer A {@link Quantizer} to use in this index
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link HashIndex} on the given attribute using the given {@link Quantizer}
*/
public static <A, O> HashIndex<A, O> withQuantizerOnAttribute(Factory<ConcurrentMap<A, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, final Quantizer<A> quantizer, Attribute<O, A> attribute) {
return new HashIndex<A, O>(indexMapFactory, valueSetFactory, attribute) {
// ---------- Override the hook methods related to Quantizer ----------
@Override
protected ResultSet<O> filterForQuantization(ResultSet<O> resultSet, final Query<O> query, QueryOptions queryOptions) {
return new QuantizedResultSet<O>(resultSet, query, queryOptions);
}
@Override
protected A getQuantizedValue(A attributeValue) {
return quantizer.getQuantizedValue(attributeValue);
}
@Override
public boolean isQuantized() {
return true;
}
};
}
/**
* Creates an index map using default settings.
*/
public static class DefaultIndexMapFactory<A, O> implements Factory<ConcurrentMap<A, StoredResultSet<O>>> {
@Override
public ConcurrentMap<A, StoredResultSet<O>> create() {
return new ConcurrentHashMap<A, StoredResultSet<O>>();
}
}
/**
* Creates a value set using default settings.
*/
public static class DefaultValueSetFactory<O> implements Factory<StoredResultSet<O>> {
@Override
public StoredResultSet<O> create() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
}
/**
* Creates a value set which is tuned to reduce memory overhead, with an expectation that only a single or
* a very small number of object(s) will be stored in each bucket.
* <p/>
* Additionally, this is tuned with the <b>expectation of low concurrency for writes</b>. Concurrent writes are
* safe, but they might block each other.
*/
public static class CompactValueSetFactory<O> implements Factory<StoredResultSet<O>> {
@Override
public StoredResultSet<O> create() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>( 1, 1.0F, 1)));
}
}
}
| 15,557 | 42.458101 | 232 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/radixinverted/InvertedRadixTreeIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.radixinverted;
import static com.googlecode.cqengine.index.support.IndexSupport.deduplicateIfNecessary;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import com.googlecode.concurrenttrees.common.LazyIterator;
import com.googlecode.concurrenttrees.radix.node.NodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radixinverted.ConcurrentInvertedRadixTree;
import com.googlecode.concurrenttrees.radixinverted.InvertedRadixTree;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.AbstractAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.DeduplicationOption;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.Equal;
import com.googlecode.cqengine.query.simple.In;
import com.googlecode.cqengine.query.comparative.LongestPrefix;
import com.googlecode.cqengine.query.simple.StringIsContainedIn;
import com.googlecode.cqengine.query.simple.StringIsPrefixOf;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.connective.ResultSetUnion;
import com.googlecode.cqengine.resultset.connective.ResultSetUnionAll;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
/**
* An index backed by a {@link ConcurrentInvertedRadixTree}.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link Equal}
* </li>
* <li>
* {@link StringIsContainedIn}
* </li>
* </ul>
*
* @author Niall Gallagher
*/
public class InvertedRadixTreeIndex<A extends CharSequence, O> extends AbstractAttributeIndex<A, O> implements OnHeapTypeIndex {
private static final int INDEX_RETRIEVAL_COST = 52;
final NodeFactory nodeFactory;
volatile InvertedRadixTree<StoredResultSet<O>> tree;
/**
* Package-private constructor, used by static factory methods.
*/
protected InvertedRadixTreeIndex(Attribute<O, A> attribute) {
this(attribute, new DefaultCharArrayNodeFactory());
}
/**
* Package-private constructor, used by static factory methods.
*/
protected InvertedRadixTreeIndex(Attribute<O, A> attribute, NodeFactory nodeFactory) {
super(attribute, new HashSet<Class<? extends Query>>() {/**
*
*/
private static final long serialVersionUID = 1L;
{
add(Equal.class);
add(In.class);
add(StringIsContainedIn.class);
add(LongestPrefix.class);
add(StringIsPrefixOf.class);
}});
this.nodeFactory = nodeFactory;
this.tree = new ConcurrentInvertedRadixTree<StoredResultSet<O>>(nodeFactory);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public boolean isQuantized() {
return false;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
final InvertedRadixTree<StoredResultSet<O>> tree = this.tree;
Class<?> queryClass = query.getClass();
if (queryClass.equals(Equal.class)) {
@SuppressWarnings("unchecked")
Equal<O, A> equal = (Equal<O, A>) query;
return retrieveEqual(equal, queryOptions, tree);
}
else if (queryClass.equals(In.class)){
@SuppressWarnings("unchecked")
In<O, A> in = (In<O, A>) query;
return retrieveIn(in, queryOptions, tree);
}
else if (queryClass.equals(StringIsContainedIn.class)) {
@SuppressWarnings("unchecked")
final StringIsContainedIn<O, A> stringIsContainedIn = (StringIsContainedIn<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContainedIn(stringIsContainedIn.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.iterator();
}
@Override
public boolean contains(O object) {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContainedIn(stringIsContainedIn.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContainedIn(stringIsContainedIn.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysContainedIn(stringIsContainedIn.getValue());
ResultSet<O> rs = unionResultSets(resultSets, query, queryOptions);
return rs.getMergeCost();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
} else if (queryClass.equals(LongestPrefix.class)) {
@SuppressWarnings("unchecked")
final LongestPrefix<O, A> longestPrefix = (LongestPrefix<O, A>) query;
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = tree.getValueForLongestKeyPrefixing(longestPrefix.getValue());
return rs == null ? Collections.<O>emptySet().iterator() : rs.iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = tree.getValueForLongestKeyPrefixing(longestPrefix.getValue());
return rs != null && rs.contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
ResultSet<O> rs = tree.getValueForLongestKeyPrefixing(longestPrefix.getValue());
return rs != null ? rs.getMergeCost() : 0;
}
@Override
public int size() {
ResultSet<O> rs = tree.getValueForLongestKeyPrefixing(longestPrefix.getValue());
return rs != null ? rs.size() : 0;
}
@Override
public void close() {
// No-OP
}
};
} else if (queryClass.equals(StringIsPrefixOf.class)) {
@SuppressWarnings("unchecked")
final StringIsPrefixOf<O, A> isPrefixOf = (StringIsPrefixOf<O, A>) query;
return new ResultSet<O>() {
private ResultSet<O> getRS() {
Iterable<? extends ResultSet<O>> resultSets = tree.getValuesForKeysPrefixing(isPrefixOf.getValue());
return unionResultSets(resultSets, query, queryOptions);
}
@Override
public Iterator<O> iterator() {
return getRS().iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = getRS();
if(null != rs) {
return rs.contains(object);
}
return false;
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
ResultSet<O> rs = getRS();
if(null != rs) {
return rs.getMergeCost();
}
return 0;
}
@Override
public int size() {
ResultSet<O> rs = getRS();
if(null != rs) {
return rs.size();
}
return 0;
}
@Override
public void close() {
// No-OP
}
};
} else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final InvertedRadixTree<StoredResultSet<O>> tree) {
// Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
@Override
public Iterator<ResultSet<O>> iterator() {
return new LazyIterator<ResultSet<O>>() {
final Iterator<A> values = in.getValues().iterator();
@Override
protected ResultSet<O> computeNext() {
if (values.hasNext()){
return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
}else{
return endOfData();
}
}
};
}
};
return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
protected ResultSet<O> retrieveEqual(final Equal<O, A> equal, final QueryOptions queryOptions, final InvertedRadixTree<StoredResultSet<O>> tree) {
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? Collections.<O>emptySet().iterator() : rs.iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs != null && rs.contains(object);
}
@Override
public boolean matches(O object) {
return equal.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = tree.getValueForExactKey(equal.getValue());
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return equal;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
/**
* If a query option specifying logical deduplication was supplied, wrap the given result sets in
* {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
* <p/>
* An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
* {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
*
* @param results Provides the result sets to union
* @param query The query for which the union is being constructed
* @param queryOptions Specifies whether or not logical deduplication is required
* @return A union view over the given result sets
*/
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
if (DeduplicationOption.isLogicalElimination(queryOptions)
&& !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
return new ResultSetUnion<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
else {
return new ResultSetUnionAll<O>(results, query, queryOptions) {
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
};
}
}
/**
* @return A {@link StoredSetBasedResultSet} based on a set backed by {@link ConcurrentHashMap}, as created via
* {@link java.util.Collections#newSetFromMap(java.util.Map)}
*/
public StoredResultSet<O> createValueSet() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final InvertedRadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
// Look up StoredResultSet for the value...
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
// No StoredResultSet, create and add one...
valueSet = createValueSet();
StoredResultSet<O> existingValueSet = tree.putIfAbsent(attributeValue, valueSet);
if (existingValueSet != null) {
// Another thread won race to add new value set, use that one...
valueSet = existingValueSet;
}
}
// Add the object to the StoredResultSet for this value...
modified |= valueSet.add(object);
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
try {
boolean modified = false;
final InvertedRadixTree<StoredResultSet<O>> tree = this.tree;
for (O object : objectSet) {
Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
for (A attributeValue : attributeValues) {
StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
if (valueSet == null) {
continue;
}
modified |= valueSet.remove(object);
if (valueSet.isEmpty()) {
tree.remove(attributeValue);
}
}
}
return modified;
}
finally {
objectSet.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {
addAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions);
}
/**
* This is a no-op for this type of index.
* @param queryOptions Optional parameters for the update
*/
@Override
public void destroy(QueryOptions queryOptions) {
// No-op
}
/**
* {@inheritDoc}
*/
@Override
public void clear(QueryOptions queryOptions) {
this.tree = new ConcurrentInvertedRadixTree<StoredResultSet<O>>(new DefaultCharArrayNodeFactory());
}
// ---------- Static factory methods to create InvertedRadixTreeIndexes ----------
/**
* Creates a new {@link InvertedRadixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param <O> The type of the object containing the attribute
* @return A {@link InvertedRadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> InvertedRadixTreeIndex<A, O> onAttribute(Attribute<O, A> attribute) {
return new InvertedRadixTreeIndex<A, O>(attribute);
}
/**
* Creates a new {@link InvertedRadixTreeIndex} on the specified attribute.
* <p/>
* @param attribute The attribute on which the index will be built
* @param nodeFactory The NodeFactory to be used by the tree
* @param <O> The type of the object containing the attribute
* @return A {@link InvertedRadixTreeIndex} on this attribute
*/
public static <A extends CharSequence, O> InvertedRadixTreeIndex<A, O> onAttributeUsingNodeFactory(Attribute<O, A> attribute, NodeFactory nodeFactory) {
return new InvertedRadixTreeIndex<A, O>(attribute, nodeFactory);
}
}
| 20,317 | 37.774809 | 156 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/compound/CompoundIndex.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.compound;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.support.*;
import com.googlecode.cqengine.index.compound.support.CompoundAttribute;
import com.googlecode.cqengine.index.compound.support.CompoundQuery;
import com.googlecode.cqengine.index.compound.support.CompoundValueTuple;
import com.googlecode.cqengine.index.support.indextype.OnHeapTypeIndex;
import com.googlecode.cqengine.quantizer.Quantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.QuantizedResultSet;
import com.googlecode.cqengine.resultset.stored.StoredResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* An index backed by a {@link java.util.concurrent.ConcurrentHashMap} which indexes {@link CompoundAttribute}s,
* storing {@link CompoundValueTuple} objects as keys.
* <p/>
* Supports query types:
* <ul>
* <li>
* {@link com.googlecode.cqengine.index.compound.support.CompoundQuery}
* </li>
* </ul>
* The constructor of this index accepts {@link Factory} objects, from which it will create the map and value sets it
* uses internally. This allows the application to "tune" the construction parameters of these maps/sets,
* by supplying custom factories.
* For default settings, supply {@link DefaultIndexMapFactory} and {@link DefaultValueSetFactory}.
*
* @author Niall Gallagher
*/
public class CompoundIndex<O> extends AbstractMapBasedAttributeIndex<CompoundValueTuple<O>, O, ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> implements KeyStatisticsAttributeIndex<CompoundValueTuple<O>, O>, OnHeapTypeIndex {
protected static final int INDEX_RETRIEVAL_COST = 20;
protected final CompoundAttribute<O> attribute;
/**
* Package-private constructor, used by static factory methods. Creates a new HashIndex initialized to index the
* supplied attribute.
*
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attribute The attribute on which the index will be built
*/
protected CompoundIndex(Factory<ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, CompoundAttribute<O> attribute) {
// We can supply the superclass constructor with an empty set of supported queries,
// because we implement/override supportsQuery() in this class instead...
super(indexMapFactory, valueSetFactory, attribute, Collections.<Class<? extends Query>>emptySet());
this.attribute = attribute;
}
/**
* Returns true if the given {@link Query} is based on the same list of attributes as the
* {@link CompoundAttribute} on which this compound index is based.
*
* @param query A {@link Query} to test
* @return True if the given {@link Query} is based on the same list of attributes as the
* {@link CompoundAttribute} on which this compound index is based, otherwise false
*/
@Override
public boolean supportsQuery(Query<O> query, QueryOptions queryOptions) {
if (query instanceof CompoundQuery) {
CompoundQuery<O> compoundQuery = (CompoundQuery<O>) query;
return attribute.equals(compoundQuery.getCompoundAttribute());
}
return false;
}
@Override
public CompoundAttribute<O> getAttribute() {
return attribute;
}
/**
* {@inheritDoc}
* <p/>
* This index is mutable.
*
* @return true
*/
@Override
public boolean isMutable() {
return true;
}
@Override
public Index<O> getEffectiveIndex() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
Class<?> queryClass = query.getClass();
if (queryClass.equals(CompoundQuery.class)) {
final CompoundQuery<O> compoundQuery = (CompoundQuery<O>) query;
final CompoundValueTuple<O> valueTuple = compoundQuery.getCompoundValueTuple();
return new ResultSet<O>() {
@Override
public Iterator<O> iterator() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(valueTuple));
return rs == null ? Collections.<O>emptySet().iterator() : filterForQuantization(rs, compoundQuery, queryOptions).iterator();
}
@Override
public boolean contains(O object) {
ResultSet<O> rs = indexMap.get(getQuantizedValue(valueTuple));
return rs != null && filterForQuantization(rs, compoundQuery, queryOptions).contains(object);
}
@Override
public boolean matches(O object) {
return query.matches(object, queryOptions);
}
@Override
public int size() {
ResultSet<O> rs = indexMap.get(getQuantizedValue(valueTuple));
return rs == null ? 0 : filterForQuantization(rs, compoundQuery, queryOptions).size();
}
@Override
public int getRetrievalCost() {
return INDEX_RETRIEVAL_COST;
}
@Override
public int getMergeCost() {
// Return size of entire stored set as merge cost...
ResultSet<O> rs = indexMap.get(getQuantizedValue(valueTuple));
return rs == null ? 0 : rs.size();
}
@Override
public void close() {
// No op.
}
@Override
public Query<O> getQuery() {
return query;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
};
}
else {
throw new IllegalArgumentException("Unsupported query: " + query);
}
}
@Override
public CloseableIterable<CompoundValueTuple<O>> getDistinctKeys(QueryOptions queryOptions) {
return super.getDistinctKeys();
}
@Override
public Integer getCountForKey(CompoundValueTuple<O> key, QueryOptions queryOptions) {
return super.getCountForKey(key);
}
@Override
public Integer getCountOfDistinctKeys(QueryOptions queryOptions) {
return super.getCountOfDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyStatistics<CompoundValueTuple<O>>> getStatisticsForDistinctKeys(QueryOptions queryOptions) {
return super.getStatisticsForDistinctKeys(queryOptions);
}
@Override
public CloseableIterable<KeyValue<CompoundValueTuple<O>, O>> getKeysAndValues(QueryOptions queryOptions) {
return super.getKeysAndValues();
}
// ---------- Hook methods which can be overridden by subclasses using a Quantizer ----------
/**
* A no-op method which can be overridden by a subclass to return a {@link ResultSet} which filters objects from the
* given {@link ResultSet}, to return only those objects matching the query, for the case that the index is using a
* {@link com.googlecode.cqengine.quantizer.Quantizer}.
* <p/>
* <b>This default implementation simply returns the given {@link ResultSet} unmodified.</b>
*
* @param storedResultSet A {@link com.googlecode.cqengine.resultset.ResultSet} stored against a quantized key in the index
* @param query The query against which results should be matched
* @param queryOptions Optional parameters for the query
* @return A {@link ResultSet} which filters objects from the given {@link ResultSet},
* to return only those objects matching the query
*/
protected ResultSet<O> filterForQuantization(ResultSet<O> storedResultSet, Query<O> query, QueryOptions queryOptions) {
return storedResultSet;
}
/**
* Creates a new {@link CompoundIndex} on the given combination of attributes.
* <p/>
* @param attributes The combination of simple attributes on which index will be built
* @param <O> The type of the object containing the attributes
* @return A {@link CompoundIndex} based on these attributes
*/
// TODO: add overloaded non-varargs versions of this method to prevent unchecked warnings pre JDK 7?
public static <O> CompoundIndex<O> onAttributes(Attribute<O, ?>... attributes) {
return onAttributes(new DefaultIndexMapFactory<O>(), new DefaultValueSetFactory<O>(), attributes);
}
/**
* Creates a new {@link CompoundIndex} on the given combination of attributes.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attributes The combination of simple attributes on which index will be built
* @param <O> The type of the object containing the attributes
* @return A {@link CompoundIndex} based on these attributes
*/
// TODO: add overloaded non-varargs versions of this method to prevent unchecked warnings pre JDK 7?
public static <O> CompoundIndex<O> onAttributes(Factory<ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, Attribute<O, ?>... attributes) {
List<Attribute<O, ?>> attributeList = Arrays.asList(attributes);
CompoundAttribute<O> compoundAttribute = new CompoundAttribute<O>(attributeList);
return new CompoundIndex<O>(indexMapFactory, valueSetFactory, compoundAttribute);
}
/**
* Creates a new {@link CompoundIndex} using the given {@link Quantizer} on the given combination of attributes.
* <p/>
* @param attributes The combination of simple attributes on which index will be built
* @param quantizer A {@link Quantizer} to use in this index
* @param <O> The type of the object containing the attributes
* @return A {@link CompoundIndex} based on these attributes
*/
public static <O> CompoundIndex<O> withQuantizerOnAttributes(final Quantizer<CompoundValueTuple<O>> quantizer, Attribute<O, ?>... attributes) {
return withQuantizerOnAttributes(new DefaultIndexMapFactory<O>(), new DefaultValueSetFactory<O>(), quantizer, attributes);
}
/**
* Creates a new {@link CompoundIndex} using the given {@link Quantizer} on the given combination of attributes.
* <p/>
* @param indexMapFactory A factory used to create the main map-based data structure used by the index
* @param valueSetFactory A factory used to create sets to store values in the index
* @param attributes The combination of simple attributes on which index will be built
* @param quantizer A {@link Quantizer} to use in this index
* @param <O> The type of the object containing the attributes
* @return A {@link CompoundIndex} based on these attributes
*/
public static <O> CompoundIndex<O> withQuantizerOnAttributes(Factory<ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, final Quantizer<CompoundValueTuple<O>> quantizer, Attribute<O, ?>... attributes) {
List<Attribute<O, ?>> attributeList = Arrays.asList(attributes);
CompoundAttribute<O> compoundAttribute = new CompoundAttribute<O>(attributeList);
return new CompoundIndex<O>(indexMapFactory, valueSetFactory, compoundAttribute) {
// ---------- Override the hook methods related to Quantizer ----------
@Override
protected ResultSet<O> filterForQuantization(ResultSet<O> resultSet, final Query<O> query, QueryOptions queryOptions) {
return new QuantizedResultSet<O>(resultSet, query, queryOptions);
}
@Override
protected CompoundValueTuple<O> getQuantizedValue(CompoundValueTuple<O> attributeValue) {
return quantizer.getQuantizedValue(attributeValue);
}
@Override
public boolean isQuantized() {
return true;
}
};
}
/**
* Creates an index map using default settings.
*/
public static class DefaultIndexMapFactory<O> implements Factory<ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> {
@Override
public ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>> create() {
return new ConcurrentHashMap<CompoundValueTuple<O>, StoredResultSet<O>>();
}
}
/**
* Creates a value set using default settings.
*/
public static class DefaultValueSetFactory<O> implements Factory<StoredResultSet<O>> {
@Override
public StoredResultSet<O> create() {
return new StoredSetBasedResultSet<O>(Collections.<O>newSetFromMap(new ConcurrentHashMap<O, Boolean>()));
}
}
}
| 14,171 | 44.716129 | 275 | java |
cqengine | cqengine-master/code/src/main/java/com/googlecode/cqengine/index/compound/support/CompoundValueTuple.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.compound.support;
import com.googlecode.cqengine.attribute.Attribute;
import java.util.Collections;
import java.util.List;
/**
* A tuple (ordered list) of values, extracted from the fields of an object, according to, and in the same order as, the
* {@link Attribute}s encapsulated in a {@link CompoundAttribute}.
* <p/>
* The combination of values encapsulated in objects of this type are used as keys in compound indexes. This object
* implements {@link Object#equals(Object)} and {@link Object#hashCode()} where the hash code is calculated from the
* combination of values.
*
* @author Niall Gallagher
*/
public class CompoundValueTuple<O> {
private final List<?> attributeValues;
private final int hashCode;
public CompoundValueTuple(List<?> attributeValues) {
this.attributeValues = attributeValues;
this.hashCode = attributeValues.hashCode();
}
public Iterable<Object> getAttributeValues() {
return Collections.unmodifiableList(attributeValues);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CompoundValueTuple)) return false;
CompoundValueTuple that = (CompoundValueTuple) o;
if (hashCode != that.hashCode) return false;
if (!attributeValues.equals(that.attributeValues)) return false;
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return "CompoundValueTuple{" +
"attributeValues=" + attributeValues +
", hashCode=" + hashCode +
'}';
}
}
| 2,309 | 30.643836 | 120 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.