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 |
---|---|---|---|---|---|---|
tquery | tquery-master/src/main/java/joliex/tquery/engine/UnwindService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.unwind.UnwindQuery;
public final class UnwindService {
static Value unwind( Value request ) throws FaultException{
return UnwindQuery.unwind( request );
}
}
| 2,072 | 56.583333 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/LookupService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.lookup.LookupQuery;
public class LookupService {
static Value lookup( Value request ) throws FaultException {
return LookupQuery.lookup( request );
}
}
| 2,066 | 56.416667 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/MatchService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.match.MatchQuery;
public class MatchService {
static Value match( Value request ) throws FaultException {
return MatchQuery.match( request );
}
}
| 2,062 | 54.756757 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/PipelineService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.pipeline.PipelineQuery;
public class PipelineService {
static Value pipeline( Value request ) throws FaultException {
long start = System.currentTimeMillis();
Value response = PipelineQuery.pipeline( request );
response.setFirstChild( "queryTime", ( System.currentTimeMillis() - start ) );
return response;
}
}
| 2,233 | 54.85 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/TQueryService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
public class TQueryService extends JavaService {
public Value group( Value request ) throws FaultException {
return GroupService.group( request );
}
public Value lookup( Value request ) throws FaultException {
return LookupService.lookup( request );
}
public Value match( Value request ) throws FaultException {
return MatchService.match( request );
}
public Value project( Value request ) throws FaultException {
return ProjectService.project( request );
}
public Value unwind( Value request ) throws FaultException {
return UnwindService.unwind( request );
}
public Value pipeline( Value request ) throws FaultException {
return PipelineService.pipeline( request );
}
}
| 2,620 | 44.982456 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/pipeline/PipelineQuery.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.pipeline;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.LookupService;
import joliex.tquery.engine.MatchService;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.group.GroupQuery;
import joliex.tquery.engine.lookup.LookupQuery;
import joliex.tquery.engine.match.MatchQuery;
import joliex.tquery.engine.project.ProjectQuery;
import joliex.tquery.engine.unwind.UnwindQuery;
import java.util.Optional;
public final class PipelineQuery {
private static class RequestType {
private static final String DATA = "data";
private static final String PIPELINE = "pipeline";
private static class QuerySubtype {
private static final String MATCH_QUERY = "matchQuery";
private static final String PROJECT_QUERY = "projectQuery";
private static final String UNWIND_QUERY = "unwindQuery";
private static final String GROUP_QUERY = "groupQuery";
private static final String LOOKUP_QUERY = "lookupQuery";
}
}
private static final String QUERY = "query";
public static Value pipeline( Value pipelineRequest ) throws FaultException {
ValueVector pipeline = pipelineRequest.getChildren( RequestType.PIPELINE );
pipelineRequest.children().remove( "pipeline" );
for ( int i = 0; i < pipeline.size(); i++ ) {
Value stage = pipeline.get( i );
if ( stage.hasChildren( RequestType.QuerySubtype.MATCH_QUERY ) ) {
pipelineRequest.children().put( QUERY, stage.getChildren( RequestType.QuerySubtype.MATCH_QUERY ) );
Value response = MatchQuery.match( pipelineRequest );
pipelineRequest.children().put( RequestType.DATA, response.getChildren( TQueryExpression.ResponseType.RESULT ) );
} else if ( stage.hasChildren( RequestType.QuerySubtype.PROJECT_QUERY ) ) {
pipelineRequest.children().put( QUERY, stage.getChildren( RequestType.QuerySubtype.PROJECT_QUERY ) );
Value response = ProjectQuery.project( pipelineRequest );
pipelineRequest.children().put( RequestType.DATA, response.getChildren( TQueryExpression.ResponseType.RESULT ) );
} else if ( stage.hasChildren( RequestType.QuerySubtype.UNWIND_QUERY ) ) {
pipelineRequest.children().put( QUERY, stage.getChildren( RequestType.QuerySubtype.UNWIND_QUERY ) );
Value response = UnwindQuery.unwind( pipelineRequest );
pipelineRequest.children().put( RequestType.DATA, response.getChildren( TQueryExpression.ResponseType.RESULT ) );
} else if ( stage.hasChildren( RequestType.QuerySubtype.GROUP_QUERY) ) {
pipelineRequest.children().put( QUERY, stage.getChildren( RequestType.QuerySubtype.GROUP_QUERY ) );
Value response = GroupQuery.group( pipelineRequest );
pipelineRequest.children().put( RequestType.DATA, response.getChildren( TQueryExpression.ResponseType.RESULT ) );
} else if ( stage.hasChildren( RequestType.QuerySubtype.LOOKUP_QUERY ) ) {
pipelineRequest.children().put( "leftData", pipelineRequest.getChildren( RequestType.DATA ) );
pipelineRequest.children().remove( QUERY );
pipelineRequest.children().remove( RequestType.DATA );
Value lookupQuery = stage.getFirstChild( RequestType.QuerySubtype.LOOKUP_QUERY );
pipelineRequest.children().put( "leftPath", lookupQuery.getChildren( "leftPath" ) );
pipelineRequest.children().put( "rightData", lookupQuery.getChildren( "rightData" ) );
pipelineRequest.children().put( "rightPath", lookupQuery.getChildren( "rightPath" ) );
pipelineRequest.children().put( "dstPath", lookupQuery.getChildren( "dstPath" ) );
Value response = LookupQuery.lookup( pipelineRequest );
pipelineRequest.children().remove( "leftData" );
pipelineRequest.children().remove( "leftPath" );
pipelineRequest.children().remove( "rightData" );
pipelineRequest.children().remove( "rightPath" );
pipelineRequest.children().remove( "dstPath" );
pipelineRequest.children().put( RequestType.DATA, response.getChildren( TQueryExpression.ResponseType.RESULT ) );
} else {
throw new FaultException( "Unrecognized operation at position " + i );
}
}
Value response = Value.create();
response.children().put( TQueryExpression.ResponseType.RESULT, pipelineRequest.getChildren( RequestType.DATA ) );
return response;
}
}
| 6,166 | 48.336 | 117 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/common/Path.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.common;
import java.util.Optional;
import java.util.stream.IntStream;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
/**
* This class implements {@link Path}s. We use {@link Path}s in
* the TQuery framework for ephemeral data handling over trees.
*/
public class Path {
private static final String PATH_SEPARATOR = ".";
private final String node;
private final Optional< Path > continuation;
private Path( String node, Optional< Path > continuation ) {
this.node = node;
this.continuation = continuation;
}
public String getCurrentNode() {
return node;
}
public Optional< Path > getContinuation() {
return continuation;
}
/**
* It parses a
* <pre>String</pre>, e.g. a.b.c, and recursively build a
* {@link Path} with a node in the root and a {@link Path} as its
* continuation
*
* @param path the <pre>String</pre> representing the {@link Path}
* @return
*/
public static Path parsePath( String path ) throws FaultException {
path = path.trim();
int idx = path.indexOf( PATH_SEPARATOR );
if ( idx > 0 ) {
try {
return new Path( path.substring( 0, idx ), Optional.of( parsePath( path.substring( idx + 1 ) ) ) );
} catch ( FaultException e ) {
throw new FaultException( "Could not parse path \"" + path + "\"" );
}
} else if ( path.length() > 0 ) {
return new Path( path, Optional.empty() );
} else {
throw new FaultException( "Could not parse path \"" + path + "\"" );
}
}
/**
* @param value
* @return
*/
public Optional< ValueVector > apply( Value value ) {
if ( value.hasChildren( node ) ) {
if ( continuation.isPresent() ) {
ValueVector children = ValueVector.create();
value.getChildren( node )
.stream() // here we do not parallelise to preserve the ordering of the children
.forEach( child -> {
Optional< ValueVector > grandChildren = continuation.get().apply( child );
grandChildren.ifPresent( values -> values.stream().forEach( children::add ) );
} );
return children.size() > 0 ? Optional.of( children ) : Optional.empty();
} else {
return Optional.of( value.getChildren( node ) );
}
} else {
return Optional.empty();
}
}
/**
* Checks the presence of a given {@link Path} in a {@link Value}, it can
* be used for first sanity check on the query to look for
*
* @param value
* @return <pre>true</pre> or <pre>false</pre> wether the entire path is
* present in the given {@link Value}
*/
public boolean exists( Value value ) {
if ( value.hasChildren( node ) ) {
if ( continuation.isPresent() ) {
for ( Value child : value.getChildren( node ) ) {
if ( continuation.get().exists( child ) ) {
return true;
}
}
return false;
} else {
return true;
}
} else {
return false;
}
}
/**
* It gives a nice <pre>String</pre> representation of a {@link Path}
*
* @return the <pre>String</pre> representation of this {@link Path}
*/
public String toPrettyString() {
return node + ( continuation.map( path -> PATH_SEPARATOR + path.toPrettyString() ).orElse( "" ) );
}
} | 4,977 | 34.81295 | 103 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/common/Utils.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.common;
import jolie.runtime.*;
import jolie.runtime.expression.CompareCondition;
import jolie.runtime.typing.TypeCastingException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
public final class Utils {
public static boolean strictEquals( Value v1, Value v2 ) {
boolean r = false;
try {
if ( v1.isDefined() && v2.isDefined() ) {
if ( v1.isByteArray() && v2.isByteArray() ) {
r = v1.byteArrayValueStrict().equals( v2.byteArrayValueStrict() );
} else if ( v1.isString() && v2.isString() ) {
r = v1.strValueStrict().equals( v2.strValueStrict() );
} else if ( v1.isInt() && v2.isInt() ) {
r = v1.intValueStrict() == v2.intValueStrict();
} else if ( v1.isDouble() && v2.isDouble() ) {
r = v1.doubleValueStrict() == v2.doubleValueStrict();
} else if ( v1.isBool() && v2.isBool() ) {
r = v1.boolValueStrict() == v1.boolValueStrict();
} else if ( v1.isLong() && v2.isLong() ) {
r = v1.longValueStrict() == v2.longValueStrict();
} else if ( v1.valueObject() != null && v2.valueObject() != null ) {
r = v1.valueObject().equals( v2.valueObject() );
}
} else {
// undefined == undefined
r = !( v1.isDefined() && v2.isDefined() );
}
} catch ( TypeCastingException ignored ) {}
return r;
}
public static boolean checkTreeEquality( Value v1, Value v2 ) {
// if ( v1.equals( v2 ) ){ // if the root value matches
if ( strictEquals( v1, v2 ) ) {
if ( v1.children().keySet().equals( v2.children().keySet() ) ) {
for ( String node : v1.children().keySet() ) {
if ( !checkVectorEquality( v1.getChildren( node ), v2.getChildren( node ) ) ) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
}
public static boolean checkVectorEquality( ValueVector v1, ValueVector v2 ) {
if ( v1.size() == v2.size() ) {
for ( int i = 0; i < v1.size(); i++ ) {
if ( !checkTreeEquality( v1.get( i ), v2.get( i ) ) ) {
return false;
}
}
return true;
} else {
return false;
}
}
public static Value merge( Value v1, Value v2 ) throws FaultException {
if ( CompareOperators.EQUAL.test( v1, v2 ) ) {
Value returnValue = v1.clone();
// REMOVE THIS AND JUST USE CONDITIONALS
Set< String > keySetIntersection = new HashSet<>( v1.children().keySet() );
keySetIntersection.retainAll( v2.children().keySet() );
// we just need the unique set of keys for v2 since we already cloned the keys and children of V1
Set< String > uniqueKeySetV2 = new HashSet<>( v2.children().keySet() );
uniqueKeySetV2.removeAll( keySetIntersection );
for ( String key : keySetIntersection ) {
returnValue.children().put( key, merge( v1.getChildren( key ), v2.getChildren( key ) ) );
}
uniqueKeySetV2.forEach( ( key ) -> {
returnValue.children().put( key, v2.getChildren( key ) );
} );
return returnValue;
} else {
throw new FaultException(
"MergeValueException",
"Values: \n" + valueToPrettyString( v1 ) + "\n and \n" + valueToPrettyString( v2 ) + "\n cannot be merged"
);
}
}
public static ValueVector merge( ValueVector v1, ValueVector v2 ) throws FaultException {
if ( v1.size() >= v2.size() ) {
ValueVector returnVector = ValueVector.create();
for ( int i = 0; i < v1.size(); i++ ) {
if ( v2.size() > i ) {
returnVector.add( merge( v1.get( i ), v2.get( i ) ) );
} else {
returnVector.add( v1.get( i ) );
}
}
return returnVector;
} else {
return merge( v2, v1 );
}
}
public static String valueToPrettyString( Value v ) {
Writer writer = new StringWriter();
ValuePrettyPrinter printer = new ValuePrettyPrinter( v, writer, "Value" );
try {
printer.run();
} catch ( IOException e ) {
} // Should never happen
return writer.toString();
}
public static ValueVector listToValueVector( List< Value > values ) {
ValueVector returnVector = ValueVector.create();
values.stream().forEach( returnVector::add );
return returnVector;
}
public static < T > T applyOrFault( Supplier< T > supplier ) throws FaultException {
try {
return supplier.get();
} catch ( Exception e ){
throw new FaultException( e.getMessage() );
}
}
}
| 6,213 | 36.660606 | 113 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/common/TQueryExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.common;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
public interface TQueryExpression {
ValueVector applyOn( ValueVector elements ) throws FaultException;
Value applyOn( Value element ) throws FaultException;
class ResponseType {
public static final String RESULT = "result";
}
} | 2,159 | 57.378378 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/group/GroupQuery.java | package joliex.tquery.engine.group;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.match.*;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.project.ProjectExpressionChain;
import joliex.tquery.engine.project.ValueToPathProjectExpression;
import joliex.tquery.engine.project.valuedefinition.ConstantValueDefinition;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public final class GroupQuery {
private static class RequestType {
private static final String DATA = "data";
private static final String QUERY = "query";
private static final String AGGREGATE = "aggregate";
private static final String GROUPBY = "groupBy";
private static class GroupDefinition {
private static final String DST_PATH = "dstPath";
private static final String SRC_PATH = "srcPath";
private static final String DISTINCT = "distinct";
}
}
public static Value group( Value groupRequest ) throws FaultException {
ValueVector dataElements = groupRequest.getChildren( RequestType.DATA );
Value query = groupRequest.getFirstChild( RequestType.QUERY );
ValueVector group = query.getChildren( RequestType.GROUPBY );
ValueVector aggregate = query.getChildren( RequestType.AGGREGATE );
// grouping request parsing, i.e., s_1 > r_1, ..., s_n > r_n
List< GroupPair > groupingList = new LinkedList<>();
for ( Value gRequest : group ) {
groupingList.add( getGroupPair(
Path.parsePath( gRequest.getFirstChild( RequestType.GroupDefinition.SRC_PATH ).strValue() ),
Path.parsePath( gRequest.getFirstChild( RequestType.GroupDefinition.DST_PATH ).strValue() ) )
);
}
// aggregation request parsing, i.e., q_1 > p_1, ..., q_n > p_n
List< AggregatePair > aggregationList = new LinkedList<>();
for ( Value gRequest : aggregate ) {
aggregationList.add( getAggregatePair(
Path.parsePath( gRequest.getFirstChild( RequestType.GroupDefinition.SRC_PATH ).strValue() ),
Path.parsePath( gRequest.getFirstChild( RequestType.GroupDefinition.DST_PATH ).strValue() ),
gRequest.hasChildren( RequestType.GroupDefinition.DISTINCT )
&& gRequest.getFirstChild( RequestType.GroupDefinition.DISTINCT ).boolValue()
) );
}
ValueVector resultElements = ValueVector.create();
if ( groupingList.size() > 0 ) {
List< List< Boolean > > combinations = getCombinations( groupingList.size() );
List< MatchExpression > existenceGroups =
Utils.applyOrFault( () -> combinations.stream()
.map( c -> {
try {
return getMatchExistenceExpression( c, groupingList );
} catch ( FaultException e ) {
throw new RuntimeException( e.getMessage() );
}
} )
.collect( Collectors.toList() ) );
List< List< Value > > concatenationList =
Utils.applyOrFault( () -> existenceGroups.stream().map( matchExpression -> {
boolean[] bitMask = matchExpression.applyOn( dataElements );
List< Value > dataList = IntStream.range( 0, bitMask.length )
.filter( i -> bitMask[ i ] )
.mapToObj( dataElements::get )
.collect( Collectors.toList() );
try {
return group( dataList, combinations.get( existenceGroups.indexOf( matchExpression ) ), groupingList, aggregationList );
} catch ( FaultException e ) {
throw new RuntimeException( e.getMessage() );
}
}
).collect( Collectors.toList() ) );
concatenationList.forEach( l -> l.forEach( resultElements::add ) );
} else {
List< Value > dataList = dataElements.stream().collect( Collectors.toList() );
resultElements.add( aggregate( dataList, groupingList, aggregationList ) );
}
Value response = Value.create();
response.children().put( TQueryExpression.ResponseType.RESULT, resultElements );
return response;
}
private static List< Value > group(
List< Value > dataList,
List< Boolean > combination,
List< GroupPair > groupingList,
List< AggregatePair > aggregationList ) throws FaultException {
List< Value > returnVector = new LinkedList<>();
if ( dataList.size() > 0 ) {
if ( combination.stream().anyMatch( i -> i ) ) {
List< Path > paths = IntStream.range( 0, combination.size() )
.filter( combination::get )
.mapToObj( i -> groupingList.get( i ).srcPath() )
.collect( Collectors.toList() );
boolean[] bitMask = getMatchGroupingExpression( paths, dataList.get( 0 ) )
.applyOn( Utils.listToValueVector( dataList ) );
List< Value > current = new LinkedList<>();
List< Value > residuals = new LinkedList<>();
IntStream.range( 0, bitMask.length ).forEach( i -> {
if ( bitMask[ i ] ) {
current.add( dataList.get( i ) );
} else {
residuals.add( dataList.get( i ) );
}
} );
returnVector.add( aggregate( current, groupingList, aggregationList ) );
returnVector.addAll( group( residuals, combination, groupingList, aggregationList ) );
} else {
returnVector.add( aggregate( dataList, groupingList, aggregationList ) );
}
}
return returnVector;
}
private static MatchExpression getMatchGroupingExpression( List< Path > paths, Value v ) throws FaultException {
if ( paths.size() < 0 ) {
throw new FaultException( "getMatchGroupingExpression received a combination of size 0" ); //todo: refine this error into a Fault
} else {
MatchExpression currentExpression = new EqualDataExpression( paths.get( 0 ), paths.get( 0 ).apply( v ).get() ); // we can always get here, because we passed the existence tests in the group method
if ( paths.size() > 1 ) {
return BinaryExpression.AndExpression(
currentExpression,
getMatchGroupingExpression( paths.subList( 1, paths.size() ), v )
);
} else {
return currentExpression;
}
}
}
private static Value aggregate( List< Value > dataList, List< GroupPair > groupingList, List< AggregatePair > aggregationList ) {
Value returnValue = Value.create();
ProjectExpressionChain returnProjectionChain = new ProjectExpressionChain();
groupingList.forEach( groupElement ->
{
try {
Optional< ValueVector > maybeValueVector = groupElement.srcPath().apply( dataList.get( 0 ) );
if ( maybeValueVector.isPresent() ) {
returnProjectionChain.addExpression(
new ValueToPathProjectExpression(
groupElement.dstPath(),
new ConstantValueDefinition( maybeValueVector.get() )
) );
}
} catch ( FaultException e ) {
e.printStackTrace();
}
} );
aggregationList.forEach( aggregationElement ->
{
DistinctFilter d = new DistinctFilter();
List< ValueVector > distinctValueVectors = dataList.stream()
.map( v -> aggregationElement.srcPath().apply( v ) )
.filter( Optional::isPresent )
.map( Optional::get )
.filter( e -> ( !aggregationElement.isDistinct() ) || d.isDistinct( e ) )
.collect( Collectors.toList() );
ValueVector mergedValueVector = ValueVector.create();
distinctValueVectors.stream().flatMap( ValueVector::stream ).forEach( mergedValueVector::add );
try {
returnProjectionChain.addExpression(
new ValueToPathProjectExpression(
aggregationElement.dstPath(),
new ConstantValueDefinition( mergedValueVector )
) );
} catch ( FaultException e ) {
e.printStackTrace();
}
} );
try {
returnValue = returnProjectionChain.applyOn( returnValue );
} catch ( FaultException e ) {
e.printStackTrace();
}
return returnValue;
}
// 0 -> emptyList
// 1 -> [ [ true ], [ false ] ]
// 2 -> [ [ true, false ], [ true, true ], [ false, true ], [ true, false ]
// ...
private static List< List< Boolean > > getCombinations( int size ) {
if ( size > 1 ) {
List< List< Boolean > > subCombinations = getCombinations( size - 1 );
return subCombinations.stream()
.flatMap( e -> Stream.of(
Stream.concat( Stream.of( true ), e.stream() ).collect( Collectors.toList() ),
Stream.concat( Stream.of( false ), e.stream() ).collect( Collectors.toList() )
) )
.collect( Collectors.toList() );
}
if ( size > 0 ) {
return List.of( Collections.singletonList( true ), Collections.singletonList( false ) );
} else {
return Collections.emptyList();
}
}
private static MatchExpression getMatchExistenceExpression( List< Boolean > combination, List< GroupPair > groupPairList ) throws FaultException {
if ( combination.size() < 0 || groupPairList.size() < 0 ) {
throw new FaultException( "getMatchExistenceExpression received a combination of size 0" ); //todo: refine this error into a Fault
} else {
MatchExpression currentExpression = new ExistsExpression( groupPairList.get( 0 ).srcPath() );
currentExpression = combination.get( 0 ) ? currentExpression : new NotExpression( currentExpression );
if ( combination.size() > 1 ) {
return BinaryExpression.AndExpression(
currentExpression,
getMatchExistenceExpression( combination.subList( 1, combination.size() ), groupPairList.subList( 1, combination.size() ) )
);
} else {
return currentExpression;
}
}
}
public static class AggregatePair extends GroupPair {
private final Boolean isDistinct;
public AggregatePair( Path sourcePath, Path destinationPath, Boolean isDistinct ) {
super( sourcePath, destinationPath );
this.isDistinct = isDistinct;
}
public Boolean isDistinct() {
return isDistinct;
}
}
public static class GroupPair {
private final Path s, d;
public GroupPair( Path sourcePath, Path destinationPath ) {
this.s = sourcePath;
this.d = destinationPath;
}
public Path dstPath() {
return d;
}
public Path srcPath() {
return s;
}
}
public static GroupPair getGroupPair( Path sourcePath, Path destinationPath ) {
return new GroupPair( sourcePath, destinationPath );
}
public static AggregatePair getAggregatePair( Path sourcePath, Path destinationPath, Boolean isDistinc ) {
return new AggregatePair( sourcePath, destinationPath, isDistinc );
}
private static class DistinctFilter {
Set< ValueVector > seen;
DistinctFilter() {
seen = new HashSet<>();
}
public boolean isDistinct( ValueVector element ) {
if ( seen.stream().anyMatch( v -> Utils.checkVectorEquality( v, element ) ) ) {
return false;
} else {
seen.add( element );
return true;
}
}
}
}
| 10,724 | 35.85567 | 199 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/unwind/UnwindExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.unwind;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import java.util.Arrays;
import java.util.stream.IntStream;
class UnwindExpression {
private final Path path;
UnwindExpression( Path path ) {
this.path = path;
}
public ValueVector applyOn( ValueVector elements ) {
ValueVector resultElements = ValueVector.create();
ValueVector[] batches = new ValueVector[ elements.size() ];
IntStream.range( 0, elements.size() )
.parallel()
.forEach( index -> {
try {
String node = path.getCurrentNode();
Value element = elements.get( index );
ValueVector elementsContinuation = Path.parsePath( node )
.apply( element )
.orElse( ValueVector.create() );
if ( path.getContinuation().isPresent() ) {
elementsContinuation =
new UnwindExpression( path.getContinuation().get() )
.applyOn( Path.parsePath( node ).apply( element ).orElse( ValueVector.create() ) );
}
batches[ index ] = expand( element, elementsContinuation, node );
} catch ( Exception e ) {
e.printStackTrace(); // we should never reach this due to a Path.parse exception since the path is checked at the beginnign
}
} );
Arrays.stream( batches ).flatMap( ValueVector::stream ).forEach( resultElements::add );
return resultElements;
}
private ValueVector expand( Value element, ValueVector elements, String node ) {
ValueVector returnVector = ValueVector.create();
IntStream.range( 0, elements.size() )
.parallel()
.forEach( index -> {
Value thisElement = Value.create();
returnVector.set( index, thisElement );
element.children().keySet().stream()
.filter( key -> !key.equals( node ) )
.parallel()
.forEach( key ->
thisElement.children().put( key, ValueVector.createClone( element.getChildren( key ) ) )
);
thisElement.children().put( node, getFreshValueVector( elements.get( index ) ) );
} );
return returnVector;
}
private ValueVector getFreshValueVector( Value element ) {
ValueVector result = ValueVector.create();
result.add( element );
return result;
}
}
| 4,093 | 40.77551 | 131 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/unwind/UnwindQuery.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.unwind;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
public class UnwindQuery {
public static Value unwind( Value request ) throws FaultException {
Value query = request.getFirstChild( UnwindQuery.RequestType.QUERY );
Path path = Path.parsePath( query.strValue() );
ValueVector elements = request.getChildren( UnwindQuery.RequestType.DATA );
Value responseValue = Value.create();
responseValue.children().put(TQueryExpression.ResponseType.RESULT, unwindOperator( path, elements ) );
return responseValue;
}
private static ValueVector unwindOperator( Path path, ValueVector elements ) throws FaultException {
UnwindExpression unwindExpression = new UnwindExpression( path );
return unwindExpression.applyOn( elements );
}
private static class RequestType {
private static final String QUERY = "query";
private static final String DATA = "data";
}
}
| 2,849 | 49 | 104 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/PathProjectExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import java.util.Optional;
public class PathProjectExpression implements ProjectExpression {
private final Path path;
public PathProjectExpression( String path ) throws FaultException {
this.path = Path.parsePath( path );
}
private PathProjectExpression( Path path ) {
this.path = path;
}
@Override
public Value applyOn( Value element ) throws FaultException {
Value returnValue = Value.create();
Optional< ValueVector > valueVector = Path.parsePath( path.getCurrentNode() ).apply( element );
if ( valueVector.isPresent() ) {
returnValue.children().put( path.getCurrentNode(), valueVector.get() );
if ( path.getContinuation().isPresent() ) {
returnValue = new PathProjectExpression( path.getContinuation().get() ).applyOn( returnValue );
}
}
return returnValue;
}
}
| 2,772 | 46 | 99 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/ProjectExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import java.util.stream.IntStream;
public interface ProjectExpression {
default ValueVector applyOn( ValueVector elements ) throws FaultException {
ValueVector returnVector = ValueVector.create();
try {
IntStream.range( 0, elements.size() )
.parallel()
.forEach( i -> {
try {
returnVector.set( i, this.applyOn( elements.get( i ) ) );
} catch ( FaultException e ) {
throw new RuntimeException( e.getMessage() );
}
} );
} catch ( Exception e ) {
throw new FaultException( e.getMessage() );
}
return returnVector;
}
Value applyOn( Value element ) throws FaultException;
} | 2,578 | 46.759259 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/ValueToPathProjectExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.project.valuedefinition.ValueDefinition;
import joliex.tquery.engine.project.valuedefinition.ValueDefinitionParser;
public class ValueToPathProjectExpression implements ProjectExpression {
private final Path destination_path;
private final ValueDefinition valueDefinition;
public ValueToPathProjectExpression( String destination_path, ValueVector values ) throws FaultException {
this.destination_path = Path.parsePath( destination_path );
valueDefinition = ValueDefinitionParser.parseValues( values );
}
public ValueToPathProjectExpression( Path destination_path, ValueDefinition valueDefinition ) throws FaultException {
this.destination_path = destination_path;
this.valueDefinition = valueDefinition;
}
@Override
public Value applyOn( Value element ) throws FaultException {
Value returnValue = Value.create();
if ( valueDefinition.isDefined( element ) ) {
if ( destination_path.getContinuation().isPresent() ) {
ValueVector v = ValueVector.create();
v.add( new ValueToPathProjectExpression( destination_path.getContinuation().get(), valueDefinition ).applyOn( element ) );
returnValue.children().put( destination_path.getCurrentNode(), v );
} else {
returnValue.children().put( destination_path.getCurrentNode(), valueDefinition.evaluate( element ) );
}
}
return returnValue;
}
}
| 3,386 | 51.107692 | 126 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/ProjectExpressionChain.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import java.util.Iterator;
import java.util.LinkedList;
public class ProjectExpressionChain implements ProjectExpression {
private final LinkedList< ProjectExpression > expressions = new LinkedList<>();
public ProjectExpressionChain addExpression( ProjectExpression expression ) {
expressions.add( expression );
return this;
}
@Override
public Value applyOn( Value element ) throws FaultException {
if ( expressions.isEmpty() ) {
return element;
} else {
return _applyOn( element, expressions.iterator() );
}
}
private Value _applyOn( Value element, Iterator< ProjectExpression > i ) throws FaultException {
ProjectExpression pe = i.next();
if( i.hasNext() ){
return Utils.merge( pe.applyOn( element ), _applyOn( element, i ) );
} else {
return pe.applyOn( element );
}
}
}
| 2,836 | 44.758065 | 97 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/ProjectQuery.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.TQueryExpression;
import java.util.stream.IntStream;
public class ProjectQuery {
private static class RequestType {
private static final String DATA = "data";
private static final String QUERY = "query";
private static class ValueToPathExpression {
private static final String DESTINATION_PATH = "dstPath";
private static final String VALUE = "value";
}
}
public static Value project( Value projectRequest ) throws FaultException {
ValueVector query = projectRequest.getChildren( RequestType.QUERY );
ValueVector dataElements = projectRequest.getChildren( RequestType.DATA );
ProjectExpression projectExpression = parseProjectionChain( query );
Value response = Value.create();
ValueVector responseVector = ValueVector.create();
response.children().put( TQueryExpression.ResponseType.RESULT, responseVector );
try {
IntStream.range( 0, dataElements.size() )
.parallel()
.forEach( i -> {
try {
responseVector.set( i, projectExpression.applyOn( dataElements.get( i ) ) );
} catch ( Exception e ) {
throw new RuntimeException( e.getMessage() );
}
} );
} catch ( Exception e ) {
throw new FaultException( e.getMessage() );
}
return response;
}
private static ProjectExpressionChain parseProjectionChain( ValueVector queries ) throws FaultException {
ProjectExpressionChain returnExpressionChain = new ProjectExpressionChain();
for ( Value query : queries ) {
returnExpressionChain.addExpression( parseProjectExpression( query ) );
}
return returnExpressionChain;
}
private static ProjectExpression parseProjectExpression( Value query ) throws FaultException {
if ( query.isString() ) {
return new PathProjectExpression( query.strValue() );
} else {
return new ValueToPathProjectExpression(
query.getFirstChild( RequestType.ValueToPathExpression.DESTINATION_PATH ).strValue(),
query.getChildren( RequestType.ValueToPathExpression.VALUE )
);
}
}
}
| 3,959 | 43.494382 | 106 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/MatchValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.match.MatchExpression;
public class MatchValueDefinition implements ValueDefinition {
private final MatchExpression matchExpression;
public MatchValueDefinition( MatchExpression matchExpression ){
this.matchExpression = matchExpression;
}
@Override
public ValueVector evaluate( Value value ) {
ValueVector returnVector = ValueVector.create();
returnVector.add( Value.create( matchExpression.applyOn( value ) ) );
return returnVector;
}
@Override
public boolean isDefined( Value value ) {
return true;
}
}
| 2,463 | 47.313725 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/ListValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import java.util.List;
public class ListValueDefinition implements ValueDefinition {
private final List<ValueDefinition> valueDefinitions;
public ListValueDefinition( List<ValueDefinition> valueDefinitions ) {
this.valueDefinitions = valueDefinitions;
}
@Override
public ValueVector evaluate( Value value ) {
ValueVector returnVector = ValueVector.create();
valueDefinitions.forEach( ( valueDefinition ) -> {
if( valueDefinition.isDefined( value ) ){
valueDefinition.evaluate( value ).forEach( ( resultValue ) -> {
returnVector.add( resultValue );
});
}
});
return returnVector;
}
@Override
public boolean isDefined( Value value ) {
for ( ValueDefinition valueDefinition : valueDefinitions ) {
if( valueDefinition.isDefined( value ) ){
return true;
}
}
return false;
}
}
| 2,736 | 42.444444 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/TernaryValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.match.MatchExpression;
public class TernaryValueDefinition implements ValueDefinition {
private final MatchExpression condition;
private final ValueDefinition ifTrue, ifFalse;
public TernaryValueDefinition( MatchExpression condition, ValueDefinition ifTrue, ValueDefinition ifFalse ) {
this.condition = condition;
this.ifTrue = ifTrue;
this.ifFalse = ifFalse;
}
@Override
public ValueVector evaluate( Value value ) {
if ( condition.applyOn( value ) ) {
return ifTrue.evaluate( value );
} else {
return ifFalse.evaluate( value );
}
}
@Override
public boolean isDefined( Value value ) {
if ( condition.applyOn( value ) ) {
return ifTrue.isDefined( value );
} else {
return ifFalse.isDefined( value );
}
}
}
| 2,681 | 43.7 | 110 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/ValueDefinitionParser.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.match.MatchExpression;
import joliex.tquery.engine.match.MatchQuery;
import java.util.ArrayList;
public class ValueDefinitionParser {
private static final class ValueDefinitionType {
private static final String PATH = "path";
private static final String MATCH = "match";
private static final String CONDITION = "condition";
private static final String IF_TRUE = "ifTrue";
private static final String IF_FALSE = "ifFalse";
}
public static ValueDefinition parseValues( ValueVector values ) throws FaultException {
if ( values.size() == 1 ) {
return parseValue( values.get( 0 ) );
} else {
ArrayList< ValueDefinition > valueDefinitions = new ArrayList<>();
for ( Value value : values ) {
valueDefinitions.add( parseValue( value ) );
}
return new ListValueDefinition( valueDefinitions );
}
}
public static ValueDefinition parseValue( Value value ) throws FaultException {
if ( value.hasChildren( ValueDefinitionType.PATH ) ) {
return new PathValueDefinition( value.getFirstChild( ValueDefinitionType.PATH ).strValue() );
} else if ( value.hasChildren( ValueDefinitionType.MATCH ) ) {
return new MatchValueDefinition( parseMatchExpression( value.getFirstChild( ValueDefinitionType.MATCH ) ) );
} else if ( value.hasChildren( ValueDefinitionType.CONDITION ) ) {
MatchExpression condition = parseMatchExpression( value.getFirstChild( ValueDefinitionType.CONDITION ) );
ValueDefinition ifTrue = parseValues( value.getChildren( ValueDefinitionType.IF_TRUE ) );
ValueDefinition ifFalse = parseValues( value.getChildren( ValueDefinitionType.IF_FALSE ) );
return new TernaryValueDefinition( condition, ifTrue, ifFalse );
} else {
return new ConstantValueDefinition( value );
}
}
private static MatchExpression parseMatchExpression( Value value ) throws FaultException {
return MatchQuery.parseMatchExpression( value ).orElseThrow(
() -> new FaultException(
"MatchQuerySyntaxException",
"Could not parse query expression " + Utils.valueToPrettyString( value.getFirstChild( ValueDefinitionType.MATCH ) ) ) );
}
}
| 4,117 | 50.475 | 130 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/PathValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.Utils;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PathValueDefinition implements ValueDefinition {
private final Path path;
public PathValueDefinition( String path ) throws FaultException {
this.path = Path.parsePath( path );
}
@Override
public ValueVector evaluate( Value value ) {
return path.apply( value ).orElseGet( () -> {
Logger.getLogger( PathValueDefinition.class.getName() )
.log( Level.SEVERE, null, new FaultException( "IllegalEvaluation",
"Tried to apply path " + path.toPrettyString() + " on " + Utils.valueToPrettyString( value ) ) );
ValueVector v = ValueVector.create();
v.add( Value.create() );
return v;
} );
}
@Override
public boolean isDefined( Value value ) {
return path.exists( value );
}
}
| 2,820 | 44.5 | 108 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/ValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
public interface ValueDefinition {
ValueVector evaluate( Value value );
boolean isDefined( Value value );
}
| 2,013 | 60.030303 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/project/valuedefinition/ConstantValueDefinition.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.project.valuedefinition;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
public class ConstantValueDefinition implements ValueDefinition {
private final ValueVector returnValue;
public ConstantValueDefinition( Value value ){
ValueVector v = ValueVector.create();
v.add( value );
returnValue = v;
}
public ConstantValueDefinition( ValueVector valueVector ){
returnValue = valueVector;
}
@Override
public ValueVector evaluate( Value value ) {
return returnValue;
}
@Override
public boolean isDefined( Value value ) {
return true;
}
}
| 2,395 | 43.37037 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/lookup/LookupQuery.java | package joliex.tquery.engine.lookup;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.match.EqualDataExpression;
import joliex.tquery.engine.project.ProjectExpression;
import joliex.tquery.engine.project.ValueToPathProjectExpression;
import java.util.Optional;
import java.util.stream.IntStream;
public final class LookupQuery {
private static class RequestType {
private static final String LEFT_DATA = "leftData";
private static final String RIGHT_DATA = "rightData";
private static final String LEFT_PATH = "leftPath";
private static final String RIGHT_PATH = "rightPath";
private static final String DST_PATH = "dstPath";
}
public static Value lookup( Value lookupRequest ) throws FaultException {
ValueVector leftData = lookupRequest.getChildren( RequestType.LEFT_DATA );
ValueVector rightData = lookupRequest.getChildren( RequestType.RIGHT_DATA );
Value leftPathValue = lookupRequest.getFirstChild( RequestType.LEFT_PATH );
Value rightPathValue = lookupRequest.getFirstChild( RequestType.RIGHT_PATH );
Value dstPath = lookupRequest.getFirstChild( RequestType.DST_PATH );
ValueVector result = ValueVector.create();
Path leftPath;
Path rightPath;
try {
leftPath = Path.parsePath( leftPathValue.strValue() );
} catch ( IllegalArgumentException e ) {
throw new FaultException( "LookupQuerySyntaxException", "Could not parse left path value" + Utils.valueToPrettyString( leftPathValue ) );
}
try {
rightPath = Path.parsePath( rightPathValue.strValue() );
} catch ( IllegalArgumentException e ) {
throw new FaultException( "LookupQuerySyntaxException", "Could not parse right path value" + Utils.valueToPrettyString( rightPathValue ) );
}
try {
Path.parsePath( dstPath.strValue() );
} catch ( IllegalArgumentException e ) {
throw new FaultException( "LookupQuerySyntaxException", "Could not parse destination path " + Utils.valueToPrettyString( dstPath ) );
}
try {
IntStream.range( 0, leftData.size() )
.parallel()
.forEach( index -> {
try {
ValueVector responseVector = ValueVector.create();
Value leftValue = leftData.get( index );
Optional< ValueVector > optionalValues = leftPath.apply( leftValue );
if ( optionalValues.isPresent() ) {
ValueVector values = optionalValues.get();
//check if the rightData array contains any tree under the rightPath with the content equals to the content of values
EqualDataExpression v = new EqualDataExpression( rightPath, values );
boolean[] mask = v.applyOn( rightData );
for ( int i = 0; i < mask.length; i++ ) {
if ( mask[ i ] ) {
responseVector.add( rightData.get( i ) );
}
}
ProjectExpression beta = new ValueToPathProjectExpression( dstPath.strValue(), responseVector );
Value value = beta.applyOn( leftValue );
result.set( index, Utils.merge( leftValue, value ) );
}
} catch ( FaultException e ) {
throw new RuntimeException( e.getMessage() );
}
}
);
} catch ( Exception e ){
throw new FaultException( e.getMessage() );
}
Value response = Value.create();
response.children().put( TQueryExpression.ResponseType.RESULT, result );
return response;
}
}
| 3,538 | 35.112245 | 142 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/BinaryExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import java.util.function.Function;
public class BinaryExpression implements MatchExpression {
final private Function<Value, Boolean> assembleResult;
private BinaryExpression( Function< Value, Boolean > assembleResult ){
this.assembleResult = assembleResult;
}
public static BinaryExpression OrExpression( MatchExpression leftExpression, MatchExpression rightExpression ){
Function<Value, Boolean> assembleFunction = ( Value v ) -> leftExpression.applyOn( v ) || rightExpression.applyOn( v );
return new BinaryExpression( assembleFunction );
}
public static BinaryExpression AndExpression( MatchExpression leftExpression, MatchExpression rightExpression ){
Function<Value, Boolean> assembleFunction = (Value v) -> leftExpression.applyOn( v ) && rightExpression.applyOn( v );
return new BinaryExpression( assembleFunction );
}
@Override
public boolean applyOn( Value element ) {
return this.assembleResult.apply( element );
}
}
| 2,845 | 50.745455 | 121 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/EqualPathExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.Utils;
import java.util.Optional;
public class EqualPathExpression implements MatchExpression {
private final Path left;
private final Path right;
public EqualPathExpression( Path left, Path right ){
this.left = right;
this.right = left;
}
@Override
public boolean applyOn( Value element ) {
Optional<ValueVector> leftPathApplication = left.apply( element );
Optional< ValueVector > rightPathApplication = right.apply( element );
return ( leftPathApplication.isEmpty() && rightPathApplication.isEmpty() )
||
Utils.checkVectorEquality( leftPathApplication.get(), rightPathApplication.get() );
}
}
| 2,590 | 47.886792 | 89 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/MatchUtils.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.ValueVector;
public class MatchUtils {
public static boolean[] getMask( ValueVector elements ){
return new boolean[ elements.size() ];
}
}
| 1,991 | 55.914286 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/ExistsExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
public class ExistsExpression implements MatchExpression {
private final Path path;
public ExistsExpression( Path path ){
this.path = path;
}
@Override
public boolean applyOn( Value element ) {
return path.exists( element );
}
}
| 2,172 | 48.386364 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/MatchExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import java.util.stream.IntStream;
public interface MatchExpression {
default boolean[] applyOn( ValueVector elements ){
boolean[] mask = MatchUtils.getMask( elements );
IntStream.range( 0, elements.size() )
.parallel()
.forEach( i -> mask[ i ] = applyOn( elements.get( i ) ) );
return mask;
}
boolean applyOn( Value element );
} | 2,238 | 52.309524 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/BooleanExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import java.util.Arrays;
public class BooleanExpression implements MatchExpression {
private final boolean booleanValue;
public BooleanExpression( boolean booleanValue ) {
this.booleanValue = booleanValue;
}
@Override
public boolean applyOn( Value element ) {
return booleanValue;
}
}
| 2,189 | 46.608696 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/NotExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
public class NotExpression implements MatchExpression {
private final MatchExpression expression;
public NotExpression( MatchExpression expression ){
this.expression = expression;
}
@Override
public boolean applyOn( Value element ) {
return !expression.applyOn( element );
}
}
| 2,179 | 49.697674 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/EqualDataExpression.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.Utils;
import java.util.Optional;
public class EqualDataExpression implements MatchExpression {
private final Path path;
private final ValueVector vector;
public EqualDataExpression( Path path, ValueVector vector ){
this.path = path;
this.vector = vector;
}
@Override
public boolean applyOn( Value element ) {
Optional<ValueVector> pathApplication = path.apply( element );
return pathApplication.isPresent() && Utils.checkVectorEquality( pathApplication.get(), vector );
}
}
| 2,455 | 48.12 | 99 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/match/MatchQuery.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine.match;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Path;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import java.util.Optional;
public final class MatchQuery {
private static class RequestType {
private static final String DATA = "data";
private static final String QUERY = "query";
private static class QuerySubtype {
private static final String NOT = "not";
private static final String EQUAL = "equal";
private static final String OR = "or";
private static final String AND = "and";
private static final String EXISTS = "exists";
private static final String LEFT = "left";
private static final String RIGHT = "right";
private static final String PATH = "path";
private static final String DATA = "data";
}
}
public static Value match( Value matchRequest ) throws FaultException {
Value query = matchRequest.getFirstChild( RequestType.QUERY );
ValueVector dataElements = matchRequest.getChildren( RequestType.DATA );
boolean[] mask = parseMatchExpression( query )
.orElseThrow(
() -> new FaultException( "MatchQuerySyntaxException", "Could not parse query expression " + Utils.valueToPrettyString( query ) )
).applyOn( dataElements );
Value response = Value.create();
ValueVector responseVector = ValueVector.create();
response.children().put( TQueryExpression.ResponseType.RESULT, responseVector );
for ( int i = 0; i < mask.length; i++ ) {
if ( mask[ i ] ) {
responseVector.add( dataElements.get( i ) );
}
}
return response;
}
public static Optional< MatchExpression > parseMatchExpression( Value query ) throws FaultException {
MatchExpression e = unsafeParseMatchExpression( query );
return ( e != null ) ? Optional.of( e ) : Optional.empty();
}
//type MatchRequestType : void {
//.data* : undefined
//.query : void {
// .not : MatchExp
// | .or : void { .left: MatchExp, .right: MatchExp }
// | .and : void { .left: MatchExp, .right: MatchExp }
// | .equal : void { .path: Path, .data[1,*]: undefined }
// | .equal : void { .left: Path, .right: Path }
// | .exists : Path
// | bool
private static MatchExpression unsafeParseMatchExpression( Value query ) throws FaultException {
if ( query.children().size() > 1 ) {
throw new FaultException( "Query data does not have the expected structure: " + Utils.valueToPrettyString( query ) );
} else {
if ( query.isBool() ) {
return new BooleanExpression( query.boolValue() );
} else if ( query.hasChildren( RequestType.QuerySubtype.EQUAL ) ) {
if( query.getFirstChild( RequestType.QuerySubtype.EQUAL ).hasChildren( RequestType.QuerySubtype.PATH ) ){
return new EqualDataExpression(
Path.parsePath( query.getFirstChild( RequestType.QuerySubtype.EQUAL ).getFirstChild( RequestType.QuerySubtype.PATH ).strValue() ),
query.getFirstChild( RequestType.QuerySubtype.EQUAL ).getChildren( RequestType.QuerySubtype.DATA )
);
} else {
return new EqualPathExpression(
Path.parsePath( query.getFirstChild( RequestType.QuerySubtype.EQUAL ).getFirstChild( RequestType.QuerySubtype.LEFT ).strValue() ),
Path.parsePath( query.getFirstChild( RequestType.QuerySubtype.EQUAL ).getFirstChild( RequestType.QuerySubtype.RIGHT ).strValue() )
);
}
} else if ( query.hasChildren( RequestType.QuerySubtype.EXISTS ) ) {
return new ExistsExpression(
Path.parsePath( query.getFirstChild( RequestType.QuerySubtype.EXISTS ).strValue() )
);
} else if ( query.hasChildren( RequestType.QuerySubtype.OR ) ) {
return BinaryExpression.OrExpression(
parseMatchExpression( query.getFirstChild( RequestType.QuerySubtype.OR ).getFirstChild( RequestType.QuerySubtype.LEFT ) )
.orElseThrow(
() -> new FaultException( "Could not parse left hand of " + Utils.valueToPrettyString( query ) )
),
parseMatchExpression( query.getFirstChild( RequestType.QuerySubtype.OR ).getFirstChild( RequestType.QuerySubtype.RIGHT ) )
.orElseThrow(
() -> new FaultException( "Could not parse right hand of " + Utils.valueToPrettyString( query ) )
)
);
} else if ( query.hasChildren( RequestType.QuerySubtype.AND ) ) {
return BinaryExpression.AndExpression(
parseMatchExpression( query.getFirstChild( RequestType.QuerySubtype.AND ).getFirstChild( RequestType.QuerySubtype.LEFT ) )
.orElseThrow(
() -> new FaultException( "Could not parse left hand of " + Utils.valueToPrettyString( query ) )
),
parseMatchExpression( query.getFirstChild( RequestType.QuerySubtype.AND ).getFirstChild( RequestType.QuerySubtype.RIGHT ) )
.orElseThrow(
() -> new FaultException( "Could not parse right hand of " + Utils.valueToPrettyString( query ) )
)
);
} else if ( query.hasChildren( RequestType.QuerySubtype.NOT ) ) {
return new NotExpression( parseMatchExpression( query.getFirstChild( RequestType.QuerySubtype.NOT ) )
.orElseThrow(
() -> new FaultException( "Could not parse " + Utils.valueToPrettyString( query ) )
)
);
}
}
return null;
}
}
| 7,285 | 48.564626 | 139 | java |
cqengine | cqengine-master/documentation/documents/CQEngine.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.DefaultConcurrentSetFactory;
import com.googlecode.cqengine.index.support.Factory;
import java.util.Collection;
import java.util.Set;
/**
* <p>
* A bridge class which provides backward compatibility from CQEngine 2.x to applications which were using CQEngine 1.x.
* </p>
* <p>
* In CQEngine 2.0, applications should not use the static factory methods in this class to create instances of
* {@link com.googlecode.cqengine.IndexedCollection}s, but should use the constructors of the required
* IndexedCollection implementation instead, such as:
* <ul>
* <li>
* {@link com.googlecode.cqengine.ConcurrentIndexedCollection}
* </li>
* <li>
* {@link com.googlecode.cqengine.ObjectLockingIndexedCollection}
* </li>
* <li>
* {@link com.googlecode.cqengine.TransactionalIndexedCollection}
* </li>
* </ul>
* </p>
* @deprecated This class will not be supported in later versions of CQEngine.
* @author Niall Gallagher
*/
@Deprecated
public class CQEngine {
/**
* Returns a new {@link IndexedCollection} to which objects can be added subsequently.
* <p/>
* The implementation returned supports concurrent reads in all cases, and supports concurrent modification in
* cases where multiple threads will add/remove different objects but not the same objects to the collection
* concurrently. See {@link ConcurrentIndexedCollection} for details.
*
* @param <O> The type of objects in the collection
* @return A new {@link IndexedCollection} initially containing no objects
*/
public static <O> IndexedCollection<O> newInstance() {
return new ConcurrentIndexedCollection<O>(new DefaultConcurrentSetFactory<O>());
}
/**
* Returns a new {@link IndexedCollection} to which objects can be added subsequently.
* <p/>
* The implementation returned supports concurrent reads in all cases, and supports concurrent modification in
* cases where multiple threads will add/remove different objects but not the same objects to the collection
* concurrently. See {@link ConcurrentIndexedCollection} for details.
*
* @param backingSetFactory A factory which will create a concurrent {@link java.util.Set} in which objects
* added to the indexed collection will be stored
* @param <O> The type of objects in the collection
* @return A new {@link IndexedCollection} initially containing no objects
*/
public static <O> IndexedCollection<O> newInstance(Factory<Set<O>> backingSetFactory) {
return new ConcurrentIndexedCollection<O>(backingSetFactory);
}
/**
* Returns a new {@link IndexedCollection} containing objects from the given collection.
* <p/>
* The implementation returned supports concurrent reads in all cases, and supports concurrent modification in
* cases where multiple threads will add/remove different objects but not the same objects to the collection
* concurrently. See {@link ConcurrentIndexedCollection} for details.
*
* @param collection A collection containing initial values to be indexed
* @param <O> The type of objects in the collection
* @return An {@link IndexedCollection} initialized with objects from the given collection
*/
public static <O> IndexedCollection<O> copyFrom(Collection<O> collection) {
Factory<Set<O>> setFactory = new DefaultConcurrentSetFactory<O>(collection.size());
IndexedCollection<O> indexedCollection = new ConcurrentIndexedCollection<O>(setFactory);
indexedCollection.addAll(collection);
return indexedCollection;
}
/**
* Returns a new {@link IndexedCollection} containing objects from the given collection.
* <p/>
* The implementation returned supports concurrent reads in all cases, and supports concurrent modification in
* cases where multiple threads will add/remove different objects but not the same objects to the collection
* concurrently. See {@link ConcurrentIndexedCollection} for details.
*
* @param collection A collection containing initial values to be indexed
* @param backingSetFactory A factory which will create a concurrent {@link java.util.Set} in which objects
* added to the indexed collection will be stored
* @param <O> The type of objects in the collection
* @return An {@link IndexedCollection} initialized with objects from the given collection
*/
public static <O> IndexedCollection<O> copyFrom(Collection<O> collection, Factory<Set<O>> backingSetFactory) {
IndexedCollection<O> indexedCollection = new ConcurrentIndexedCollection<O>(backingSetFactory);
indexedCollection.addAll(collection);
return indexedCollection;
}
/**
* Returns a new {@link IndexedCollection} to which objects can be added subsequently.
* <p/>
* The implementation returned supports concurrent reads and writes in general, but employs some locking
* in the write path for applications in which multiple threads might try to add/remove the <i>same</i>
* object to/from the collection concurrently.
* See {@link ObjectLockingIndexedCollection} for details.
*
* @param concurrencyLevel The estimated number of concurrently updating threads. 64 could be a sensible default
* @param <O> The type of objects in the collection
* @return A new {@link IndexedCollection} initially containing no objects
*/
public static <O> IndexedCollection<O> newObjectLockingInstance(int concurrencyLevel) {
return new ObjectLockingIndexedCollection<O>(new DefaultConcurrentSetFactory<O>(), concurrencyLevel);
}
/**
* Returns a new {@link IndexedCollection} to which objects can be added subsequently.
* <p/>
* The implementation returned supports concurrent reads and writes in general, but employs some locking
* in the write path for applications in which multiple threads might try to add/remove the <i>same</i>
* object to/from the collection concurrently.
* See {@link ObjectLockingIndexedCollection} for details.
*
* @param concurrencyLevel The estimated number of concurrently updating threads. 64 could be a sensible default
* @param backingSetFactory A factory which will create a concurrent {@link java.util.Set} in which objects
* added to the indexed collection will be stored
* @param <O> The type of objects in the collection
* @return A new {@link IndexedCollection} initially containing no objects
*/
public static <O> IndexedCollection<O> newObjectLockingInstance(int concurrencyLevel, Factory<Set<O>> backingSetFactory) {
return new ObjectLockingIndexedCollection<O>(backingSetFactory, concurrencyLevel);
}
/**
* Returns a new {@link IndexedCollection} containing objects from the given collection.
* <p/>
* The implementation returned supports concurrent reads and writes in general, but employs some locking
* in the write path for applications in which multiple threads might try to add/remove the <i>same</i>
* object to/from the collection concurrently.
* See {@link ObjectLockingIndexedCollection} for details.
*
* @param collection A collection containing initial values to be indexed
* @param concurrencyLevel The estimated number of concurrently updating threads. 64 could be a sensible default
* @param <O> The type of objects in the collection
* @return An {@link IndexedCollection} initialized with objects from the given collection
*/
public static <O> IndexedCollection<O> copyFromObjectLocking(Collection<O> collection, int concurrencyLevel) {
Factory<Set<O>> setFactory = new DefaultConcurrentSetFactory<O>(collection.size());
IndexedCollection<O> indexedCollection = new ObjectLockingIndexedCollection<O>(setFactory, concurrencyLevel);
indexedCollection.addAll(collection);
return indexedCollection;
}
/**
* Returns a new {@link IndexedCollection} containing objects from the given collection.
* <p/>
* <p/>
* The implementation returned supports concurrent reads and writes in general, but employs some locking
* in the write path for applications in which multiple threads might try to add/remove the <i>same</i>
* object to/from the collection concurrently.
* See {@link ObjectLockingIndexedCollection} for details.
*
* @param collection A collection containing initial values to be indexed
* @param concurrencyLevel The estimated number of concurrently updating threads. 64 could be a sensible default
* @param backingSetFactory A factory which will create a concurrent {@link java.util.Set} in which objects
* added to the indexed collection will be stored
* @param <O> The type of objects in the collection
* @return An {@link IndexedCollection} initialized with objects from the given collection
*/
public static <O> IndexedCollection<O> copyFromObjectLocking(Collection<O> collection, int concurrencyLevel, Factory<Set<O>> backingSetFactory) {
IndexedCollection<O> indexedCollection = new ObjectLockingIndexedCollection<O>(backingSetFactory, concurrencyLevel);
indexedCollection.addAll(collection);
return indexedCollection;
}
/**
* Private constructor, not used.
*/
CQEngine() {
}
} | 10,121 | 50.121212 | 149 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/ConcurrentIndexedCollectionTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import com.googlecode.cqengine.testutil.Car;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.testutil.TestUtil.setOf;
import static java.util.Arrays.asList;
/**
* Unit tests for {@link ConcurrentIndexedCollection}. Note that tests for support behavior (such as query processing)
* which applies to all implementations of {@link IndexedCollection} can be found in
* {@link com.googlecode.cqengine.IndexedCollectionFunctionalTest}.
* <p/>
* In addition to the unit tests in this class, this class also runs a further several hundred unit tests in
* <a href="https://code.google.com/p/guava-libraries/source/browse/guava-testlib">guava-testlib</a> on the
* IndexedCollection to validate its compliance with the API specifications of java.util.Set.
*
* @author Niall Gallagher
*/
public class ConcurrentIndexedCollectionTest extends TestCase {
public static junit.framework.Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SetTestSuiteBuilder.using(onHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OnHeap_ConcurrentIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTest(SetTestSuiteBuilder.using(offHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OffHeap_ConcurrentIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTestSuite(ConcurrentIndexedCollectionTest.class);
return suite;
}
private static TestStringSetGenerator onHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>(OnHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(asList(elements));
return indexedCollection;
}
};
}
private static TestStringSetGenerator offHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>(OffHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(asList(elements));
return indexedCollection;
}
};
}
public void testUpdate() {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
Assert.assertTrue(indexedCollection.update(Collections.<String>emptyList(), asList("a", "b", "c")));
Assert.assertEquals(setOf("a", "b", "c"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asList("b"), Collections.<String>emptyList()));
Assert.assertEquals(setOf("a", "c"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asList("a"), asList("d")));
Assert.assertEquals(setOf("c", "d"), indexedCollection);
Assert.assertFalse(indexedCollection.update(asList("a"), Collections.<String>emptyList()));
Assert.assertEquals(setOf("c", "d"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asList("c", "e"), Collections.<String>emptyList()));
Assert.assertEquals(setOf("d"), indexedCollection);
}
public void testUpdate_IterableArguments() {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
Assert.assertTrue(indexedCollection.update(asIterable(Collections.<String>emptyList()), asIterable(asList("a", "b", "c"))));
Assert.assertEquals(setOf("a", "b", "c"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asIterable(asList("b")), asIterable(Collections.<String>emptyList())));
Assert.assertEquals(setOf("a", "c"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asIterable(asList("a")), asIterable(asList("d"))));
Assert.assertEquals(setOf("c", "d"), indexedCollection);
Assert.assertFalse(indexedCollection.update(asIterable(asList("a")), asIterable(Collections.<String>emptyList())));
Assert.assertEquals(setOf("c", "d"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asIterable(asList("c", "e")), asIterable(Collections.<String>emptyList())));
Assert.assertEquals(setOf("d"), indexedCollection);
Assert.assertTrue(indexedCollection.update(asIterable(Collections.<String>emptyList()), asIterable(asList("e", "d"))));
Assert.assertEquals(setOf("d", "e"), indexedCollection);
Assert.assertFalse(indexedCollection.update(asIterable(Collections.<String>emptyList()), asIterable(asList("e", "d"))));
Assert.assertEquals(setOf("d", "e"), indexedCollection);
}
public void testGetIndexes() {
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>();
indexedCollection.addIndex(HashIndex.onAttribute(Car.CAR_ID), noQueryOptions());
List<Index<Car>> indexes = new ArrayList<Index<Car>>();
for (Index<Car> index : indexedCollection.getIndexes()) {
indexes.add(index);
}
Assert.assertEquals(1, indexes.size());
Assert.assertEquals(HashIndex.class, indexes.get(0).getClass());
}
public void testRemoveIndex() {
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>();
HashIndex<Integer, Car> index = HashIndex.onAttribute(Car.CAR_ID);
indexedCollection.addIndex(index);
Assert.assertEquals(1, IteratorUtil.countElements(indexedCollection.getIndexes()));
indexedCollection.removeIndex(index);
Assert.assertEquals(0, IteratorUtil.countElements(indexedCollection.getIndexes()));
}
static <O> Iterable<O> asIterable(final Collection<O> collection) {
return new Iterable<O>() {
@Override
public Iterator<O> iterator() {
return collection.iterator();
}
};
}
}
| 7,766 | 45.789157 | 177 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/IndexedCollectionFunctionalTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.attribute.StandingQueryAttribute;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.index.compound.CompoundIndex;
import com.googlecode.cqengine.index.compound.support.CompoundValueTuple;
import com.googlecode.cqengine.index.disk.DiskIndex;
import com.googlecode.cqengine.index.disk.PartialDiskIndex;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.navigable.PartialNavigableIndex;
import com.googlecode.cqengine.index.offheap.OffHeapIndex;
import com.googlecode.cqengine.index.offheap.PartialOffHeapIndex;
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.standingquery.StandingQueryIndex;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.index.support.AbstractMapBasedAttributeIndex;
import com.googlecode.cqengine.index.support.indextype.DiskTypeIndex;
import com.googlecode.cqengine.index.support.indextype.OffHeapTypeIndex;
import com.googlecode.cqengine.index.unique.UniqueIndex;
import com.googlecode.cqengine.persistence.Persistence;
import com.googlecode.cqengine.persistence.composite.CompositePersistence;
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.quantizer.IntegerQuantizer;
import com.googlecode.cqengine.quantizer.Quantizer;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.*;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import com.googlecode.cqengine.testutil.DiskConcurrentIndexedCollection;
import com.googlecode.cqengine.testutil.OffHeapConcurrentIndexedCollection;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.AssumptionViolatedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.option.EngineThresholds.INDEX_ORDERING_SELECTIVITY;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*;
/**
* Tests CQEngine handing a wide range of queries, with different configurations of indexes.
*
* @author Niall Gallagher
*/
@RunWith(DataProviderRunner.class)
public class IndexedCollectionFunctionalTest {
static final Set<Car> REGULAR_DATASET = CarFactory.createCollectionOfCars(1000);
static final Set<Car> SMALL_DATASET = CarFactory.createCollectionOfCars(10);
// Note: Unfortunately ObjectLockingIndexedCollection can slow down the functional test a lot when
// disk indexes are in use (because it splits bulk inserts into a separate transaction per object).
// Set this true to skip the slow scenarios *during development only!*...
static final boolean SKIP_SLOW_SCENARIOS =
"true".equalsIgnoreCase(System.getProperty("cqengine.skip.slow.scenarios")) // system property
|| "true".equalsIgnoreCase(System.getenv("cqengine_skip_slow_scenarios")); // environment variable
static final boolean RUN_HIGH_PRIORITY_SCENARIOS_ONLY = false;
// Print progress of functional tests to the console at this frequency...
final int STATUS_UPDATE_FREQUENCY_MS = 1000;
static long lastStatusTimestamp = 0L;
// Macro scenarios specify sets of IndexedCollection implementations,
// sets of index combinations, and sets of queries. Macro scenarios will be expanded
// to many individual scenarios comprised of the distinct combinations of these sets.
// Each individual scenario resulting from the expansion will be run as a separate test.
// This allows to run the same set of queries with different combinations of indexes etc.
static List<MacroScenario> getMacroScenarios() {
return Arrays.asList(
new MacroScenario() {{
name = "typical queries";
dataSet = REGULAR_DATASET;
alsoEvaluateWithIndexMergeStrategy = true; // runs each of these scenarios twice to test with both the default merge strategy and with the index merge strategy
collectionImplementations = SKIP_SLOW_SCENARIOS
? classes(ConcurrentIndexedCollection.class, TransactionalIndexedCollection.class, OffHeapConcurrentIndexedCollection.class)
: classes(ConcurrentIndexedCollection.class, TransactionalIndexedCollection.class, OffHeapConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = equal(Car.CAR_ID, 500);
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(500);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 500, 500);
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(500);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 998, 2000);
expectedResults = new ExpectedResults() {{
size = 2;
carIdsAnyOrder = asSet(998, 999);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, -10, 2);
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(0, 1, 2);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 499, 501);
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(499, 500, 501);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 407, 683);
expectedResults = new ExpectedResults() {{
size = 277;
carIdsAnyOrder = integersBetween(407, 683);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 407, true, 683, true);
expectedResults = new ExpectedResults() {{
size = 277;
carIdsAnyOrder = integersBetween(407, 683);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 407, false, 683, true);
expectedResults = new ExpectedResults() {{
size = 276;
carIdsAnyOrder = integersBetween(408, 683);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 407, true, 683, false);
expectedResults = new ExpectedResults() {{
size = 276;
carIdsAnyOrder = integersBetween(407, 682);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 407, false, 683, false);
expectedResults = new ExpectedResults() {{
size = 275;
carIdsAnyOrder = integersBetween(408, 682);
}};
}},
new QueryToEvaluate() {{
query = lessThan(Car.CAR_ID, 5);
expectedResults = new ExpectedResults() {{
size = 5;
carIdsAnyOrder = integersBetween(0, 4);
}};
}},
new QueryToEvaluate() {{
query = lessThanOrEqualTo(Car.CAR_ID, 5);
expectedResults = new ExpectedResults() {{
size = 6;
carIdsAnyOrder = integersBetween(0, 5);
}};
}},
new QueryToEvaluate() {{
query = greaterThan(Car.CAR_ID, 995);
expectedResults = new ExpectedResults() {{
size = 4;
carIdsAnyOrder = integersBetween(996, 999);
}};
}},
new QueryToEvaluate() {{
query = greaterThanOrEqualTo(Car.CAR_ID, 995);
expectedResults = new ExpectedResults() {{
size = 5;
carIdsAnyOrder = integersBetween(995, 999);
}};
}},
new QueryToEvaluate() {{
query = in(Car.CAR_ID, 5, 463, 999);
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(5, 463, 999);
}};
}},
new QueryToEvaluate() {{
query = in(Car.CAR_ID, -10, 5, 463, 999, 1500);
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(5, 463, 999);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
expectedResults = new ExpectedResults() {{
size = 1000;
carIdsAnyOrder = integersBetween(0, 999);
}};
}},
new QueryToEvaluate() {{
query = none(Car.class);
expectedResults = new ExpectedResults() {{
size = 0;
}};
}},
new QueryToEvaluate() {{
query = and(between(Car.CAR_ID, 400, 500), lessThan(Car.CAR_ID, 450));
expectedResults = new ExpectedResults() {{
containsCarIds = asSet(400, 449);
doesNotContainCarIds = asSet(399, 450, 501);
}};
}},
new QueryToEvaluate() {{
query = and(between(Car.CAR_ID, 400, 500), not(greaterThan(Car.CAR_ID, 450)));
expectedResults = new ExpectedResults() {{
containsCarIds = asSet(400, 450, 449);
doesNotContainCarIds = asSet(11, 399, 451, 501);
}};
}},
new QueryToEvaluate() {{
query = or(between(Car.CAR_ID, 400, 500), between(Car.CAR_ID, 450, 550));
expectedResults = new ExpectedResults() {{
containsCarIds = integersBetween(400, 550);
doesNotContainCarIds = asSet(399, 551);
}};
}},
new QueryToEvaluate() {{
query = not(greaterThan(Car.CAR_ID, 450));
expectedResults = new ExpectedResults() {{
containsCarIds = asSet(1, 449, 450);
doesNotContainCarIds = asSet(451);
}};
}},
new QueryToEvaluate() {{
query = equal(Car.FEATURES, "hybrid");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 200;
containsCarIds = asSet(1, 7);
doesNotContainCarIds = asSet(0, 2, 3, 4, 5, 6, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = in(Car.FEATURES, "hybrid", "coupe");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(1, 7, 9);
doesNotContainCarIds = asSet(0, 2, 3, 4, 5, 6, 8);
}};
}},
new QueryToEvaluate() {{
query = between(Car.FEATURES, "grade a", "grade c"); // note: lexicographically between
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(2, 3, 4);
doesNotContainCarIds = asSet(0, 1, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = between(Car.FEATURES, "grade a", false, "grade c", true); // note: lexicographically between
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 200;
containsCarIds = asSet(3, 4);
doesNotContainCarIds = asSet(0, 1, 2, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = between(Car.FEATURES, "grade a", true, "grade c", false); // note: lexicographically between
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 200;
containsCarIds = asSet(2, 3);
doesNotContainCarIds = asSet(0, 1, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = between(Car.FEATURES, "grade a", false, "grade c", false); // note: lexicographically between
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(3);
doesNotContainCarIds = asSet(0, 1, 2, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = and(greaterThan(Car.FEATURES, "grade a"), lessThan(Car.FEATURES, "grade c"));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(3);
doesNotContainCarIds = asSet(0, 1, 2, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = and(greaterThanOrEqualTo(Car.FEATURES, "grade a"), lessThanOrEqualTo(Car.FEATURES, "grade c"));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(2, 3, 4);
doesNotContainCarIds = asSet(0, 1, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = startsWith(Car.FEATURES, "grade");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(2, 3, 4);
doesNotContainCarIds = asSet(0, 1, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = startsWith(Car.MANUFACTURER, "Hon");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(3, 4, 5);
doesNotContainCarIds = asSet(0, 1, 2, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = contains(Car.FEATURES, "ade");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(2, 3, 4);
doesNotContainCarIds = asSet(0, 1, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = contains(Car.MANUFACTURER, "on");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(3, 4, 5);
doesNotContainCarIds = asSet(0, 1, 2, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = isContainedIn(Car.MANUFACTURER, "I would like to buy a Honda car");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(3, 4, 5);
doesNotContainCarIds = asSet(0, 1, 2, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = and(lessThan(Car.CAR_ID, 100), or(none(Car.class), isContainedIn(Car.MANUFACTURER, "I would like to buy a Honda car")));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 30;
containsCarIds = asSet(3, 4, 5);
doesNotContainCarIds = asSet(0, 1, 2, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = isContainedIn(Car.FEATURES, "I would like a coupe or a sunroof please");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 200;
containsCarIds = asSet(7, 9);
doesNotContainCarIds = asSet(0, 1, 2, 3, 4, 5, 6, 8);
}};
}},
new QueryToEvaluate() {{
query = matchesRegex(Car.MODEL, "F.+n");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(0, 2, 3, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = matchesRegex(Car.FEATURES, ".*ade.*");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 300;
containsCarIds = asSet(2, 3, 4);
doesNotContainCarIds = asSet(0, 1, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = or(between(Car.CAR_ID, 400, 500), between(Car.CAR_ID, 450, 550));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 151;
containsCarIds = integersBetween(400, 550);
doesNotContainCarIds = asSet(399, 551);
}};
}},
new QueryToEvaluate() {{
query = or(between(Car.CAR_ID, 400, 500), between(Car.CAR_ID, 450, 550));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 151;
containsCarIds = integersBetween(400, 550);
doesNotContainCarIds = asSet(399, 551);
}};
}},
new QueryToEvaluate() {{
query = or(between(Car.CAR_ID, 400, 450), or(between(Car.CAR_ID, 451, 499), between(Car.CAR_ID, 500, 550)));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 151;
containsCarIds = integersBetween(400, 550);
doesNotContainCarIds = asSet(399, 551);
}};
}},
new QueryToEvaluate() {{
query = endsWith(Car.FEATURES, "roof");
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(7);
doesNotContainCarIds = asSet(0, 1, 2, 3, 4, 5, 6, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = endsWith(Car.MODEL, "sight");
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(5);
doesNotContainCarIds = asSet(0, 1, 2, 3, 4, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = and(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Fusion"));
expectedResults = new ExpectedResults() {{
size = 100;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(0, 2, 3, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = and(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "XXX"));
expectedResults = new ExpectedResults() {{
size = 0;
}};
}},
new QueryToEvaluate() {{
query = has(Car.FEATURES);
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 600;
containsCarIds = asSet(1, 2, 3, 4, 7, 9);
doesNotContainCarIds = asSet(0, 5, 6, 8);
}};
}},
new QueryToEvaluate() {{
query = has(Car.FEATURES);
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 600;
containsCarIds = asSet(1, 2, 3, 4, 7, 9);
doesNotContainCarIds = asSet(0, 5, 6, 8);
}};
}},
new QueryToEvaluate() {{
query = has(Car.MANUFACTURER);
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION));
expectedResults = new ExpectedResults() {{
size = 1000;
}};
}},
new QueryToEvaluate() {{
query = has(Car.MANUFACTURER);
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 1000;
}};
}},
new QueryToEvaluate() {{
query = isPrefixOf(Car.MANUFACTURER, "BMW2");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 100;
}};
}}
);
indexCombinations = indexCombinations(
noIndexes(),
indexCombination(UniqueIndex.onAttribute(Car.CAR_ID)),
indexCombination(HashIndex.onAttribute(Car.CAR_ID)),
indexCombination(HashIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID)),
indexCombination(NavigableIndex.onAttribute(Car.CAR_ID)),
indexCombination(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID)),
indexCombination(NavigableIndex.onAttribute(Car.FEATURES)),
indexCombination(HashIndex.onAttribute(Car.FEATURES)),
indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.MODEL)),
indexCombination(CompoundIndex.withQuantizerOnAttributes(new Quantizer<CompoundValueTuple<Car>>() {
@Override
public CompoundValueTuple<Car> getQuantizedValue(CompoundValueTuple<Car> tuple) {
Iterator<Object> tupleValues = tuple.getAttributeValues().iterator();
String manufacturer = (String) tupleValues.next();
String model = (String) tupleValues.next();
String quantizedModel = "Focus".equals(model) ? "Focus" : "Other";
return new CompoundValueTuple<Car>(Arrays.asList(manufacturer, quantizedModel));
}
}, Car.MANUFACTURER, Car.MODEL)
),
indexCombination(OffHeapIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(DiskIndex.onAttribute(Car.FEATURES)),
indexCombination(DiskIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(OffHeapIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "comparative queries";
dataSet = SMALL_DATASET;
alsoEvaluateWithIndexMergeStrategy = false;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = min(Car.PRICE); // will invoke Min.getMatchesForSimpleAttribute() for the noIndexes() scenario
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(4); // car with the lowest price
}};
}},
new QueryToEvaluate() {{
query = max(Car.PRICE); // will invoke Max.getMatchesForSimpleAttribute() for the noIndexes() scenario
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(9); // car with the highest price
}};
}},
new QueryToEvaluate() {{
query = min(Car.DOORS);
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(9); // cars with 2 doors
}};
}},
new QueryToEvaluate() {{
query = max(Car.DOORS);
expectedResults = new ExpectedResults() {{
size = 5;
carIdsAnyOrder = asSet(0, 3, 4, 6, 8); // cars with 5 doors
}};
}},
new QueryToEvaluate() {{
query = min(Car.KEYWORDS); // will invoke Min.getMatchesForNonSimpleAttribute() for the noIndexes() scenario
expectedResults = new ExpectedResults() {{
size = 2;
carIdsAnyOrder = asSet(2, 5); // cars with keyword "alpha"
}};
}},
new QueryToEvaluate() {{
query = max(Car.KEYWORDS); // will invoke Max.getMatchesForNonSimpleAttribute() for the noIndexes() scenario
expectedResults = new ExpectedResults() {{
size = 2;
carIdsAnyOrder = asSet(1, 9); // cars with keyword "zulu"
}};
}},
new QueryToEvaluate() {{
query = longestPrefix(Car.KEYWORDS, "very-good-car-indeed");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 2;
carIdsAnyOrder = asSet(6, 8); // cars with keyword "very-good-car" and not keyword "very-good"
}};
}},
new QueryToEvaluate() {{
query = longestPrefix(Car.MANUFACTURER, "Toyota2");
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(6, 7, 8);
}};
}},
// Test comparative queries enclosed in logical queries...
new QueryToEvaluate() {{
query = and(all(Car.class), min(Car.PRICE));
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(4);
}};
}},
new QueryToEvaluate() {{
query = and(none(Car.class), min(Car.PRICE));
expectedResults = new ExpectedResults() {{
size = 0;
}};
}},
new QueryToEvaluate() {{
query = or(none(Car.class), min(Car.PRICE));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 1;
carIdsAnyOrder = asSet(4);
}};
}},
new QueryToEvaluate() {{
query = or(all(Car.class), min(Car.PRICE));
queryOptions = queryOptions(deduplicate(DeduplicationStrategy.MATERIALIZE));
expectedResults = new ExpectedResults() {{
size = 10;
}};
}},
new QueryToEvaluate() {{
query = not(min(Car.PRICE));
expectedResults = new ExpectedResults() {{
size = 9;
}};
}}
);
indexCombinations = indexCombinations(
noIndexes(),
indexCombination(NavigableIndex.onAttribute(Car.PRICE)),
indexCombination(NavigableIndex.onAttribute(Car.KEYWORDS)),
indexCombination(InvertedRadixTreeIndex.onAttribute(Car.KEYWORDS))
);
}},
new MacroScenario() {{
name = "off-heap collection";
dataSet = SMALL_DATASET;
collectionImplementations = classes(OffHeapConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = in(Car.CAR_ID, 3, 4, 5);
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(3, 4, 5);
indexUsed = true; // An index should be used, because OffHeapPersistence creates an index on primary key
mergeCost = 3;
}};
}}
);
indexCombinations = indexCombinations(
noIndexes()
);
}},
new MacroScenario() {{
name = "off-heap index";
dataSet = SMALL_DATASET;
collectionImplementations = classes(OffHeapConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
mergeCost = 3;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(OffHeapIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "disk index";
dataSet = SMALL_DATASET;
collectionImplementations = classes(DiskConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
mergeCost = 3;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(DiskIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "merge cost without indexes";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = false;
mergeCost = Integer.MAX_VALUE;
}};
}}
);
indexCombinations = indexCombinations(noIndexes());
}},
new MacroScenario() {{
name = "merge costs with indexes";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
mergeCost = 3;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(HashIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(NavigableIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(DiskIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "retrieval cost without indexes";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = Integer.MAX_VALUE;
}};
}}
);
indexCombinations = indexCombinations(noIndexes());
}},
new MacroScenario() {{
name = "retrieval cost with HashIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 30;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(HashIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with NavigableIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 40;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(NavigableIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with RadixTreeIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 50;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with ReversedRadixTreeIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 51;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with InvertedRadixTreeIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 52;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with SuffixTreeIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
retrievalCost = 53;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER)));
}},
new MacroScenario() {{
name = "retrieval cost with CompoundIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(equal(Car.MANUFACTURER, "Ford"), equal(Car.MODEL, "Fusion"));
expectedResults = new ExpectedResults() {{
retrievalCost = 20;
mergeCost = 1;
}};
}}
);
indexCombinations = indexCombinations(indexCombination(CompoundIndex.onAttributes(Car.MANUFACTURER, Car.MODEL)));
}},
new MacroScenario() {{
name = "retrieval cost with PartialNavigableIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(greaterThan(Car.PRICE, 4000.0), equal(Car.MANUFACTURER, "Ford"));
expectedResults = new ExpectedResults() {{
retrievalCost = 35; // 40 from NavigableIndex, -5 from PartialIndex
mergeCost = 2;
size = 2;
carIdsAnyOrder = asSet(0, 2);
}};
}}
);
indexCombinations = indexCombinations(indexCombination(
PartialNavigableIndex.onAttributeWithFilterQuery(Car.PRICE, equal(Car.MANUFACTURER, "Ford"))
));
}},
new MacroScenario() {{
name = "retrieval cost with PartialOffHeapIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(greaterThan(Car.PRICE, 4000.0), equal(Car.MANUFACTURER, "Ford"));
expectedResults = new ExpectedResults() {{
retrievalCost = 65; // 80 from SQLiteIndex, -10 from OffHeapIndex, -5 from PartialIndex
mergeCost = 2;
size = 2;
carIdsAnyOrder = asSet(0, 2);
}};
}}
);
indexCombinations = indexCombinations(indexCombination(
PartialOffHeapIndex.onAttributeWithFilterQuery(Car.PRICE, equal(Car.MANUFACTURER, "Ford"))
));
}},
new MacroScenario() {{
name = "retrieval cost with PartialDiskIndex";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(greaterThan(Car.PRICE, 4000.0), equal(Car.MANUFACTURER, "Ford"));
expectedResults = new ExpectedResults() {{
retrievalCost = 85; // 80 from SQLiteIndex, +10 from DiskIndex, -5 from PartialIndex
mergeCost = 2;
size = 2;
carIdsAnyOrder = asSet(0, 2);
}};
}}
);
indexCombinations = indexCombinations(indexCombination(
PartialDiskIndex.onAttributeWithFilterQuery(Car.PRICE, equal(Car.MANUFACTURER, "Ford"))
));
}},
new MacroScenario() {{
name = "string queries 1";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = startsWith(Car.MANUFACTURER, "For");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(5, 8);
}};
}},
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(5, 8);
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "string queries 2";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = endsWith(Car.MANUFACTURER, "ord");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(5, 8);
}};
}},
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(5, 8);
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "string queries 3";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = contains(Car.MANUFACTURER, "on");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(3, 4, 5);
indexUsed = true;
}};
}},
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 3;
mergeCost = 3;
carIdsAnyOrder = asSet(0, 1, 2);
indexUsed = true;
containsCarIds = asSet(1);
doesNotContainCarIds = asSet(5, 8);
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "ordering";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = in(Car.MANUFACTURER, "Ford", "Toyota");
queryOptions = queryOptions(orderBy(descending(Car.MANUFACTURER), ascending(Car.CAR_ID)));
expectedResults = new ExpectedResults() {{
size = 6;
carIdsInOrder = asList(6, 7, 8, 0, 1, 2);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Ascending regular order: <cars with no features> <cars with features in ascending feature order>
queryOptions = queryOptions(orderBy(ascending(Car.FEATURES), descending(Car.CAR_ID)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(8, 6, 5, 0, 9, 2, 3, 4, 1, 7);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Ascending missingLast order: <cars with features in ascending feature order> <cars with no features>
queryOptions = queryOptions(orderBy(ascending(missingLast(Car.FEATURES)), descending(Car.CAR_ID)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(9, 2, 3, 4, 1, 7, 8, 6, 5, 0);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Descending regular order: <cars with features in descending feature order> <cars with no features>
queryOptions = queryOptions(orderBy(descending(Car.FEATURES), descending(Car.CAR_ID)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(7, 1, 4, 3, 2, 9, 8, 6, 5, 0);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Descending missingFirst order: <cars with no features> <cars with features in descending feature order>
queryOptions = queryOptions(orderBy(descending(missingFirst(Car.FEATURES)), descending(Car.CAR_ID)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(8, 6, 5, 0, 7, 1, 4, 3, 2, 9);
}};
}}
);
indexCombinations = indexCombinations(
noIndexes(),
indexCombination(
NavigableIndex.onAttribute(Car.CAR_ID),
NavigableIndex.onAttribute(Car.FEATURES),
NavigableIndex.onAttribute(forObjectsMissing(Car.FEATURES))
)
);
}},
new MacroScenario() {{
name = "index ordering";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = asList(
// Force use of the index ordering strategy (set selectivity threshold = 1.0)...
new QueryToEvaluate() {{
query = all(Car.class);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 4, 6);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(4, 5, 6);
}};
}},
new QueryToEvaluate() {{
query = lessThan(Car.CAR_ID, 6);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 6;
carIdsInOrder = asList(0, 1, 2, 3, 4, 5);
}};
}},
new QueryToEvaluate() {{
query = lessThanOrEqualTo(Car.CAR_ID, 6);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 7;
carIdsInOrder = asList(0, 1, 2, 3, 4, 5, 6);
}};
}},
new QueryToEvaluate() {{
query = greaterThan(Car.CAR_ID, 3);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 6;
carIdsInOrder = asList(4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = greaterThanOrEqualTo(Car.CAR_ID, 3);
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 7;
carIdsInOrder = asList(3, 4, 5, 6, 7, 8, 9);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 4, 6);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(6, 5, 4);
}};
}},
new QueryToEvaluate() {{
query = lessThan(Car.CAR_ID, 6);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 6;
carIdsInOrder = asList(5, 4 ,3 ,2 ,1, 0);
}};
}},
new QueryToEvaluate() {{
query = lessThanOrEqualTo(Car.CAR_ID, 6);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 7;
carIdsInOrder = asList(6, 5, 4 ,3 ,2 ,1, 0);
}};
}},
new QueryToEvaluate() {{
query = greaterThan(Car.CAR_ID, 3);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 6;
carIdsInOrder = asList(9, 8, 7, 6, 5, 4);
}};
}},
new QueryToEvaluate() {{
query = greaterThanOrEqualTo(Car.CAR_ID, 3);
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 7;
carIdsInOrder = asList(9, 8, 7, 6, 5, 4, 3);
}};
}},
new QueryToEvaluate() {{
query = and(greaterThanOrEqualTo(Car.CAR_ID, 3), lessThanOrEqualTo(Car.CAR_ID, 6));
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 4;
carIdsInOrder = asList(6, 5, 4, 3);
}};
}},
new QueryToEvaluate() {{
query = or(greaterThanOrEqualTo(Car.CAR_ID, 7), none(Car.class));
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(9, 8, 7);
}};
}},
new QueryToEvaluate() {{
query = and(or(greaterThanOrEqualTo(Car.CAR_ID, 7), none(Car.class)), or(all(Car.class), none(Car.class)));
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(9, 8, 7);
}};
}},
new QueryToEvaluate() {{
query = and(equal(Car.CAR_ID, 8), all(Car.class));
queryOptions = queryOptions(orderBy(ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 1;
carIdsInOrder = singletonList(8);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Should order cars without any features first, followed by cars with features
// in ascending alphabetical order of feature string...
queryOptions = queryOptions(orderBy(ascending(Car.FEATURES), ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(0, 5, 6, 8, 9, 2, 3, 4, 1, 7);
}};
}},
new QueryToEvaluate() {{
query = all(Car.class);
// Should order cars without any features last, preceded by cars with features
// in descending alphabetical order of feature string...
queryOptions = queryOptions(orderBy(descending(Car.FEATURES), ascending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 10;
carIdsInOrder = asList(7, 1, 4, 3, 2, 9, 0, 5, 6, 8);
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(
NavigableIndex.onAttribute(Car.CAR_ID),
NavigableIndex.onAttribute(Car.FEATURES),
NavigableIndex.onAttribute(forObjectsMissing(Car.FEATURES))
),
indexCombination(OffHeapIndex.onAttribute(Car.CAR_ID))
);
}},
new MacroScenario() {{
name = "index ordering strategy selection";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = asList(
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 4, 6); // querySelectivity = 1.0 - 3/10 = 0.7
queryOptions = queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.PRICE)),
applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 0.8))); // selectivityThreshold = 0.8 -> use index ordering
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(5, 4, 6);
containsQueryLogMessages = asList("querySelectivity: 0.7", "orderingStrategy: index");
}};
}},
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 4, 6); // querySelectivity = 1.0 - 3/10 = 0.7
queryOptions = queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.PRICE)),
applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 0.6))); // selectivityThreshold = 0.6 -> use materialize ordering
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(5, 4, 6);
containsQueryLogMessages = asList("querySelectivity: 0.7", "orderingStrategy: materialize");
}};
}}//, TODO: the following test is disabled until index ordering support is enabled by default...
// new QueryToEvaluate() {{
// query = between(Car.CAR_ID, 4, 6); // querySelectivity = 1.0 - 3/10 = 0.7
// queryOptions = queryOptions(orderBy(ascending(Car.MANUFACTURER), descending(Car.PRICE))); // selectivityThreshold = default of 0.5 -> use materialize ordering
// expectedResults = new ExpectedResults() {{
// size = 3;
// carIdsInOrder = asList(5, 4, 6);
// containsQueryLogMessages = asList("querySelectivity: 0.7", "orderingStrategy: materialize");
// }};
// }}
);
indexCombinations = indexCombinations(
indexCombination(
NavigableIndex.onAttribute(Car.CAR_ID),
NavigableIndex.onAttribute(Car.MANUFACTURER),
NavigableIndex.onAttribute(Car.PRICE)
)
);
}},
new MacroScenario() {{
name = "index ordering strategy selection - negative";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = asList(
// Try to force use of the index ordering strategy (set selectivity threshold = 1.0),
// however it will not actually be used...
new QueryToEvaluate() {{
query = between(Car.CAR_ID, 4, 6); // querySelectivity = 1.0 - 3/10 = 0.7
queryOptions = queryOptions(orderBy(descending(Car.CAR_ID)), applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0)));
expectedResults = new ExpectedResults() {{
size = 3;
carIdsInOrder = asList(6, 5, 4);
// The materialize strategy will be used instead because the index is quantized...
containsQueryLogMessages = singletonList("orderingStrategy: materialize");
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(5), Car.CAR_ID))
);
}},
new MacroScenario() {{
name = "remove objects";
dataSet = REGULAR_DATASET;
removeDataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 297;
doesNotContainCarIds = asSet(0, 1, 2);
containsCarIds = asSet(10, 11, 12);
}};
}}
);
indexCombinations = indexCombinations(
noIndexes(),
indexCombination(UniqueIndex.onAttribute(Car.CAR_ID)),
indexCombination(HashIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(NavigableIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(OffHeapIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "clear objects";
dataSet = REGULAR_DATASET;
clearDataSet = true;
collectionImplementations = classes(ConcurrentIndexedCollection.class, ObjectLockingIndexedCollection.class, TransactionalIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = equal(Car.MANUFACTURER, "Ford");
expectedResults = new ExpectedResults() {{
size = 0;
}};
}}
);
indexCombinations = indexCombinations(
noIndexes(),
indexCombination(UniqueIndex.onAttribute(Car.CAR_ID)),
indexCombination(HashIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(NavigableIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(RadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(SuffixTreeIndex.onAttribute(Car.MANUFACTURER)),
indexCombination(OffHeapIndex.onAttribute(Car.MANUFACTURER))
);
}},
new MacroScenario() {{
name = "standing query index on entire query";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE));
expectedResults = new ExpectedResults() {{
size = 5;
retrievalCost = 10;
mergeCost = 5;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(StandingQueryIndex.onQuery(or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE))))
);
}},
new MacroScenario() {{
name = "standing query index on nested logical query";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(all(Car.class), or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE)));
expectedResults = new ExpectedResults() {{
size = 5;
retrievalCost = 10;
mergeCost = 5;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(StandingQueryIndex.onQuery(or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE))))
);
}},
new MacroScenario() {{
name = "standing query index on nested simple query";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = and(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.RED));
expectedResults = new ExpectedResults() {{
size = 2;
retrievalCost = 10;
mergeCost = 3; // there are 3 RED cars in total (although only 2 of them are Ford)
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(StandingQueryIndex.onQuery(equal(Car.COLOR, Car.Color.RED)))
);
}},
new MacroScenario() {{
name = "HashIndex on standing query";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE));
expectedResults = new ExpectedResults() {{
size = 5;
retrievalCost = 30;
mergeCost = 5;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(HashIndex.onAttribute(forStandingQuery(or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE)))))
);
}},
new MacroScenario() {{
name = "OffHeapIndex on standing query";
dataSet = SMALL_DATASET;
collectionImplementations = classes(ConcurrentIndexedCollection.class);
queriesToEvaluate = singletonList(
new QueryToEvaluate() {{
query = or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE));
expectedResults = new ExpectedResults() {{
size = 5;
retrievalCost = 70; // 80 from SQLiteIndex, -10 from OffHeapIndex
mergeCost = 5;
}};
}}
);
indexCombinations = indexCombinations(
indexCombination(OffHeapIndex.onAttribute(forStandingQuery(
or(equal(Car.MANUFACTURER, "Ford"), equal(Car.COLOR, Car.Color.BLUE))
))
)
);
}}
);
}
private static SimpleAttribute<Integer, Car> createForeignKeyAttribute() {
return new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(final Integer carId, final QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
};
}
static class MacroScenario {
String name = "<unnamed>";
Collection<Car> dataSet = Collections.emptySet();
Collection<Car> removeDataSet = Collections.emptySet();
Boolean clearDataSet = false;
Boolean alsoEvaluateWithIndexMergeStrategy = false;
Iterable<? extends QueryToEvaluate> queriesToEvaluate = Collections.emptyList();
Iterable<Class> collectionImplementations;
Iterable<Iterable<Index>> indexCombinations;
}
public static class Scenario {
String name = "<unnamed>";
Integer lineNumber;
Long startTime;
Integer scenarioNumber;
AtomicInteger totalScenarioCount;
Collection<Car> dataSet = Collections.emptySet();
Collection<Car> removeDataSet = Collections.emptySet();
Boolean clearDataSet = false;
Query<Car> query = none(Car.class);
QueryOptions queryOptions = noQueryOptions();
ExpectedResults expectedResults = null;
Class collectionImplementation;
Iterable<Index> indexCombination;
boolean useIndexMergeStrategy = false;
boolean highPriority = false;
@Override
public String toString() {
return "[" +
"name='" + name + '\'' +
", line=" + lineNumber +
", collection=" + collectionImplementation.getSimpleName().replace("IndexedCollection", "").toLowerCase() +
", indexes=" + getIndexDescriptions(indexCombination) +
", mergeStrategy=" + (useIndexMergeStrategy ? "index" : "default") +
", query=" + query +
", queryOptions=" + queryOptions +
", dataSet=<" + dataSet.size() + " items>" +
", removeDataSet=<" + removeDataSet.size() + " items>" +
", clearDataSet=" + clearDataSet +
", expectedResults=" + expectedResults +
']';
}
}
@DataProvider
public static List<List<Object>> expandMacroScenarios() {
List<MacroScenario> macroScenarios = getMacroScenarios();
List<List<Object>> scenarios = new ArrayList<List<Object>>();
final long finalStartTime = System.currentTimeMillis();
final AtomicInteger scenarioCount = new AtomicInteger();
for (int i = 0; i < macroScenarios.size(); i++) {
final MacroScenario macroScenario = macroScenarios.get(i);
try {
for (final Class currentCollectionImplementation : macroScenario.collectionImplementations) {
for (final Iterable<Index> currentIndexCombination : macroScenario.indexCombinations) {
for (final QueryToEvaluate currentQueryToEvaluate : macroScenario.queriesToEvaluate) {
Scenario scenario = new Scenario() {{
name = macroScenario.name;
lineNumber = currentQueryToEvaluate.lineNumber;
startTime = finalStartTime;
scenarioNumber = scenarioCount.incrementAndGet();
totalScenarioCount = scenarioCount;
dataSet = macroScenario.dataSet;
removeDataSet = macroScenario.removeDataSet;
clearDataSet = macroScenario.clearDataSet;
query = currentQueryToEvaluate.query;
queryOptions = currentQueryToEvaluate.queryOptions;
expectedResults = currentQueryToEvaluate.expectedResults;
collectionImplementation = currentCollectionImplementation;
indexCombination = currentIndexCombination;
highPriority = currentQueryToEvaluate.highPriority;
}};
scenarios.add(Collections.<Object>singletonList(scenario));
if (macroScenario.alsoEvaluateWithIndexMergeStrategy) {
Scenario scenarioWithIndexMergeStrategy = new Scenario() {{
name = macroScenario.name;
lineNumber = currentQueryToEvaluate.lineNumber;
startTime = finalStartTime;
scenarioNumber = scenarioCount.incrementAndGet();
totalScenarioCount = scenarioCount;
dataSet = macroScenario.dataSet;
removeDataSet = macroScenario.removeDataSet;
clearDataSet = macroScenario.clearDataSet;
query = currentQueryToEvaluate.query;
queryOptions = currentQueryToEvaluate.queryOptions;
expectedResults = currentQueryToEvaluate.expectedResults;
collectionImplementation = currentCollectionImplementation;
indexCombination = currentIndexCombination;
highPriority = currentQueryToEvaluate.highPriority;
useIndexMergeStrategy = true;
}};
scenarios.add(Collections.<Object>singletonList(scenarioWithIndexMergeStrategy));
}
}
}
}
} catch (Exception e) {
throw new IllegalStateException("Configuration issue for MacroScenario " + i + " in the list: " + macroScenario.name, e);
}
}
if (SKIP_SLOW_SCENARIOS) {
System.out.println(" === Note: slow scenarios in the functional test are disabled ===");
} else {
System.out.println(" === Note: all scenarios in the functional test are enabled ===\n To skip slow scenarios, run with: -Dcqengine.skip.slow.scenarios=true");
}
return scenarios;
}
@Test
@UseDataProvider(value = "expandMacroScenarios")
@SuppressWarnings("unchecked")
public void testScenario(Scenario scenario) {
if (RUN_HIGH_PRIORITY_SCENARIOS_ONLY && !scenario.highPriority) {
throw new AssumptionViolatedException("Skipping non-high priority scenario");
}
if (!IndexedCollection.class.isAssignableFrom(scenario.collectionImplementation)) {
throw new IllegalStateException("Invalid IndexedCollection class: " + scenario.collectionImplementation);
}
boolean hasDiskIndex = false, hasOffHeapIndex = false;
for (Index<Car> index : scenario.indexCombination) {
if (index instanceof DiskTypeIndex) {
hasDiskIndex = true;
}
else if (index instanceof OffHeapTypeIndex) {
hasOffHeapIndex = true;
}
}
Persistence<Car, Integer> persistence;
if (hasDiskIndex && hasOffHeapIndex) {
persistence = CompositePersistence.of(OffHeapPersistence.onPrimaryKey(Car.CAR_ID), DiskPersistence.onPrimaryKey(Car.CAR_ID));
}
else if (hasDiskIndex) {
persistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
}
else if (hasOffHeapIndex) {
persistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
}
else {
persistence = OnHeapPersistence.onPrimaryKey(Car.CAR_ID);
}
IndexedCollection<Car> indexedCollection;
try {
if (TransactionalIndexedCollection.class.isAssignableFrom(scenario.collectionImplementation)) {
indexedCollection = (IndexedCollection<Car>) scenario.collectionImplementation.getConstructor(Class.class, Persistence.class).newInstance(Car.class, persistence);
}
else if (OffHeapConcurrentIndexedCollection.class.isAssignableFrom(scenario.collectionImplementation)) {
if (!(persistence instanceof OffHeapTypeIndex)) {
persistence = CompositePersistence.of(OffHeapPersistence.onPrimaryKey(Car.CAR_ID), persistence);
}
indexedCollection = (IndexedCollection<Car>) scenario.collectionImplementation.getConstructor(Persistence.class).newInstance(persistence);
}
else {
indexedCollection = (IndexedCollection<Car>) scenario.collectionImplementation.getConstructor(Persistence.class).newInstance(persistence);
}
}
catch (Exception e) {
throw new IllegalStateException("Could not instantiate IndexedCollection: " + scenario.collectionImplementation, e);
}
for (Index<Car> index : scenario.indexCombination) {
if (!persistenceProvidesEquivalentIndexAlready(persistence, index)) {
try {
indexedCollection.addIndex(index);
}
catch (Exception e) {
throw new IllegalStateException("Could not add " + getIndexDescription(index) + " with persistence type: " + persistence, e);
}
}
}
indexedCollection.addAll(scenario.dataSet);
indexedCollection.removeAll(scenario.removeDataSet);
if (scenario.clearDataSet) {
indexedCollection.clear();
}
FlagsEnabled flagsEnabled = scenario.queryOptions.get(FlagsEnabled.class);
if (flagsEnabled == null) {
flagsEnabled = new FlagsEnabled();
}
if (scenario.useIndexMergeStrategy) {
flagsEnabled.add(EngineFlags.PREFER_INDEX_MERGE_STRATEGY);
}
else {
flagsEnabled.remove(EngineFlags.PREFER_INDEX_MERGE_STRATEGY);
}
scenario.queryOptions.put(FlagsEnabled.class, flagsEnabled);
try {
evaluateQuery(indexedCollection, scenario.query, scenario.queryOptions, scenario.expectedResults);
}
catch (RuntimeException e) {
System.err.println("Failed scenario: " + scenario);
throw e;
}
catch (AssertionError e) {
System.err.println("Failed scenario: " + scenario);
throw e;
}
finally {
int scenarioNumber = scenario.scenarioNumber;
int totalScenarioCount = scenario.totalScenarioCount.get();
long currentTime = System.currentTimeMillis();
if ((currentTime - lastStatusTimestamp) >= STATUS_UPDATE_FREQUENCY_MS || scenarioNumber == totalScenarioCount || scenarioNumber == 1) {
double fractionComplete = ((double) scenarioNumber) / totalScenarioCount;
long elapsedTime = currentTime - scenario.startTime;
System.out.format(" Scenario %d of %d :: %d seconds elapsed :: %d%% complete", scenarioNumber, totalScenarioCount, elapsedTime / 1000, (int)(fractionComplete * 100));
System.out.print(scenarioNumber == totalScenarioCount ? "\n" : "\r");
lastStatusTimestamp = currentTime;
}
if (persistence instanceof CompositePersistence) {
CompositePersistence compositePersistence = (CompositePersistence) persistence;
closePersistenceIfNecessary(compositePersistence.getPrimaryPersistence());
closePersistenceIfNecessary(compositePersistence.getSecondaryPersistence());
List<? extends Persistence<Car, Integer>> additionalPersistences = compositePersistence.getAdditionalPersistences();
for (Persistence<Car, Integer> additionalPersistence : additionalPersistences) {
closePersistenceIfNecessary(additionalPersistence);
}
}
else {
closePersistenceIfNecessary(persistence);
}
}
}
static void closePersistenceIfNecessary(Persistence<Car, Integer> persistence) {
if (persistence instanceof DiskPersistence) {
DiskPersistence diskPersistence = (DiskPersistence) persistence;
diskPersistence.close();
File diskPersistenceFile = diskPersistence.getFile();
if (!diskPersistenceFile.delete()) {
throw new IllegalStateException("Failed to delete temporary disk persistence file: " + diskPersistenceFile);
}
}
else if (persistence instanceof OffHeapPersistence) {
((OffHeapPersistence) persistence).close();
}
}
static boolean persistenceProvidesEquivalentIndexAlready(Persistence<Car, Integer> persistence, Index<Car> indexToBeAdded) {
if (persistence != null && !(persistence instanceof OnHeapPersistence)) {
// Persistence is non-heap therefore has a primary key index already.
if (indexToBeAdded instanceof AttributeIndex) {
if (Car.CAR_ID.equals(((AttributeIndex) indexToBeAdded).getAttribute())) {
// Collection will already have an identity index on this attribute...
return true;
}
}
}
return false;
}
static void evaluateQuery(IndexedCollection<Car> indexedCollection, Query<Car> query, QueryOptions queryOptions, ExpectedResults expectedResults) {
if (expectedResults == null) {
throw new IllegalStateException("No expectedResults configured for query: " + query);
}
try {
if (expectedResults.containsQueryLogMessages != null) {
queryOptions.put(QueryLog.class, new QueryLog(new AppendableCollection()));
}
ResultSet<Car> results = indexedCollection.retrieve(query, queryOptions);
try {
if (expectedResults.size != null) {
assertEquals("size mismatch for query: " + query, expectedResults.size.intValue(), results.size());
}
if (expectedResults.mergeCost != null) {
assertEquals("mergeCost mismatch for query: " + query, expectedResults.mergeCost.intValue(), results.getMergeCost());
}
if (expectedResults.retrievalCost != null) {
assertEquals("retrievalCost mismatch for query: " + query, expectedResults.retrievalCost.intValue(), results.getRetrievalCost());
}
if (expectedResults.indexUsed != null) {
assertEquals("indexUsed mismatch for query: " + query, expectedResults.indexUsed, results.getRetrievalCost() < Integer.MAX_VALUE);
}
if (expectedResults.carIdsAnyOrder != null) {
assertEquals("carIdsAnyOrder mismatch for query: " + query, expectedResults.carIdsAnyOrder, extractCarIds(results, new HashSet<Integer>()));
}
if (expectedResults.carIdsInOrder != null) {
assertEquals("carIdsInOrder mismatch for query: " + query, expectedResults.carIdsInOrder, extractCarIds(results, new ArrayList<Integer>()));
}
if (expectedResults.containsCarIds != null) {
// Validate ResultSet.contains()...
for (Integer carId : expectedResults.containsCarIds) {
assertTrue("containsCarIds mismatch, results do not contain carId " + carId + " for query: " + query, results.contains(CarFactory.createCar(carId)));
}
// Validate actual results returned by ResultSet.iterator()...
Set<Integer> expectedCarIds = new HashSet<Integer>(expectedResults.containsCarIds);
for (Car car : results) {
if (expectedCarIds.contains(car.getCarId())) {
expectedCarIds.remove(car.getCarId());
}
if (expectedCarIds.isEmpty()) {
break;
}
}
assertTrue("containsCarIds mismatch, iterated results do not include carIds " + expectedCarIds + " for query: " + query, expectedCarIds.isEmpty());
}
if (expectedResults.doesNotContainCarIds != null) {
// Validate ResultSet.contains()...
for (Integer carId : expectedResults.doesNotContainCarIds) {
assertFalse("doesNotContainCarIds mismatch, results contain carId " + carId + " for query: " + query, results.contains(CarFactory.createCar(carId)));
}
// Validate actual results returned by ResultSet.iterator()...
for (Car car : results) {
assertFalse("doesNotContainCarIds mismatch, results contain carId " + car.getCarId() + " for query: " + query, expectedResults.doesNotContainCarIds.contains(car.getCarId()));
}
}
if (expectedResults.containsQueryLogMessages != null) {
QueryLog queryLog = queryOptions.get(QueryLog.class);
AppendableCollection messages = (AppendableCollection)queryLog.getSink();
for (String expectedMessage : expectedResults.containsQueryLogMessages) {
assertTrue("QueryLog does not contain message '" + expectedMessage + "' for query: " + query + ", messages contained: " + messages, messages.contains(expectedMessage));
}
}
}
finally {
results.close();
}
}
catch (Exception e) {
throw new IllegalStateException("Failed to retrieve results for query: " + query, e);
}
}
static class QueryToEvaluate {
final int lineNumber = getLineNumber();
Query<Car> query = none(Car.class);
QueryOptions queryOptions = noQueryOptions();
ExpectedResults expectedResults = null;
boolean highPriority = false;
static int getLineNumber() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (ste.getClassName() != null
&& ste.getClassName().startsWith(IndexedCollectionFunctionalTest.class.getName())
&& !ste.getClassName().endsWith(QueryToEvaluate.class.getName())) {
return ste.getLineNumber();
}
}
return -1;
}
}
static class ExpectedResults {
Integer size;
Integer retrievalCost;
Integer mergeCost;
Boolean indexUsed;
Collection<String> containsQueryLogMessages;
List<Integer> carIdsInOrder;
Set<Integer> carIdsAnyOrder;
Set<Integer> containsCarIds;
Set<Integer> doesNotContainCarIds;
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
boolean first = true;
if (size != null) {
sb.append("size=").append(size);
first = false;
}
if (retrievalCost != null) {
if (!first) {
sb.append(", ");
}
sb.append("retrievalCost=").append(retrievalCost);
first = false;
}
if (mergeCost != null) {
if (!first) {
sb.append(", ");
}
sb.append("mergeCost=").append(mergeCost);
first = false;
}
if (indexUsed != null) {
if (!first) {
sb.append(", ");
}
sb.append("indexUsed=").append(indexUsed);
first = false;
}
if (carIdsInOrder != null) {
if (!first) {
sb.append(", ");
}
sb.append("carIdsInOrder=").append(carIdsInOrder);
first = false;
}
if (carIdsAnyOrder != null) {
if (!first) {
sb.append(", ");
}
sb.append("carIdsAnyOrder=").append(carIdsAnyOrder);
first = false;
}
if (containsCarIds != null) {
if (!first) {
sb.append(", ");
}
sb.append("containsCarIds=").append(containsCarIds);
first = false;
}
if (doesNotContainCarIds != null) {
if (!first) {
sb.append(", ");
}
sb.append("doesNotContainCarIds=").append(doesNotContainCarIds);
}
if (containsQueryLogMessages != null) {
if (!first) {
sb.append(", ");
}
sb.append("containsQueryLogMessages=").append(containsQueryLogMessages);
}
sb.append("]");
return sb.toString();
}
}
@SuppressWarnings("unchecked")
static List<Class> classes(Class<?>... indexedCollectionClasses) {
return Arrays.<Class>asList(indexedCollectionClasses);
}
static Iterable<? extends Index> noIndexes() {
return indexCombination();
}
static Iterable<Index> indexCombination(Index... indexes) {
return Arrays.asList(indexes);
}
@SuppressWarnings("unchecked")
static Iterable<Iterable<Index>> indexCombinations(Iterable... indexSets) {
return Arrays.<Iterable<Index>>asList(indexSets);
}
static String getIndexDescriptions(Iterable<Index> indexes) {
StringBuilder sb = new StringBuilder("[");
for (Iterator<Index> iterator = indexes.iterator(); iterator.hasNext(); ) {
Index index = iterator.next();
sb.append(getIndexDescription(index));
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
static String getIndexDescription(Index index) {
String description = index.getClass().getSimpleName();
if (description.isEmpty()) {
// Anonymous inner class, use enclosing class name...
description = index.getClass().getEnclosingClass().getSimpleName();
if (description.isEmpty()) {
throw new IllegalStateException("Failed to determine name for index: " + index.getClass());
}
}
if (index instanceof CompoundIndex) {
description += ".onAttribute(<CompoundAttribute>)";
}
else if (index instanceof AttributeIndex) {
Attribute attribute = ((AttributeIndex) index).getAttribute();
if (attribute instanceof StandingQueryAttribute) {
description += ".onAttribute(" + attribute.getAttributeName() + ")";
}
else {
description += ".onAttribute(" + attribute.getObjectType().getSimpleName() + "." + attribute.getAttributeName() + ")";
}
}
if (index instanceof AbstractMapBasedAttributeIndex && index.isQuantized()) {
description += " (quantized)";
}
return description;
}
public static <C extends Collection<Integer>> C extractCarIds(Iterable<Car> resultSet, C output) {
for (Car car : resultSet) {
output.add(car.getCarId());
}
return output;
}
public static Set<Integer> asSet(Integer... integers) {
return new HashSet<Integer>(asList(integers));
}
static SortedSet<Integer> integersBetween(int lower, int upper) {
SortedSet<Integer> treeSet = new TreeSet<Integer>();
for (int i = lower; i <= upper; i++) {
treeSet.add(i);
}
return treeSet;
}
static class AppendableCollection extends LinkedList<String> implements Appendable {
final String lineSeparator = System.getProperty("line.separator");
@Override
public Appendable append(CharSequence csq) throws IOException {
if (!lineSeparator.equals(csq)) {
super.add(String.valueOf(csq));
}
return this;
}
@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Appendable append(char c) throws IOException {
throw new UnsupportedOperationException();
}
}
}
| 116,340 | 57.462814 | 198 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/ObjectLockingIndexedCollectionTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.query.QueryFactory;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.util.Arrays;
import java.util.Set;
/**
* Unit tests for {@link ObjectLockingIndexedCollection}. Note that tests for support behavior (such as query processing)
* which applies to all implementations of {@link IndexedCollection} can be found in
* {@link com.googlecode.cqengine.IndexedCollectionFunctionalTest}.
* <p/>
* In addition to the unit tests in this class, this class also runs a further several hundred unit tests in
* <a href="https://code.google.com/p/guava-libraries/source/browse/guava-testlib">guava-testlib</a> on the
* IndexedCollection to validate its compliance with the API specifications of java.util.Set.
*
* @author Niall Gallagher
*/
public class ObjectLockingIndexedCollectionTest extends TestCase {
public static junit.framework.Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SetTestSuiteBuilder.using(onHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OnHeap_ObjectLockingIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTest(SetTestSuiteBuilder.using(offHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OffHeap_ObjectLockingIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTestSuite(ObjectLockingIndexedCollectionTest.class);
return suite;
}
private static TestStringSetGenerator onHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new ObjectLockingIndexedCollection<String>(OnHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(Arrays.asList(elements));
return indexedCollection;
}
};
}
private static TestStringSetGenerator offHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new ObjectLockingIndexedCollection<String>(OffHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(Arrays.asList(elements));
return indexedCollection;
}
};
}
public void testConstructor() {
ObjectLockingIndexedCollection<Integer> collection1 = new ObjectLockingIndexedCollection<Integer>();
ObjectLockingIndexedCollection<Integer> collection2 = new ObjectLockingIndexedCollection<Integer>(new OnHeapPersistence<Integer, Integer>());
ObjectLockingIndexedCollection<Integer> collection3 = new ObjectLockingIndexedCollection<Integer>(64);
assertEquals(64, collection1.stripedLock.concurrencyLevel);
assertEquals(64, collection2.stripedLock.concurrencyLevel);
assertEquals(64, collection3.stripedLock.concurrencyLevel);
}
}
| 4,323 | 48.136364 | 180 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/CQEngineDemo.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.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.query.Query;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.Car.Color;
import java.util.Collections;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* Demonstrates creating an indexed collection, adding various indexes to it, adding various objects to the collection,
* and performing some queries on the collection to retrieve matching objects.
*
* @author Niall Gallagher
*/
public class CQEngineDemo {
public static void main(String[] args) {
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", Color.BLUE, 5, 9000.50, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(2, "Ford", "Fiesta", Color.BLUE, 2, 5000.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(3, "Ford", "F-150", Color.RED, 2, 9500.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(4, "Honda", "Civic", Color.RED, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()));
cars.add(new Car(5, "Toyota", "Prius", Color.BLACK, 3, 9700.00, Collections.<String>emptyList(), Collections.emptyList()));
Query<Car> query;
System.out.println("\nAll cars, ordered by carId:");
query = all(Car.class);
for (Car car : cars.retrieve(query, queryOptions(orderBy(ascending(Car.CAR_ID))))) {
System.out.println(car);
}
System.out.println("\nFord cars:");
query = equal(Car.MANUFACTURER, "Ford");
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\n3-door cars:");
query = equal(Car.DOORS, 3);
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\n2 or 3-door cars:");
query = between(Car.DOORS, 2, 3);
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\n2 or 5-door cars:");
query = in(Car.DOORS, 2, 5);
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nBlue Ford cars:");
query = and(equal(Car.COLOR, Color.BLUE), equal(Car.MANUFACTURER, "Ford"));
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nNOT 3-door cars:");
query = not(equal(Car.DOORS, 3));
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nCars which have 5 doors and which are not red:");
query = and(equal(Car.DOORS, 5), not(equal(Car.COLOR, Color.RED)));
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nNOT 3-door cars, sorted by doors ascending:");
query = not(equal(Car.DOORS, 3));
for (Car car : cars.retrieve(query, queryOptions(orderBy(ascending(Car.DOORS))))) {
System.out.println(car);
}
System.out.println("\nNOT 3-door cars, sorted by doors ascending then price descending:");
query = not(equal(Car.DOORS, 3));
for (Car car : cars.retrieve(query, queryOptions(orderBy(ascending(Car.DOORS), descending(Car.PRICE))))) {
System.out.println(car);
}
System.out.println("\nCars whose model starts with 'F':");
query = startsWith(Car.MODEL, "F");
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nCars whose model ends with 's':");
query = endsWith(Car.MODEL, "s");
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nCars whose model contains 'i':");
query = contains(Car.MODEL, "i");
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
System.out.println("\nCars whose model is contained in 'Banana, Focus, Civic, Foobar':");
query = isContainedIn(Car.MODEL, "Banana, Focus, Civic, Foobar");
for (Car car : cars.retrieve(query)) {
System.out.println(car);
}
}
}
| 5,866 | 39.743056 | 132 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/TransactionalIndexedCollectionTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.googlecode.cqengine.persistence.offheap.OffHeapPersistence;
import com.googlecode.cqengine.persistence.onheap.OnHeapPersistence;
import com.googlecode.cqengine.persistence.support.CollectionWrappingObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import com.googlecode.cqengine.testutil.Car;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Assert;
import java.util.*;
import java.util.concurrent.*;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.option.ArgumentValidationStrategy.SKIP;
import static com.googlecode.cqengine.testutil.CarFactory.createCar;
import static java.util.Arrays.asList;
/**
* Unit tests for {@link TransactionalIndexedCollection}. Note that tests for support behavior (such as query processing)
* which applies to all implementations of {@link IndexedCollection} can be found in
* {@link com.googlecode.cqengine.IndexedCollectionFunctionalTest}.
* <p/>
* In addition to the unit tests in this class, this class also runs a further several hundred unit tests in
* <a href="https://code.google.com/p/guava-libraries/source/browse/guava-testlib">guava-testlib</a> on the
* IndexedCollection to validate its compliance with the API specifications of java.util.Set.
*
* @author Niall Gallagher
*/
public class TransactionalIndexedCollectionTest extends TestCase {
public static junit.framework.Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SetTestSuiteBuilder.using(onHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OnHeap_TransactionalIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTest(SetTestSuiteBuilder.using(offHeapIndexedCollectionGenerator())
.withFeatures(CollectionSize.ANY, CollectionFeature.GENERAL_PURPOSE)
.named("OffHeap_TransactionalIndexedCollectionAPICompliance")
.createTestSuite());
suite.addTestSuite(TransactionalIndexedCollectionTest.class);
return suite;
}
private static TestStringSetGenerator onHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new TransactionalIndexedCollection<String>(String.class, OnHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(Arrays.asList(elements));
return indexedCollection;
}
};
}
private static TestStringSetGenerator offHeapIndexedCollectionGenerator() {
return new TestStringSetGenerator() {
@Override protected Set<String> create(String[] elements) {
IndexedCollection<String> indexedCollection = new TransactionalIndexedCollection<String>(String.class, OffHeapPersistence.onPrimaryKey(QueryFactory.selfAttribute(String.class)));
indexedCollection.addAll(Arrays.asList(elements));
return indexedCollection;
}
};
}
public void testWritePath() {
TransactionalIndexedCollection<Car> collection = new TransactionalIndexedCollection<Car>(Car.class);
// Version number initially starts at 1...
assertEquals(1, collection.currentVersion.versionNumber);
// Adding objects to the collection should cause version number to be incremented twice...
collection.addAll(asSet(createCar(1), createCar(2), createCar(3), createCar(4)));
assertEquals(4, collection.size());
assertEquals(asSet(createCar(1), createCar(2), createCar(3), createCar(4)), collection);
assertEquals(3, collection.currentVersion.versionNumber);
// Removing objects from the collection should cause version number to be incremented twice...
collection.removeAll(asSet(createCar(2), createCar(3)));
assertEquals(2, collection.size());
assertEquals(asSet(createCar(1), createCar(4)), collection);
assertEquals(5, collection.currentVersion.versionNumber);
// Replacing objects in the collection should cause version number to be incremented thrice...
collection.update(asSet(createCar(4)), asSet(createCar(5), createCar(6)));
assertEquals(3, collection.size());
assertEquals(asSet(createCar(1), createCar(5), createCar(6)), collection);
assertEquals(8, collection.currentVersion.versionNumber);
// Replacing no objects should not cause version number to change...
collection.update(Collections.<Car>emptySet(), Collections.<Car>emptySet());
assertEquals(8, collection.currentVersion.versionNumber);
}
public void testReadPath() throws InterruptedException, ExecutionException {
// Set up the initial collection to contain 2 objects...
final TransactionalIndexedCollection<Car> collection = new TransactionalIndexedCollection<Car>(Car.class);
collection.addAll(asSet(createCar(1), createCar(2)));
assertEquals(2, collection.size());
// Set up an executor which will execute tasks in separate threads.
ExecutorService executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
// This thread will subsequently act as a control thread, submitting tasks to background threads and validating the behaviour.
// == STEP 1: Set up a background thread which will read from the collection... ==
// Create a semaphore on which the background reading thread will block after it has opened a ResultSet,
// but before it has actually read any objects from it...
final Semaphore readBlock = new Semaphore(0);
// Define a semaphore which allows this control thread to wait for the background read to begin...
final Semaphore readStartedSignal = new Semaphore(0);
// Submit a reading task to a background thread...
Future<Set<Car>> resultsFromFirstRead = executor.submit(new Callable<Set<Car>>() {
@Override
public Set<Car> call() throws Exception {
ResultSet<Car> resultSet = collection.retrieve(all(Car.class));
// Signal that this reading thread has started...
readStartedSignal.release();
// BLOCK the reading thread here...
readBlock.acquire();
// At this point thread was unblocked...
// Now read from this ResultSet...
Set<Car> materializedObjects = asSet(resultSet);
// Close the ResultSet, and return the objects which were read...
resultSet.close();
return materializedObjects;
}
});
// Block this control thread until the reading thread has actually started...
readStartedSignal.acquire();
// ...at this point, a background thread has an open ResultSet,
// so attempts to modify the collection should block.
// Try to modify the collection in a different background thread...
// Define a semaphore which allows this control thread to wait for the write to begin...
final Semaphore writeStartedSignal = new Semaphore(0);
// Define a semaphore which allows this control thread to determine that the write has finished...
final Semaphore writeFinishedSignal = new Semaphore(0);
executor.submit(new Runnable() {
@Override
public void run() {
// Signal that this writing thread has started...
writeStartedSignal.release();
// Remove Car 2, and add Cars 3 & 4...
collection.update(asSet(createCar(2)), asSet(createCar(3), createCar(4)));
writeFinishedSignal.release();
}
});
writeStartedSignal.acquire();
// Make this control thread sleep to allow time for the writing thread to enter update() where it should block...
Thread.sleep(1000L);
// Assert that the writing thread is indeed blocked...
Assert.assertFalse("Writing thread should block while there is an open ResultSet", writeFinishedSignal.tryAcquire());
// Unblock the reading thread to allow it to read objects from the ResultSet it opened earlier,
// and then to close its ResultSet...
readBlock.release();
// Now validate that the reading thread did not see any of the modifications submitted to the writing thread...
Assert.assertEquals(asSet(createCar(1), createCar(2)), resultsFromFirstRead.get());
// Make this control thread sleep to allow time for the writing thread to finish...
Thread.sleep(1000L);
// Assert that the writing thread is now unblocked...
Assert.assertTrue("Writing thread should have completed after the open ResultSet was closed", writeFinishedSignal.tryAcquire());
// Now validate (in this control thread) that the modifications by the writing thread are visible...
ResultSet<Car> resultsFromSecondRead = collection.retrieve(all(Car.class));
Set<Car> materializedResultsFromSecondRead = asSet(resultsFromSecondRead);
resultsFromSecondRead.close();
Assert.assertEquals(asSet(createCar(1), createCar(3), createCar(4)), materializedResultsFromSecondRead);
}
public void testConstructor() {
TransactionalIndexedCollection<Car> indexedCollection = new TransactionalIndexedCollection<Car>(
Car.class,
new OnHeapPersistence<Car, Integer>()
);
assertEquals(indexedCollection.objectType, Car.class);
assertEquals(1L, indexedCollection.currentVersion.versionNumber);
}
public void testArgumentValidation_NotDisjoint() {
Set<Integer> s1 = asSet(1, 2, 3);
Set<Integer> s2 = asSet(3, 4, 5); // overlaps
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
try {
indexedCollection.update(s1, s2);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
// Ignore
}
}
public void testArgumentValidation_NotDisjoint_ValidationSkipped() {
Set<Integer> s1 = asSet(1, 2, 3);
Set<Integer> s2 = asSet(3, 4, 5); // overlaps
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
indexedCollection.update(s1, s2, queryOptions(argumentValidation(SKIP)));
}
public void testArgumentValidation_Disjoint() {
Set<Integer> s1 = asSet(1, 2, 3);
Set<Integer> s2 = asSet(4, 5, 6); // does not overlap
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
indexedCollection.update(s1, s2);
}
public void testStrictReplacement() {
{
// Verify that with STRICT_REPLACEMENT, when some objects to be replaced are not stored, collection is not modified...
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
indexedCollection.addAll(asSet(1, 2, 3));
assertFalse(indexedCollection.update(asSet(3, 4), asSet(5, 6), queryOptions(enableFlags(TransactionalIndexedCollection.STRICT_REPLACEMENT))));
assertEquals(indexedCollection, asSet(1, 2, 3));
}
{
// Verify that without STRICT_REPLACEMENT, when some objects to be replaced are not stored, collection is modified...
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
indexedCollection.addAll(asSet(1, 2, 3));
assertTrue(indexedCollection.update(asSet(3, 4), asSet(5, 6)));
assertEquals(indexedCollection, asSet(1, 2, 5, 6));
}
{
// Verify that with STRICT_REPLACEMENT, when no objects are to be replaced, collection is modified...
TransactionalIndexedCollection<Integer> indexedCollection = new TransactionalIndexedCollection<Integer>(Integer.class);
indexedCollection.addAll(asSet(1, 2, 3));
assertTrue(indexedCollection.update(Collections.<Integer>emptySet(), asSet(4, 5), queryOptions(enableFlags(TransactionalIndexedCollection.STRICT_REPLACEMENT))));
assertEquals(indexedCollection, asSet(1, 2, 3, 4, 5));
}
}
public void testIterableContains() {
final Set<Integer> collection = asSet(1, 2, 3);
ResultSet<Integer> resultSet = new StoredSetBasedResultSet<Integer>(collection);
Iterable<Integer> iterable = asIterable(collection);
assertTrue(TransactionalIndexedCollection.iterableContains(collection, 1));
assertFalse(TransactionalIndexedCollection.iterableContains(collection, 4));
assertTrue(TransactionalIndexedCollection.iterableContains(resultSet, 1));
assertFalse(TransactionalIndexedCollection.iterableContains(resultSet, 4));
assertTrue(TransactionalIndexedCollection.iterableContains(iterable, 1));
assertFalse(TransactionalIndexedCollection.iterableContains(iterable, 4));
}
public void testObjectStoreContainsAllIterable() {
final ObjectStore<Integer> objectStore = new CollectionWrappingObjectStore<Integer>(asSet(1, 2, 3));
assertTrue(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asSet(1, 2, 3), noQueryOptions()));
assertTrue(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asIterable(asSet(1, 2, 3)), noQueryOptions()));
assertFalse(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asSet(1, 4, 3), noQueryOptions()));
assertFalse(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asIterable(asSet(1, 4, 3)), noQueryOptions()));
assertFalse(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asSet(1, 2, 3, 4), noQueryOptions()));
assertFalse(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asIterable(asSet(1, 2, 3, 4)), noQueryOptions()));
assertTrue(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, Collections.<Integer>emptySet(), noQueryOptions()));
assertTrue(TransactionalIndexedCollection.objectStoreContainsAllIterable(objectStore, asIterable(Collections.<Integer>emptySet()), noQueryOptions()));
}
static <O> Iterable<O> asIterable(final Collection<O> collection) {
return new Iterable<O>() {
@Override
public Iterator<O> iterator() {
return collection.iterator();
}
};
}
static <O> Set<O> asSet(O... objects) {
return new LinkedHashSet<O>(asList(objects));
}
static <O> Set<O> asSet(ResultSet<O> resultSet) {
Set<O> results = new LinkedHashSet<O>();
for (O item : resultSet) {
results.add(item);
}
return results;
}
}
| 16,502 | 53.827243 | 194 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/hash/HashIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.support.AbstractMapBasedAttributeIndex;
import com.googlecode.cqengine.index.support.KeyStatistics;
import com.googlecode.cqengine.index.support.KeyStatisticsIndex;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.testutil.TestUtil.setOf;
/**
* Created by niall.gallagher on 09/01/2015.
*/
public class HashIndexTest {
@Test
public void testGetDistinctKeysAndCounts() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
KeyStatisticsIndex<String, Car> MODEL_INDEX = HashIndex.onAttribute(Car.MODEL);
collection.addIndex(MODEL_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Set<String> distinctModels = setOf(MODEL_INDEX.getDistinctKeys(noQueryOptions()));
Assert.assertEquals(setOf("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus"), distinctModels);
for (String model : distinctModels) {
Assert.assertEquals(Integer.valueOf(2), MODEL_INDEX.getCountForKey(model, noQueryOptions()));
}
}
@Test
public void testGetCountOfDistinctKeys(){
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
KeyStatisticsIndex<String, Car> MANUFACTURER_INDEX = HashIndex.onAttribute(Car.MANUFACTURER);
collection.addIndex(MANUFACTURER_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Assert.assertEquals(Integer.valueOf(4), MANUFACTURER_INDEX.getCountOfDistinctKeys(noQueryOptions()));
}
@Test
public void testGetStatisticsForDistinctKeys(){
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
KeyStatisticsIndex<String, Car> MANUFACTURER_INDEX = HashIndex.onAttribute(Car.MANUFACTURER);
collection.addIndex(MANUFACTURER_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Set<KeyStatistics<String>> keyStatistics = setOf(MANUFACTURER_INDEX.getStatisticsForDistinctKeys(noQueryOptions()));
Assert.assertEquals(setOf(
new KeyStatistics<String>("Ford", 6),
new KeyStatistics<String>("Honda", 6),
new KeyStatistics<String>("Toyota", 6),
new KeyStatistics<String>("BMW", 2)
),
keyStatistics);
}
@Test
public void testOnSemiUniqueAttribute() throws Exception{
HashIndex<Integer, Car> hashIndex = HashIndex.onSemiUniqueAttribute(Car.CAR_ID);
// Validate that the HashIndex was configured with CompactValueSetFactory.
// We have to use reflection to do this
// because the valueSetFactory has protected access in AbstractMapBasedAttributeIndex.
// This is a bit hacky, but OTOH we should not break encapsulation of AbstractMapBasedAttributeIndex...
Field valueSetFactoryField = AbstractMapBasedAttributeIndex.class.getDeclaredField("valueSetFactory");
valueSetFactoryField.setAccessible(true);
Assert.assertTrue("HashIndex should be configured with CompactValueSetFactory",
valueSetFactoryField.get(hashIndex) instanceof HashIndex.CompactValueSetFactory);
}
}
| 4,292 | 43.257732 | 145 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/radixinverted/InvertedRadixTreeIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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 com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.SmartArrayBasedNodeFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for {@link InvertedRadixTreeIndex}.
*
* Created by npgall on 13/05/2016.
*/
public class InvertedRadixTreeIndexTest {
@Test
public void testNodeFactory() {
InvertedRadixTreeIndex<String, Car> index1 = InvertedRadixTreeIndex.onAttribute(Car.MANUFACTURER);
InvertedRadixTreeIndex<String, Car> index2 = InvertedRadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new DefaultCharArrayNodeFactory());
InvertedRadixTreeIndex<String, Car> index3 = InvertedRadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new SmartArrayBasedNodeFactory());
assertTrue(index1.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index2.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index3.nodeFactory instanceof SmartArrayBasedNodeFactory);
}
} | 1,782 | 41.452381 | 157 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/compound/support/CompoundQueryTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.testutil.Car;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static org.junit.Assert.*;
/**
* @author niall.gallagher
*/
public class CompoundQueryTest {
@Test
public void testFromAndQueryIfSuitable() {
assertNotNull(CompoundQuery.fromAndQueryIfSuitable(and(equal(Car.DOORS, 5), equal(Car.MANUFACTURER, "Ford"))));
assertNull(CompoundQuery.fromAndQueryIfSuitable(and(equal(Car.DOORS, 5), in(Car.MANUFACTURER, "Ford", "Honda"))));
}
} | 1,201 | 34.352941 | 122 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/compound/support/TupleCombinationGeneratorTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Assert;
import org.junit.Test;
import java.util.*;
/**
* @author Niall Gallagher
*/
public class TupleCombinationGeneratorTest {
@Test
public void testGenerateCombinations_EmptyOuterList() {
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(Collections.<List<Object>>emptyList());
Assert.assertTrue(permutations.isEmpty());
}
@Test
public void testGenerateCombinations_AscendingListSize() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Arrays.<Object>asList(1));
add(Arrays.<Object>asList("bar", "baz"));
add(Arrays.<Object>asList(2.0, 3.0, 4.0));
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertEquals(
"[[1, bar, 2.0], [1, bar, 3.0], [1, bar, 4.0], [1, baz, 2.0], [1, baz, 3.0], [1, baz, 4.0]]",
permutations.toString()
);
}
@Test
public void testGenerateCombinations_EqualListSize() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Arrays.<Object>asList(1, 2));
add(Arrays.<Object>asList("bar", "baz"));
add(Arrays.<Object>asList(3.0, 4.0));
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertEquals(
"[[1, bar, 3.0], [1, bar, 4.0], [1, baz, 3.0], [1, baz, 4.0], [2, bar, 3.0], [2, bar, 4.0], [2, baz, 3.0], [2, baz, 4.0]]",
permutations.toString()
);
}
@Test
public void testGenerateCombinations_DescendingListSize() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Arrays.<Object>asList(1, 2, 3));
add(Arrays.<Object>asList("bar", "baz"));
add(Arrays.<Object>asList(2.0));
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertEquals(
"[[1, bar, 2.0], [1, baz, 2.0], [2, bar, 2.0], [2, baz, 2.0], [3, bar, 2.0], [3, baz, 2.0]]",
permutations.toString()
);
}
@Test
public void testGenerateCombinations_EmptySubList1() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Collections.emptyList());
add(Arrays.<Object>asList("bar", "baz"));
add(Arrays.<Object>asList(2.0, 3.0, 4.0));
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertTrue(permutations.isEmpty());
}
@Test
public void testGenerateCombinations_EmptySubList2() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Arrays.<Object>asList(1));
add(Collections.emptyList());
add(Arrays.<Object>asList(2.0, 3.0, 4.0));
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertTrue(permutations.isEmpty());
}
@Test
public void testGenerateCombinations_EmptySubList3() {
List<List<Object>> inputLists = new ArrayList<List<Object>>() {{
add(Arrays.<Object>asList(1));
add(Arrays.<Object>asList("bar", "baz"));
add(Collections.emptyList());
}};
List<List<Object>> permutations = TupleCombinationGenerator.generateCombinations(inputLists);
Assert.assertTrue(permutations.isEmpty());
}
@Test
public void testConstructor() {
// Test the constructor (for test coverage only)...
TupleCombinationGenerator combinationGenerator = new TupleCombinationGenerator();
Assert.assertNotNull(combinationGenerator);
}
}
| 4,545 | 38.189655 | 139 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/SQLiteConcurrentStatementTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.sqlite.TemporaryDatabase.TemporaryInMemoryDatabase;
import com.googlecode.cqengine.index.sqlite.support.DBUtils;
import com.googlecode.cqengine.query.QueryFactory;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.sql.*;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* Tests that we can open more than one JDBC Statement and ResultSet per Connection, and use them both at the same time
* (from the same thread). This may be a support occurrence in CQEngine when multiple SQL queries may be open from the
* same SQLite database simultaneously, but accessed lazily, to evaluate a single request.
*
* @author niall.gallagher
*/
public class SQLiteConcurrentStatementTest {
@Rule
public TemporaryInMemoryDatabase temporaryDatabase = new TemporaryInMemoryDatabase();
@Test
public void testConcurrentStatements() throws SQLException {
Connection connection = temporaryDatabase.getConnectionManager(true).getConnection(null, noQueryOptions());
final int NUM_ROWS = 10;
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS test_table (column1 INTEGER, column2 BLOB, PRIMARY KEY (column1, column2)) WITHOUT ROWID;");
stmt.executeUpdate("CREATE INDEX IF NOT EXISTS test_index ON test_table (column1);");
stmt.close();
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO test_table (column1, column2) VALUES (?, ?);");
for (int i = 0; i < NUM_ROWS; i++) {
pstmt.setObject(1, i);
pstmt.setObject(2, createBytes(i));
pstmt.executeUpdate();
pstmt.clearParameters();
}
pstmt.close();
PreparedStatement rstmt1 = connection.prepareStatement("SELECT * FROM test_table WHERE column1 >= 3 AND column1 <= 5;");
ResultSet rs1 = rstmt1.executeQuery();
Map<Integer, Integer> results = new LinkedHashMap<Integer, Integer>();
while (rs1.next()) {
Integer column1 = rs1.getInt(1);
byte[] column2 = rs1.getBytes(2);
PreparedStatement rstmt2 = connection.prepareStatement("SELECT COUNT(column2) FROM test_table WHERE column1 >= 3 AND column1 <= 5 AND column2 = ?;");
rstmt2.setBytes(1, column2);
ResultSet rs2 = rstmt2.executeQuery();
Assert.assertTrue(rs2.next());
Integer count = rs2.getInt(1);
rs2.close();
rstmt2.close();
results.put(column1, count);
}
rs1.close();
rstmt1.close();
Assert.assertEquals(3, results.size());
Assert.assertEquals(Integer.valueOf(1), results.get(3));
Assert.assertEquals(Integer.valueOf(1), results.get(4));
Assert.assertEquals(Integer.valueOf(1), results.get(5));
}
finally {
DBUtils.closeQuietly(connection);
}
}
static byte[] createBytes(int rowNumber) {
final int NUM_BYTES = 50;
byte[] result = new byte[50];
for (int i = 0; i < NUM_BYTES; i++) {
result[i] = (byte) (rowNumber + i);
}
return result;
}
}
| 4,085 | 41.123711 | 165 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/SimplifiedSQLiteIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import static org.junit.Assert.*;
/**
* @author niall.gallagher
*/
public class SimplifiedSQLiteIndexTest {
} | 766 | 27.407407 | 75 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/PartialSQLiteIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Rule;
import org.junit.Test;
import java.util.Collections;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static org.junit.Assert.assertEquals;
/**
* Tests for {@link PartialSQLiteIndex}.
*
* @author niall.gallagher
*/
public class PartialSQLiteIndexTest {
public static final SimpleAttribute<Car, Integer> OBJECT_TO_ID = Car.CAR_ID;
public static final SimpleAttribute<Integer, Car> ID_TO_OBJECT = new SimpleAttribute<Integer, Car>("carFromId") {
public Car getValue(Integer carId, QueryOptions queryOptions) { return CarFactory.createCar(carId); }
};
@Rule
public TemporaryDatabase.TemporaryInMemoryDatabase temporaryInMemoryDatabase = new TemporaryDatabase.TemporaryInMemoryDatabase();
@Test
public void testPartialSQLiteIndex() {
IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>();
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
QueryOptions queryOptions = new QueryOptions();
queryOptions.put(ConnectionManager.class, connectionManager);
PartialSQLiteIndex<String, Car, Integer> index = PartialSQLiteIndex.onAttributeWithFilterQuery(Car.MANUFACTURER, OBJECT_TO_ID, ID_TO_OBJECT, between(Car.CAR_ID, 2, 4));
indexedCollection.addIndex(index, queryOptions);
indexedCollection.update(Collections.<Car>emptySet(), CarFactory.createCollectionOfCars(10), queryOptions);
assertEquals(75, indexedCollection.retrieve(and(equal(Car.MANUFACTURER, "Ford"), between(Car.CAR_ID, 2, 4)), queryOptions).getRetrievalCost());
assertEquals(2147483647, indexedCollection.retrieve(and(equal(Car.MANUFACTURER, "Ford"), between(Car.CAR_ID, 2, 5)), queryOptions).getRetrievalCost());
}
} | 2,787 | 44.704918 | 176 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/SQLiteIdentityIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.sqlite.TemporaryDatabase.TemporaryInMemoryDatabase;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.*;
public class SQLiteIdentityIndexTest {
@Rule
public TemporaryInMemoryDatabase temporaryDatabase = new TemporaryInMemoryDatabase();
@Test
public void testSerialization() {
SQLiteIdentityIndex<Integer, Car> index = new SQLiteIdentityIndex<Integer, Car>(
Car.CAR_ID
);
SimpleAttribute<Car, byte[]> serializingAttribute = index.new SerializingAttribute(Car.class, byte[].class);
SimpleAttribute<byte[], Car> deserializingAttribute = index.new DeserializingAttribute(byte[].class, Car.class);
Car c1 = CarFactory.createCar(1);
byte[] s1 = serializingAttribute.getValue(c1, noQueryOptions());
Car c2 = deserializingAttribute.getValue(s1, noQueryOptions());
byte[] s2 = serializingAttribute.getValue(c2, noQueryOptions());
Assert.assertEquals(c1, c2);
Assert.assertArrayEquals(s1, s2);
}
} | 1,931 | 37.64 | 120 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/SQLiteIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.google.common.collect.*;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.index.sqlite.support.DBQueries;
import com.googlecode.cqengine.index.support.CloseableIterable;
import com.googlecode.cqengine.index.support.KeyStatistics;
import com.googlecode.cqengine.index.support.KeyValue;
import com.googlecode.cqengine.persistence.support.ConcurrentOnHeapObjectStore;
import com.googlecode.cqengine.persistence.support.ObjectSet;
import com.googlecode.cqengine.persistence.support.ObjectStore;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.query.simple.FilterQuery;
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.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sqlite.SQLiteConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static com.googlecode.cqengine.testutil.TestUtil.setOf;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link SQLiteIndex}
*
* @author Silvano Riz
*/
public class SQLiteIndexTest {
private static final String TABLE_NAME = "cqtbl_features";
private static final String INDEX_NAME = "cqidx_features_value";
public static final SimpleAttribute<Car, Integer> OBJECT_TO_ID = Car.CAR_ID;
public static final SimpleAttribute<Integer, Car> ID_TO_OBJECT = new SimpleAttribute<Integer, Car>("carFromId") {
public Car getValue(Integer carId, QueryOptions queryOptions) { return null; }
};
public static List<Car> data = Arrays.asList(
new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()),
new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()),
new Car(3, "Toyota", "Prius", Car.Color.BLACK, 3, 9700.00, Arrays.asList("abs"), Collections.emptyList()),
new Car(4, "Fiat", "Panda", Car.Color.BLUE, 5, 5600.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(5, "Fiat", "Punto", Car.Color.BLUE, 5, 5600.00, Arrays.asList("gps"), Collections.emptyList())
);
@Rule
public TemporaryDatabase.TemporaryInMemoryDatabase temporaryInMemoryDatabase = new TemporaryDatabase.TemporaryInMemoryDatabase();
@Test
public void testNew1() throws Exception {
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = SQLiteIndex.onAttribute(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT
);
assertNotNull(carFeaturesOffHeapIndex);
}
@Test
public void testNew2() throws Exception {
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"_tableSuffix"
);
assertNotNull(carFeaturesOffHeapIndex);
assertEquals("features_tableSuffix", carFeaturesOffHeapIndex.tableName);
}
@Test
public void testGetConnectionManager(){
ConnectionManager connectionManager = mock(ConnectionManager.class);
QueryOptions queryOptions = mock(QueryOptions.class);
when(queryOptions.get(ConnectionManager.class)).thenReturn(connectionManager);
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
assertEquals(connectionManager, carFeaturesOffHeapIndex.getConnectionManager(queryOptions));
}
@Test
public void testNotifyObjectsRemoved() throws Exception{
// Mock
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection).thenReturn(connection);
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
when(connection.createStatement()).thenReturn(statement);
when(connection.prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE objectKey = ?;")).thenReturn(preparedStatement);
when(preparedStatement.executeBatch()).thenReturn(new int[] {1});
// The objects to add
Set<Car> removedObjects = new HashSet<Car>(2);
removedObjects.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()));
removedObjects.add(new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()));
@SuppressWarnings({"unchecked", "unused"})
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.removeAll(objectSet(removedObjects), createQueryOptions(connectionManager));
// Verify
verify(statement, times(1)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
verify(statement, times(1)).executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
verify(preparedStatement, times(1)).setObject(1, 1);
verify(preparedStatement, times(1)).setObject(1, 2);
verify(preparedStatement, times(2)).addBatch();
verify(preparedStatement, times(1)).executeBatch();
verify(connection, times(0)).close();
}
@Test
public void testNotifyObjectsAdded() throws Exception {
// Mock
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection).thenReturn(connection);
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
when(connection.createStatement()).thenReturn(statement);
when(connection.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);")).thenReturn(preparedStatement);
when(preparedStatement.executeBatch()).thenReturn(new int[] {2});
// The objects to add
Set<Car> addedObjects = new HashSet<Car>(2);
addedObjects.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()));
addedObjects.add(new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()));
// Create the index and cal the addAll
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.addAll(objectSet(addedObjects), createQueryOptions(connectionManager));
// Verify
verify(statement, times(1)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
verify(statement, times(1)).executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
verify(preparedStatement, times(2)).setObject(1, 1);
verify(preparedStatement, times(1)).setObject(1, 2);
verify(preparedStatement, times(1)).setObject(2, "abs");
verify(preparedStatement, times(1)).setObject(2, "gps");
verify(preparedStatement, times(1)).setObject(2, "airbags");
verify(preparedStatement, times(3)).addBatch();
verify(preparedStatement, times(1)).executeBatch();
verify(connection, times(0)).close();
}
@Test
public void testNotifyObjectsCleared() throws Exception{
// Mock
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection).thenReturn(connection);
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
when(connection.createStatement()).thenReturn(statement).thenReturn(statement).thenReturn(statement);
@SuppressWarnings({"unchecked", "unused"})
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.clear(createQueryOptions(connectionManager));
// Verify
verify(statement, times(1)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
verify(statement, times(1)).executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
verify(statement, times(1)).executeUpdate("DELETE FROM " + TABLE_NAME + ";");
verify(connection, times(0)).close();
}
/**
* Verifies that if connectionManager.isApplyUpdateForIndexEnabled() returns false,
* init() will do nothing.
*/
@Test
public void testInit_ApplyUpdateForIndexIsFalse() throws Exception{
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
// Simulate isApplyUpdateForIndexEnabled == false...
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(false);
Statement statement = mock(Statement.class);
when(connection.createStatement()).thenReturn(statement);
java.sql.ResultSet journalModeRs = mock(java.sql.ResultSet.class);
java.sql.ResultSet synchronousRs = mock(java.sql.ResultSet.class);
when(journalModeRs.next()).thenReturn(true).thenReturn(false);
when(synchronousRs.next()).thenReturn(true).thenReturn(false);
when(journalModeRs.getString(1)).thenReturn("DELETE");
when(synchronousRs.getInt(1)).thenReturn(2);
when(statement.executeQuery("PRAGMA journal_mode;")).thenReturn(journalModeRs);
when(statement.executeQuery("PRAGMA synchronous;")).thenReturn(synchronousRs);
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.init(emptyObjectStore(), createQueryOptions(connectionManager));
verify(statement, times(1)).executeQuery("PRAGMA journal_mode;");
verify(statement, times(1)).executeQuery("PRAGMA synchronous;");
verify(statement, times(2)).close();
Assert.assertEquals(carFeaturesOffHeapIndex.pragmaSynchronous, SQLiteConfig.SynchronousMode.FULL);
Assert.assertEquals(carFeaturesOffHeapIndex.pragmaJournalMode, SQLiteConfig.JournalMode.DELETE);
Assert.assertTrue(carFeaturesOffHeapIndex.canModifySyncAndJournaling);
}
/**
* Verifies that if connectionManager.isApplyUpdateForIndexEnabled() returns true,
* and the index table already exists, init() will do nothing.
*/
@Test
public void testInit_IndexTableExists() throws Exception{
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet tableCheckRs = mock(java.sql.ResultSet.class);
java.sql.ResultSet journalModeRs = mock(java.sql.ResultSet.class);
java.sql.ResultSet synchronousRs = mock(java.sql.ResultSet.class);
when(tableCheckRs.next()).thenReturn(true); // <- simulates a preexisting table
when(journalModeRs.next()).thenReturn(true).thenReturn(false);
when(synchronousRs.next()).thenReturn(true).thenReturn(false);
when(journalModeRs.getString(1)).thenReturn("DELETE");
when(synchronousRs.getInt(1)).thenReturn(2);
when(statement.executeQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cqtbl_features';")).thenReturn(tableCheckRs);
when(statement.executeQuery("PRAGMA journal_mode;")).thenReturn(journalModeRs);
when(statement.executeQuery("PRAGMA synchronous;")).thenReturn(synchronousRs);
when(connection.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);")).thenReturn(preparedStatement);
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
when(connection.createStatement()).thenReturn(statement);
when(preparedStatement.executeBatch()).thenReturn(new int[] {2});
// The objects to add
Set<Car> initWithObjects = new HashSet<Car>(2);
initWithObjects.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()));
initWithObjects.add(new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()));
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.init(wrappingObjectStore(initWithObjects), createQueryOptions(connectionManager));
// Verify
verify(statement, times(1)).executeQuery("PRAGMA journal_mode;");
verify(statement, times(1)).executeQuery("PRAGMA synchronous;");
// Verify we should not proceed to recreate the table...
verify(statement, times(0)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
}
/**
* Verifies that if connectionManager.isApplyUpdateForIndexEnabled() returns true,
* and the index table does not exist, init() will create and populate the index table.
*/
@Test
public void testInit_IndexTableDoesNotExist() throws Exception{
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet tableCheckRs = mock(java.sql.ResultSet.class);
java.sql.ResultSet journalModeRs = mock(java.sql.ResultSet.class);
java.sql.ResultSet synchronousRs = mock(java.sql.ResultSet.class);
when(tableCheckRs.next()).thenReturn(false); // <- simulates table does not already exist
when(journalModeRs.next()).thenReturn(true).thenReturn(false);
when(synchronousRs.next()).thenReturn(true).thenReturn(false);
when(journalModeRs.getString(1)).thenReturn("DELETE");
when(synchronousRs.getInt(1)).thenReturn(2);
when(statement.executeQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cqtbl_features';")).thenReturn(tableCheckRs);
when(statement.executeQuery("PRAGMA journal_mode;")).thenReturn(journalModeRs);
when(statement.executeQuery("PRAGMA synchronous;")).thenReturn(synchronousRs);
when(connection.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);")).thenReturn(preparedStatement);
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
when(connection.createStatement()).thenReturn(statement);
when(preparedStatement.executeBatch()).thenReturn(new int[] {2});
// The objects to add
Set<Car> initWithObjects = new HashSet<Car>(2);
initWithObjects.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()));
initWithObjects.add(new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()));
SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
""
);
carFeaturesOffHeapIndex.init(wrappingObjectStore(initWithObjects), createQueryOptions(connectionManager));
// Verify
verify(statement, times(1)).executeQuery("PRAGMA journal_mode;");
verify(statement, times(1)).executeQuery("PRAGMA synchronous;");
verify(statement, times(1)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
verify(statement, times(1)).executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
verify(statement, times(6)).close();
verify(preparedStatement, times(2)).setObject(1, 1);
verify(preparedStatement, times(1)).setObject(1, 2);
verify(preparedStatement, times(1)).setObject(2, "abs");
verify(preparedStatement, times(1)).setObject(2, "gps");
verify(preparedStatement, times(1)).setObject(2, "airbags");
verify(preparedStatement, times(3)).addBatch();
verify(preparedStatement, times(1)).executeBatch();
verify(preparedStatement, times(1)).close();
verify(connection, times(0)).close();
Assert.assertEquals(carFeaturesOffHeapIndex.pragmaSynchronous, SQLiteConfig.SynchronousMode.FULL);
Assert.assertEquals(carFeaturesOffHeapIndex.pragmaJournalMode, SQLiteConfig.JournalMode.DELETE);
Assert.assertTrue(carFeaturesOffHeapIndex.canModifySyncAndJournaling);
}
@Test
public void testNewResultSet_Size() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT COUNT(1) AS countDistinct FROM (SELECT objectKey FROM " + TABLE_NAME + " WHERE value = ? GROUP BY objectKey);")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true);
when(resultSet.getInt(1)).thenReturn(3);
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
int size = carsWithAbs.size();
assertEquals(3, size);
verify(connection, times(0)).close();
}
@Test
public void testNewResultSet_GetRetrievalCost() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertEquals(SQLiteIndex.INDEX_RETRIEVAL_COST, carsWithAbs.getRetrievalCost());
}
@Test
public void testNewResultSet_GetMergeCost() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true);
when(resultSet.getInt(1)).thenReturn(3);
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
int size = carsWithAbs.getMergeCost();
assertEquals(3, size);
verify(connection, times(0)).close();
}
@Test
public void testNewResultSet_Contains() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connectionContains = mock(Connection.class);
Connection connectionDoNotContain = mock(Connection.class);
PreparedStatement preparedStatementContains = mock(PreparedStatement.class);
PreparedStatement preparedStatementDoNotContains = mock(PreparedStatement.class);
java.sql.ResultSet resultSetContains = mock(java.sql.ResultSet.class);
java.sql.ResultSet resultSetDoNotContain = mock(java.sql.ResultSet.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connectionContains).thenReturn(connectionDoNotContain);
when(connectionContains.prepareStatement("SELECT objectKey FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ? LIMIT 1;")).thenReturn(preparedStatementContains);
when(connectionDoNotContain.prepareStatement("SELECT objectKey FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ? LIMIT 1;")).thenReturn(preparedStatementDoNotContains);
when(preparedStatementContains.executeQuery()).thenReturn(resultSetContains);
when(preparedStatementDoNotContains.executeQuery()).thenReturn(resultSetDoNotContain);
when(resultSetContains.next()).thenReturn(true).thenReturn(false);
when(resultSetDoNotContain.next()).thenReturn(false);
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
boolean resultContains = carsWithAbs.contains(data.get(0));
assertTrue(resultContains);
verify(connectionContains, times(0)).close();
boolean resultDoNotContain = carsWithAbs.contains(data.get(1));
assertFalse(resultDoNotContain);
verify(connectionDoNotContain, times(0)).close();
}
@Test(expected = IllegalStateException.class)
public void testNewResultSet_Iterator_Exception_Close() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenThrow(new SQLException("SQL exception"));
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
// Iterator
try {
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
Iterator<Car> carsWithAbsIterator = carsWithAbs.iterator();
assertNotNull(carsWithAbsIterator.next());
carsWithAbsIterator.next();// Should throw exception!
}finally {
verify(connection, times(0)).close(); // Connection should be left open
verify(preparedStatement, times(1)).close();
verify(resultSet, times(1)).close();
}
}
@Test
public void testNewResultSet_Iterator_Close() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenReturn(3);
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
Iterator carsWithAbsIterator = carsWithAbs.iterator();
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertFalse(carsWithAbsIterator.hasNext());
// The end of the iteration should close the resources
verify(connection, times(0)).close(); // Connection should be left open
verify(preparedStatement, times(1)).close();
verify(resultSet, times(1)).close();
}
@Test
public void testNewResultSet_Close() throws Exception{
// Mocks
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT DISTINCT objectKey FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenReturn(3);
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
Iterator carsWithAbsIterator = carsWithAbs.iterator();
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
// Do not continue with the iteration, but close
carsWithAbs.close();
verify(connection, times(0)).close(); // Connection should be left open
verify(preparedStatement, times(1)).close();
verify(resultSet, times(1)).close();
}
@Test
public void testRowIterable(){
Iterable<DBQueries.Row<Integer, String>> rows = SQLiteIndex.rowIterable(data, Car.CAR_ID, Car.FEATURES, null);
assertNotNull(rows);
Iterator<DBQueries.Row<Integer, String>> rowsIterator = rows.iterator();
assertNotNull(rowsIterator);
assertTrue(rowsIterator.hasNext());
assertEquals(new DBQueries.Row<Integer, String>(1, "abs"), rowsIterator.next());
assertTrue(rowsIterator.hasNext());
assertEquals(new DBQueries.Row<Integer, String>(1, "gps"), rowsIterator.next());
assertTrue(rowsIterator.hasNext());
assertEquals(new DBQueries.Row<Integer, String>(2, "airbags"), rowsIterator.next());
assertTrue(rowsIterator.hasNext());
assertEquals(new DBQueries.Row<Integer, String>(3, "abs"), rowsIterator.next());
assertTrue(rowsIterator.hasNext());
assertEquals(new DBQueries.Row<Integer, String>(5, "gps"), rowsIterator.next());
assertFalse(rowsIterator.hasNext());
}
@Test
public void testObjectKeyIterable(){
Iterable<Integer> objectKeys = SQLiteIndex.objectKeyIterable(data, Car.CAR_ID, null);
assertNotNull(objectKeys);
Iterator<Integer> objectKeysIterator = objectKeys.iterator();
assertNotNull(objectKeysIterator);
assertTrue(objectKeysIterator.hasNext());
assertEquals(new Integer(1), objectKeysIterator.next());
assertTrue(objectKeysIterator.hasNext());
assertEquals(new Integer(2), objectKeysIterator.next());
assertTrue(objectKeysIterator.hasNext());
assertEquals(new Integer(3), objectKeysIterator.next());
assertTrue(objectKeysIterator.hasNext());
assertEquals(new Integer(4), objectKeysIterator.next());
assertTrue(objectKeysIterator.hasNext());
assertEquals(new Integer(5), objectKeysIterator.next());
assertFalse(objectKeysIterator.hasNext());
}
@Test
public void testGetDistinctKeys_AllAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
List<String> actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_AllDescending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected = Arrays.asList("Taurus", "Prius", "M6", "Insight", "Hilux", "Fusion", "Focus", "Civic", "Avensis", "Accord");
List<String> actual = Lists.newArrayList(offHeapIndex.getDistinctKeysDescending(createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_GreaterThanExclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("", false, null, true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("A", false, null, true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
expected = Arrays.asList("Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Accord", false, null, true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_GreaterThanInclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Accord", true, null, true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_LessThanExclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList();
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "", false, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Z", false, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Prius", false, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_LessThanInclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys(null, true, "Prius", true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_BetweenExclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Focus", "Fusion", "Hilux");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Civic", false, "Insight", false, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_BetweenInclusiveAscending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Civic", "Focus", "Fusion", "Hilux", "Insight");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Civic", true, "Insight", true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetDistinctKeys_BetweenInclusiveDescending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MODEL,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
List<String> expected, actual;
expected = Arrays.asList("Insight", "Hilux", "Fusion", "Focus", "Civic");
actual = Lists.newArrayList(offHeapIndex.getDistinctKeysDescending("Civic", true, "Insight", true, createQueryOptions(connectionManager)));
assertEquals(expected, actual);
}
@Test
public void testGetKeysAndValues(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MANUFACTURER,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
Multimap<String, Car> expected = MultimapBuilder.SetMultimapBuilder.linkedHashKeys().hashSetValues().build();
expected.put("BMW", CarFactory.createCar(9));
expected.put("Ford", CarFactory.createCar(0));
expected.put("Ford", CarFactory.createCar(1));
expected.put("Ford", CarFactory.createCar(2));
expected.put("Honda", CarFactory.createCar(3));
expected.put("Honda", CarFactory.createCar(4));
expected.put("Honda", CarFactory.createCar(5));
expected.put("Toyota", CarFactory.createCar(6));
expected.put("Toyota", CarFactory.createCar(7));
expected.put("Toyota", CarFactory.createCar(8));
Multimap<String, Car> actual = MultimapBuilder.SetMultimapBuilder.linkedHashKeys().hashSetValues().build();
CloseableIterable<KeyValue<String, Car>> keysAndValues = offHeapIndex.getKeysAndValues(createQueryOptions(connectionManager));
for (KeyValue<String, Car> keyValue : keysAndValues) {
actual.put(keyValue.getKey(), keyValue.getValue());
}
assertEquals("keys and values", expected, actual);
List<String> expectedKeysOrder = Lists.newArrayList(expected.keySet());
List<String> actualKeysOrder = Lists.newArrayList(actual.keySet());
assertEquals("key order", expectedKeysOrder, actualKeysOrder);
}
@Test
public void testGetKeysAndValuesDescending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MANUFACTURER,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
Multimap<String, Car> expected = MultimapBuilder.SetMultimapBuilder.linkedHashKeys().hashSetValues().build();
expected.put("Toyota", CarFactory.createCar(6));
expected.put("Toyota", CarFactory.createCar(7));
expected.put("Toyota", CarFactory.createCar(8));
expected.put("Honda", CarFactory.createCar(3));
expected.put("Honda", CarFactory.createCar(4));
expected.put("Honda", CarFactory.createCar(5));
expected.put("Ford", CarFactory.createCar(0));
expected.put("Ford", CarFactory.createCar(1));
expected.put("Ford", CarFactory.createCar(2));
expected.put("BMW", CarFactory.createCar(9));
Multimap<String, Car> actual = MultimapBuilder.SetMultimapBuilder.linkedHashKeys().hashSetValues().build();
CloseableIterable<KeyValue<String, Car>> keysAndValues = offHeapIndex.getKeysAndValuesDescending(createQueryOptions(connectionManager));
for (KeyValue<String, Car> keyValue : keysAndValues) {
actual.put(keyValue.getKey(), keyValue.getValue());
}
assertEquals("keys and values", expected, actual);
List<String> expectedKeysOrder = Lists.newArrayList(expected.keySet());
List<String> actualKeysOrder = Lists.newArrayList(actual.keySet());
assertEquals("key order", expectedKeysOrder, actualKeysOrder);
}
@Test
public void testGetCountOfDistinctKeys(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MANUFACTURER,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));
Assert.assertEquals(Integer.valueOf(4), offHeapIndex.getCountOfDistinctKeys(createQueryOptions(connectionManager)));
}
@Test
public void testGetStatisticsForDistinctKeys(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MANUFACTURER,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));
Set<KeyStatistics<String>> keyStatistics = setOf(offHeapIndex.getStatisticsForDistinctKeys(createQueryOptions(connectionManager)));
Assert.assertEquals(setOf(
new KeyStatistics<String>("Ford", 6),
new KeyStatistics<String>("Honda", 6),
new KeyStatistics<String>("Toyota", 6),
new KeyStatistics<String>("BMW", 2)
),
keyStatistics);
}
@Test
public void testGetStatisticsForDistinctKeysDescending(){
ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
Car.MANUFACTURER,
Car.CAR_ID,
new SimpleAttribute<Integer, Car>() {
@Override
public Car getValue(Integer carId, QueryOptions queryOptions) {
return CarFactory.createCar(carId);
}
}
);
offHeapIndex.addAll(createObjectSetOfCars(20), createQueryOptions(connectionManager));
Set<KeyStatistics<String>> keyStatistics = setOf(offHeapIndex.getStatisticsForDistinctKeysDescending(createQueryOptions(connectionManager)));
Assert.assertEquals(setOf(
new KeyStatistics<String>("Toyota", 6),
new KeyStatistics<String>("Honda", 6),
new KeyStatistics<String>("Ford", 6),
new KeyStatistics<String>("BMW", 2)
),
keyStatistics);
}
@Test(expected = IllegalStateException.class)
public void testNewResultSet_FilterQuery_Iterator_Exception_Close() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(statement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenThrow(new SQLException("SQL exception"));
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
// Iterator
try {
ResultSet<Car> cars = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(cars);
Iterator<Car> carsWithAbsIterator = cars.iterator();
assertNotNull(carsWithAbsIterator.next());
carsWithAbsIterator.next();// Should throw exception!
}finally {
verify(connection, times(0)).close(); // Connection should be left open
verify(statement, times(1)).close();
verify(resultSet, times(1)).close();
}
}
@Test
public void testNewResultSet_FilterQuery_Iterator_Close() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(statement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenReturn(1).thenReturn(2).thenReturn(3).thenReturn(4).thenReturn(5);
when(resultSet.getString(2)).thenReturn("abs").thenReturn("gps").thenReturn("airbags").thenReturn("abs").thenReturn("").thenReturn("gps");
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
when(idToObject.getValue(eq(5), anyQueryOptions())).thenReturn(data.get(4));
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
Iterator carsWithAbsIterator = carsWithAbs.iterator();
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
assertFalse(carsWithAbsIterator.hasNext());
// The end of the iteration should close the resources
verify(connection, times(0)).close(); // Connection should be left open
verify(statement, times(1)).close();
verify(resultSet, times(1)).close();
}
@Test
public void testNewResultSet_FilterQuery_Close() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
@SuppressWarnings("unchecked")
SimpleAttribute<Integer, Car> idToObject = (SimpleAttribute<Integer, Car>)mock(SimpleAttribute.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(statement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenReturn(1).thenReturn(2).thenReturn(3).thenReturn(4).thenReturn(5);
when(resultSet.getString(2)).thenReturn("abs").thenReturn("gps").thenReturn("airbags").thenReturn("abs").thenReturn("").thenReturn("gps");
when(idToObject.getValue(eq(1), anyQueryOptions())).thenReturn(data.get(0));
when(idToObject.getValue(eq(3), anyQueryOptions())).thenReturn(data.get(2));
when(idToObject.getValue(eq(5), anyQueryOptions())).thenReturn(data.get(4));
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
idToObject,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
Iterator carsWithAbsIterator = carsWithAbs.iterator();
assertTrue(carsWithAbsIterator.hasNext());
assertNotNull(carsWithAbsIterator.next());
// Do not continue with the iteration, but close
carsWithAbs.close();
verify(connection, times(0)).close(); // Connection should be left open
verify(statement, times(1)).close();
verify(resultSet, times(1)).close();
}
@Test
public void testNewResultSet_FilterQuery_GetMergeCost() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
// Behaviour
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.prepareStatement("SELECT COUNT(objectKey) FROM " + TABLE_NAME + " ;")).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(preparedStatement);
when(resultSet.next()).thenReturn(true);
when(resultSet.getInt(1)).thenReturn(3);
// Iterator
ResultSet<Car> cars = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(cars);
int mergeCost = cars.getMergeCost();
assertEquals(3, mergeCost);
verify(connection, times(0)).close();
}
@Test
public void testNewResultSet_FilterQuery_GetRetrievalCost(){
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertEquals(carsWithAbs.getRetrievalCost(), SQLiteIndex.INDEX_RETRIEVAL_COST_FILTERING);
}
@Test
public void testNewResultSet_FilterQuery_Contains() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connectionContains = mock(Connection.class);
Connection connectionDoNotContain = mock(Connection.class);
Connection connectionNoRows = mock(Connection.class);
PreparedStatement preparedStatementContains = mock(PreparedStatement.class);
PreparedStatement preparedStatementDoNotContains = mock(PreparedStatement.class);
PreparedStatement preparedStatementNoRows = mock(PreparedStatement.class);
java.sql.ResultSet resultSetContains = mock(java.sql.ResultSet.class);
java.sql.ResultSet resultSetDoNotContain = mock(java.sql.ResultSet.class);
java.sql.ResultSet resultSetNoRows = mock(java.sql.ResultSet.class);
// Behaviour
//SELECT objectKey, value FROM cqtbl_%s WHERE objectKey=?
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connectionContains).thenReturn(connectionDoNotContain).thenReturn(connectionNoRows);
when(connectionContains.prepareStatement("SELECT objectKey, value FROM " + TABLE_NAME + " WHERE objectKey = ?")).thenReturn(preparedStatementContains);
when(connectionDoNotContain.prepareStatement("SELECT objectKey, value FROM " + TABLE_NAME + " WHERE objectKey = ?")).thenReturn(preparedStatementDoNotContains);
when(connectionNoRows.prepareStatement("SELECT objectKey, value FROM " + TABLE_NAME + " WHERE objectKey = ?")).thenReturn(preparedStatementNoRows);
when(preparedStatementContains.executeQuery()).thenReturn(resultSetContains);
when(preparedStatementDoNotContains.executeQuery()).thenReturn(resultSetDoNotContain);
when(preparedStatementNoRows.executeQuery()).thenReturn(resultSetNoRows);
when(resultSetContains.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSetContains.getInt(1)).thenReturn(1).thenReturn(1);
when(resultSetContains.getString(2)).thenReturn("abs").thenReturn("gps");
when(resultSetDoNotContain.next()).thenReturn(true).thenReturn(false);
when(resultSetDoNotContain.getInt(1)).thenReturn(2);
when(resultSetDoNotContain.getString(2)).thenReturn("airbags");
when(resultSetNoRows.next()).thenReturn(false);
// Iterator
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
boolean resultContains = carsWithAbs.contains(data.get(0));
assertTrue(resultContains);
verify(connectionContains, times(0)).close();
boolean resultDoNotContain = carsWithAbs.contains(data.get(1));
assertFalse(resultDoNotContain);
verify(connectionDoNotContain, times(0)).close();
boolean resultNoRows = carsWithAbs.contains(CarFactory.createCar(100));
assertFalse(resultNoRows);
verify(connectionNoRows, times(0)).close();
}
@Test
public void testNewResultSet_FilterQuery_Size() throws Exception{
// Mocks
FilterQuery<Car, String> filterQuery = mockFilterQuery();
ConnectionManager connectionManager = mock(ConnectionManager.class);
Connection connection = mock(Connection.class);
Statement statement = mock(PreparedStatement.class);
java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
// Behaviour//
when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery("SELECT objectKey, value FROM " + TABLE_NAME + " ORDER BY objectKey;")).thenReturn(resultSet);
when(resultSet.getStatement()).thenReturn(statement);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1).thenReturn(1).thenReturn(2).thenReturn(3).thenReturn(4).thenReturn(5);
when(resultSet.getString(2)).thenReturn("abs").thenReturn("gps").thenReturn("airbags").thenReturn("abs").thenReturn("").thenReturn("gps");
ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
Car.FEATURES,
OBJECT_TO_ID,
ID_TO_OBJECT,
"")
.retrieve(filterQuery, createQueryOptions(connectionManager));
assertNotNull(carsWithAbs);
int size = carsWithAbs.size();
assertEquals(3, size);
verify(connection, times(0)).close();
}
static FilterQuery<Car, String> mockFilterQuery(){
@SuppressWarnings("unchecked")
FilterQuery<Car, String> filterQuery = (FilterQuery<Car, String>)mock(FilterQuery.class);
when(filterQuery.matchesValue(Mockito.anyString(), any(QueryOptions.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
Object[] args = invocationOnMock.getArguments();
if (args != null && args.length == 2 && args[0] instanceof String) {
String value = (String) args[0];
return "abs".equals(value) || "gps".equals(value);
}
throw new IllegalStateException("matchesValue invocation not expected. Args " + Arrays.toString(args));
}
});
return filterQuery;
}
static QueryOptions createQueryOptions(ConnectionManager connectionManager) {
QueryOptions queryOptions = new QueryOptions();
queryOptions.put(ConnectionManager.class, connectionManager);
return queryOptions;
}
static ObjectStore<Car> emptyObjectStore() {
return new ConcurrentOnHeapObjectStore<Car>();
}
static ObjectStore<Car> wrappingObjectStore(Collection<Car> objects) {
ConcurrentOnHeapObjectStore<Car> objectStore = new ConcurrentOnHeapObjectStore<Car>();
objectStore.addAll(objects, noQueryOptions());
return objectStore;
}
static QueryOptions anyQueryOptions() {
return Mockito.any();
}
static ObjectSet<Car> createObjectSetOfCars(int numCars) {
return ObjectSet.fromCollection(CarFactory.createCollectionOfCars(numCars));
}
static ObjectSet<Car> objectSet(Collection<Car> collection) {
return ObjectSet.fromCollection(collection);
}
} | 67,263 | 46.704965 | 192 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/TemporaryDatabase.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite;
import com.googlecode.cqengine.index.Index;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.junit.Assert;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
/**
* Set of utility classes and {@link org.junit.Rule} to test Disk index against a temporary SQLite database.
*
* @author Silvano Riz
*/
public class TemporaryDatabase {
// ----------------------
// Helper classes & methods
// ----------------------
public static interface ConnectionProxy extends Connection {
Connection getTargetConnection();
}
static Connection createConnectionProxy(final Connection connection) throws SQLException {
return (Connection) Proxy.newProxyInstance(
ConnectionProxy.class.getClassLoader(),
new Class<?>[]{ConnectionProxy.class},
new SuppressCloseInvocationHandler(connection));
}
static class SuppressCloseInvocationHandler implements InvocationHandler {
private final Connection target;
public SuppressCloseInvocationHandler(Connection target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on ConnectionProxy interface coming in...
final String methodName = method.getName();
if ("close".equals(methodName)) {
// Close method does nothing.
return null;
} else if ("getTargetConnection".equals(methodName)) {
// Handle getTargetConnection method: return underlying Connection.
return this.target;
}
// Invoke method on target Connection.
try {
return method.invoke(this.target, args);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
static void closeQuietly(final Connection connection) {
try {
if (connection != null) {
if (connection instanceof ConnectionProxy) {
((ConnectionProxy) connection).getTargetConnection().close();
} else {
connection.close();
}
}
} catch (Exception e) {
// Ignore
}
}
/**
* {@link org.junit.Rule} that allows to create and safely delete an SQLite temporary database file.
*
* @author Silvano Riz
*/
public static class TemporaryFileDatabase extends TemporaryFolder {
SQLiteDataSource dataSource;
SQLiteConfig config;
String url;
File dbFile;
Set<Connection> singleConnections = new HashSet<Connection>();
public TemporaryFileDatabase() {
this.config = new SQLiteConfig();
}
public TemporaryFileDatabase(SQLiteConfig config) {
this.config = config;
}
@Override
public void before() {
try {
super.before();
dbFile = newFile();
url = "jdbc:sqlite:" + dbFile.getAbsolutePath();
dataSource = new SQLiteDataSource(config);
dataSource.setUrl(url);
}
catch (Throwable throwable) {
throw new IllegalStateException(throwable);
}
}
@Override
public void after() {
super.after();
Assert.assertFalse(dbFile.exists());
for (Connection connection : singleConnections) {
closeQuietly(connection);
}
}
/**
* Returns the {@link ConnectionManager} for the tmp database.
*
* @return The {@link ConnectionManager} for the tmp database.
*/
public ConnectionManager getConnectionManager(final boolean applyUpdateForIndexEnabled) {
return new ConnectionManager() {
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
try {
return dataSource.getConnection();
} catch (Exception e) {
throw new IllegalStateException("Unable to create connection to: " + url, e);
}
}
@Override
public boolean isApplyUpdateForIndexEnabled(Index<?> index) {
return applyUpdateForIndexEnabled;
}
};
}
}
/**
* {@link org.junit.Rule} that allows to create and safely shut down an SQLite in-memory database.
*
* @author Silvano Riz
*/
public static class TemporaryInMemoryDatabase implements TestRule {
Connection connection = null;
SQLiteConfig config = null;
public TemporaryInMemoryDatabase(){}
public TemporaryInMemoryDatabase(final SQLiteConfig config){
this.config = config;
}
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} finally {
after();
}
}
};
}
public void after() {
closeQuietly(connection);
}
public void before() {
try {
if (config != null) {
connection = createConnectionProxy(DriverManager.getConnection("jdbc:sqlite:", config.toProperties()));
}else{
connection = createConnectionProxy(DriverManager.getConnection("jdbc:sqlite:"));
}
} catch (Exception e) {
throw new IllegalStateException("Cannot create in-memory database connection", e);
}
}
/**
* Returns the {@link ConnectionManager} for the tmp database.
*
* @return The {@link ConnectionManager} for the tmp database.
*/
public ConnectionManager getConnectionManager(final boolean applyUpdateForIndexEnabled) {
return new ConnectionManager() {
@Override
public Connection getConnection(Index<?> index, QueryOptions queryOptions) {
return connection;
}
@Override
public boolean isApplyUpdateForIndexEnabled(Index<?> index) {
return applyUpdateForIndexEnabled;
}
};
}
}
}
| 7,948 | 31.182186 | 123 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/support/DBQueriesTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite.support;
import com.googlecode.cqengine.index.sqlite.ConnectionManager;
import com.googlecode.cqengine.query.simple.*;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.sqlite.SQLiteConfig;
import java.sql.*;
import java.util.*;
import static com.googlecode.cqengine.index.sqlite.TemporaryDatabase.TemporaryFileDatabase;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.QueryFactory.startsWith;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link DBQueries}
*
* @author Silvano Riz
*/
public class DBQueriesTest {
private static final String NAME = "features";
private static final String TABLE_NAME = "cqtbl_" + NAME;
private static final String INDEX_NAME = "cqidx_" + NAME + "_value";
@Rule
public TemporaryFileDatabase temporaryFileDatabase = new TemporaryFileDatabase();
@Test
public void testCreateIndexTable() throws SQLException {
Connection connection = null;
Statement statement = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
connection = spy(connectionManager.getConnection(null, noQueryOptions()));
statement = spy(connection.createStatement());
when(connection.createStatement()).thenReturn(statement);
DBQueries.createIndexTable(NAME, Integer.class, String.class, connection);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", false, connectionManager);
verify(statement, times(1)).close();
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
@Test
public void testCreateIndexOnTable() throws SQLException {
Connection connection = null;
Statement statement = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
connection = spy(connectionManager.getConnection(null, noQueryOptions()));
statement = spy(connection.createStatement());
when(connection.createStatement()).thenReturn(statement);
DBQueries.createIndexTable(NAME, Integer.class, String.class, connection);
DBQueries.createIndexOnTable(NAME, connection);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", true, connectionManager);
verify(statement, times(2)).close();
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
@Test
public void testDropIndexOnTable() throws SQLException {
Connection connection = null;
Statement statement = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
connection = spy(connectionManager.getConnection(null, noQueryOptions()));
statement = spy(connection.createStatement());
when(connection.createStatement()).thenReturn(statement);
DBQueries.createIndexTable(NAME, Integer.class, String.class, connection);
DBQueries.createIndexOnTable(NAME, connection);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", true, connectionManager);
DBQueries.dropIndexOnTable(NAME, connection);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", false, connectionManager);
verify(statement, times(3)).close();
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
@Test
public void testDropIndexTable() throws SQLException {
Connection connection = null;
Statement statement = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
createSchema(connectionManager);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", true, connectionManager);
connection = spy(connectionManager.getConnection(null, noQueryOptions()));
statement = spy(connection.createStatement());
when(connection.createStatement()).thenReturn(statement);
DBQueries.dropIndexTable(NAME, connection);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", false, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", false, connectionManager);
verify(statement, times(1)).close();
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
@Test
public void testClearIndexTable() throws SQLException {
Connection connection = null;
Statement statement = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
createSchema(connectionManager);
assertObjectExistenceInSQLIteMasterTable(TABLE_NAME, "table", true, connectionManager);
assertObjectExistenceInSQLIteMasterTable(INDEX_NAME, "index", true, connectionManager);
connection = spy(connectionManager.getConnection(null, noQueryOptions()));
statement = spy(connection.createStatement());
when(connection.createStatement()).thenReturn(statement);
DBQueries.clearIndexTable(NAME, connection);
List<DBQueries.Row<Integer, String>> expectedRows = Collections.emptyList();
assertQueryResultSet("SELECT * FROM " + TABLE_NAME, expectedRows, connectionManager);
verify(statement, times(1)).close();
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
@Test
public void testBulkAdd() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
createSchema(connectionManager);
List<DBQueries.Row<Integer, String>> rowsToAdd = new ArrayList<DBQueries.Row<Integer, String>>(4);
rowsToAdd.add(new DBQueries.Row<Integer, String>(1, "abs"));
rowsToAdd.add(new DBQueries.Row<Integer, String>(1, "gps"));
rowsToAdd.add(new DBQueries.Row<Integer, String>(2, "airbags"));
rowsToAdd.add(new DBQueries.Row<Integer, String>(2, "abs"));
connection = connectionManager.getConnection(null, noQueryOptions());
DBQueries.bulkAdd(rowsToAdd, NAME, connection);
assertQueryResultSet("SELECT * FROM " + TABLE_NAME, rowsToAdd, connectionManager);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testBulkRemove() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
List<DBQueries.Row<Integer, String>> expectedRows = new ArrayList<DBQueries.Row<Integer, String>>(2);
expectedRows.add(new DBQueries.Row<Integer, String>(2, "airbags"));
expectedRows.add(new DBQueries.Row<Integer, String>(3, "abs"));
connection = connectionManager.getConnection(null, noQueryOptions());
DBQueries.bulkRemove(Collections.singletonList(1), NAME, connection);
assertQueryResultSet("SELECT * FROM " + TABLE_NAME, expectedRows, connectionManager);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testGetAllIndexEntries() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
List<DBQueries.Row<Integer, String>> expectedRows = new ArrayList<DBQueries.Row<Integer, String>>(2);
expectedRows.add(new DBQueries.Row<Integer, String>(1, "abs"));
expectedRows.add(new DBQueries.Row<Integer, String>(1, "gps"));
expectedRows.add(new DBQueries.Row<Integer, String>(2, "airbags"));
expectedRows.add(new DBQueries.Row<Integer, String>(3, "abs"));
connection = connectionManager.getConnection(null, noQueryOptions());
ResultSet resultSet = DBQueries.getAllIndexEntries( NAME, connection);
assertResultSetOrderAgnostic(resultSet, expectedRows);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testGetIndexEntryByObjectKey() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
connection = connectionManager.getConnection(null, noQueryOptions());
ResultSet resultSet = DBQueries.getIndexEntryByObjectKey(3, NAME, connection);
List<DBQueries.Row<Integer, String>> expectedRows = new ArrayList<DBQueries.Row<Integer, String>>(2);
expectedRows.add(new DBQueries.Row<Integer, String>(3, "abs"));
assertResultSetOrderAgnostic(resultSet, expectedRows);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testCount_Equal() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
Equal<Car, String> equal = equal(Car.FEATURES, "abs");
connection = connectionManager.getConnection(null, noQueryOptions());
int count = DBQueries.count(equal, NAME, connection);
Assert.assertEquals(2, count);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testSearch_Equal() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
Equal<Car, String> equal = equal(Car.FEATURES, "abs");
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(equal, NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 3));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testSearch_LessThan() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
LessThan<Car, String> lessThan = lessThan(Car.FEATURES, "abz");
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(lessThan, NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 3));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testSearch_GreaterThan() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
GreaterThan<Car, String> greaterThan = greaterThan(Car.FEATURES, "abz");
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(greaterThan, NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 2));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testSearch_Between() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
Between<Car, String> between = between(Car.FEATURES, "a", "b");
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(between, NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 2, 3));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testSearch_StringStartsWith() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
StringStartsWith<Car, String> startsWith = startsWith(Car.FEATURES, "ab");
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(startsWith, NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 3));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testSearch_Has() throws SQLException {
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.search(has(selfAttribute(Car.class)), NAME, connection);
assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 2, 3));
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(resultSet);
}
}
@Test
public void testContains() throws SQLException {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
Equal<Car, String> equal = equal(Car.FEATURES, "abs");
connection = connectionManager.getConnection(null, noQueryOptions());
Assert.assertTrue(DBQueries.contains(1, equal, NAME, connection));
Assert.assertFalse(DBQueries.contains(4, equal, NAME, connection));
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testEnsureNotNegative_ValidCase() {
IllegalStateException unexpected = null;
try {
DBQueries.ensureNotNegative(0);
DBQueries.ensureNotNegative(1);
}
catch (IllegalStateException e) {
unexpected = e;
}
assertNull(unexpected);
}
@Test
public void testEnsureNotNegative_InvalidCase() {
IllegalStateException expected = null;
try {
DBQueries.ensureNotNegative(-1);
}
catch (IllegalStateException e) {
expected = e;
}
assertNotNull(expected);
assertEquals("Update returned error code: -1", expected.getMessage());
}
@Test
public void getDistinctKeysAndCounts(){
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.getDistinctKeysAndCounts(false, NAME, connection);
Map<String, Integer> resultSetToMap = resultSetToMap(resultSet);
assertEquals(3, resultSetToMap.size());
assertEquals(new Integer(2), resultSetToMap.get("abs"));
assertEquals(new Integer(1), resultSetToMap.get("airbags"));
assertEquals(new Integer(1), resultSetToMap.get("gps"));
}finally {
DBUtils.closeQuietly(resultSet);
DBUtils.closeQuietly(connection);
}
}
@Test
public void getDistinctKeysAndCounts_SortByKeyDescending(){
Connection connection = null;
ResultSet resultSet = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
connection = connectionManager.getConnection(null, noQueryOptions());
resultSet = DBQueries.getDistinctKeysAndCounts(true, NAME, connection);
Map<String, Integer> resultSetToMap = resultSetToMap(resultSet);
assertEquals(3, resultSetToMap.size());
Iterator<Map.Entry<String, Integer>> entriesIterator = resultSetToMap.entrySet().iterator();
Map.Entry entry = entriesIterator.next();
assertEquals("gps", entry.getKey());
assertEquals(1, entry.getValue());
entry = entriesIterator.next();
assertEquals("airbags", entry.getKey());
assertEquals(1, entry.getValue());
entry = entriesIterator.next();
assertEquals("abs", entry.getKey());
assertEquals(2, entry.getValue());
}finally {
DBUtils.closeQuietly(resultSet);
DBUtils.closeQuietly(connection);
}
}
@Test
public void getCountOfDistinctKeys(){
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
initWithTestData(connectionManager);
connection = connectionManager.getConnection(null, noQueryOptions());
int countOfDistinctKeys = DBQueries.getCountOfDistinctKeys(NAME, connection);
assertEquals(3, countOfDistinctKeys);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void suspendSyncAndJournaling() throws Exception {
Connection connection = null;
try {
ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
connection = connectionManager.getConnection(null, noQueryOptions());
final SQLiteConfig.JournalMode journalMode = DBQueries.getPragmaJournalModeOrNull(connection);
final SQLiteConfig.SynchronousMode synchronousMode = DBQueries.getPragmaSynchronousOrNull(connection);
DBQueries.suspendSyncAndJournaling(connection);
final SQLiteConfig.JournalMode journalModeDisabled = DBQueries.getPragmaJournalModeOrNull(connection);
final SQLiteConfig.SynchronousMode synchronousModeDisabled = DBQueries.getPragmaSynchronousOrNull(connection);
Assert.assertEquals(journalModeDisabled, SQLiteConfig.JournalMode.OFF);
Assert.assertEquals(synchronousModeDisabled, SQLiteConfig.SynchronousMode.OFF);
DBQueries.setSyncAndJournaling(connection, SQLiteConfig.SynchronousMode.FULL, SQLiteConfig.JournalMode.DELETE);
final SQLiteConfig.JournalMode journalModeReset = DBQueries.getPragmaJournalModeOrNull(connection);
final SQLiteConfig.SynchronousMode synchronousModeReset = DBQueries.getPragmaSynchronousOrNull(connection);
Assert.assertEquals(journalModeReset, journalMode);
Assert.assertEquals(synchronousModeReset, synchronousMode);
}finally {
DBUtils.closeQuietly(connection);
}
}
@Test
public void testIndexTableExists_ExceptionHandling() throws SQLException {
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
when(connection.createStatement()).thenReturn(statement);
when(statement.executeQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cqtbl_foo';"))
.thenThrow(new SQLException("expected_exception"));
IllegalStateException expected = null;
try {
DBQueries.indexTableExists("foo", connection);
}
catch (IllegalStateException e) {
expected = e;
}
assertNotNull(expected);
assertEquals("Unable to determine if table exists: foo", expected.getMessage());
assertNotNull(expected.getCause());
assertEquals("expected_exception", expected.getCause().getMessage());
}
void createSchema(final ConnectionManager connectionManager){
Connection connection = null;
Statement statement = null;
try {
connection = connectionManager.getConnection(null, noQueryOptions());
statement = connection.createStatement();
assertEquals(statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT)"), 0);
assertEquals(statement.executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + "(value)"), 0);
}catch(Exception e){
throw new IllegalStateException("Unable to create test database schema", e);
}finally{
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
void initWithTestData(final ConnectionManager connectionManager){
createSchema(connectionManager);
Connection connection = null;
Statement statement = null;
try {
connection = connectionManager.getConnection(null, noQueryOptions());
statement = connection.createStatement();
assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (1, 'abs')"), 1);
assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (1, 'gps')"), 1);
assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (2, 'airbags')"), 1);
assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (3, 'abs')"), 1);
}catch(Exception e){
throw new IllegalStateException("Unable to initialize test database",e);
}finally{
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
public void assertObjectExistenceInSQLIteMasterTable(final String name, final String type, boolean exists, final ConnectionManager connectionManager){
Connection connection = null;
PreparedStatement statement = null;
try{
connection = connectionManager.getConnection(null, noQueryOptions());
statement = connection.prepareStatement("SELECT name FROM sqlite_master WHERE type=?");
statement.setString(1, type);
java.sql.ResultSet indices = statement.executeQuery();
boolean found = false;
StringBuilder objectsFound = new StringBuilder();
String next;
while(indices.next()){
next = indices.getString(1);
objectsFound.append("'").append(next).append("' ");
if (name.equals(next)){
found = true;
}
}
if (exists)
Assert.assertTrue("Object '" + name + "' must exists in 'sqlite_master' but it doesn't. found: " + found + ". Objects found: " + objectsFound, found);
else
Assert.assertFalse("Object '" + name + "' must NOT exists in 'sqlite_master' but it does. found: " + found + " Objects found: " + objectsFound, found);
}catch(Exception e){
throw new IllegalStateException("Unable to verify existence of the object '" + name + "' in the 'sqlite_master' table", e);
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
public static <K, V> Map<K, V> resultSetToMap(final ResultSet resultSet){
try {
final Map<K, V> map = new LinkedHashMap<K, V>();
while (resultSet.next()) {
@SuppressWarnings("unchecked")
K key = (K) resultSet.getObject(1);
@SuppressWarnings("unchecked")
V value = (V) resultSet.getObject(2);
map.put(key, value);
}
return map;
}catch(Exception e){
throw new IllegalStateException("Unable to transform the resultSet into a Map", e);
}
}
public void assertResultSetObjectKeysOrderAgnostic(final ResultSet resultSet, final List<Integer> objectKeys){
try {
List<Integer> actual = new ArrayList<Integer>(objectKeys.size());
while (resultSet.next()) {
actual.add(resultSet.getInt(1));
}
Collections.sort(actual);
Collections.sort(objectKeys);
Assert.assertEquals(objectKeys, actual);
}catch(Exception e){
throw new IllegalStateException("Unable to verify resultSet", e);
}
}
public void assertResultSetOrderAgnostic(final ResultSet resultSet, final List<DBQueries.Row<Integer, String>> rows){
try {
List<DBQueries.Row<Integer, String>> actual = new ArrayList<DBQueries.Row<Integer, String>>(rows.size());
while (resultSet.next()) {
actual.add(new DBQueries.Row<Integer, String>(resultSet.getInt(1), resultSet.getString(2)));
}
Comparator<DBQueries.Row<Integer, String>> comparator = new Comparator<DBQueries.Row<Integer, String>>() {
@Override
public int compare(DBQueries.Row<Integer, String> o1, DBQueries.Row<Integer, String> o2) {
int objectKeyComparison = o1.getObjectKey().compareTo(o2.getObjectKey());
if (objectKeyComparison != 0){
return objectKeyComparison;
}
return o1.getValue().compareTo(o2.getValue());
}
};
Collections.sort(actual, comparator);
Collections.sort(rows, comparator);
Assert.assertEquals(rows, actual);
}catch(Exception e){
throw new IllegalStateException("Unable to verify resultSet", e);
}
}
public void assertQueryResultSet(final String query, final List<DBQueries.Row<Integer, String>> rows, final ConnectionManager connectionManager) throws SQLException {
Connection connection = null;
Statement statement = null;
try{
connection = connectionManager.getConnection(null, noQueryOptions());
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
assertResultSetOrderAgnostic(resultSet, rows);
}catch(Exception e){
throw new IllegalStateException("Unable to verify resultSet", e);
}finally {
DBUtils.closeQuietly(connection);
DBUtils.closeQuietly(statement);
}
}
} | 29,122 | 38.839945 | 170 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/sqlite/support/DBUtilsTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.sqlite.support;
import org.junit.Assert;
import org.junit.Test;
import java.io.Closeable;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Calendar;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link DBUtils}
*
* @author Silvano Riz
*/
public class DBUtilsTest {
@Test
public void testWrapConnectionInCloseable() throws Exception {
ResultSet resultSet = mock(ResultSet.class);
Closeable closeable = DBUtils.wrapAsCloseable(resultSet);
closeable.close();
verify(resultSet, times(1)).close();
}
@Test
public void testCloseResultSetQuietly() throws Exception {
Statement statement = mock(Statement.class);
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getStatement()).thenReturn(statement);
DBUtils.closeQuietly(resultSet);
verify(resultSet, times(1)).close();
verify(statement, times(1)).close();
}
@Test
public void testCloseResultSetQuietly_NullStatement() throws Exception {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getStatement()).thenReturn(null);
DBUtils.closeQuietly(resultSet);
verify(resultSet, times(1)).close();
}
@Test
public void testCloseResultSetQuietly_Null() throws Exception {
ResultSet resultSet = null;
DBUtils.closeQuietly(resultSet);
}
@Test
public void testCloseResultSetQuietly_ResultSetCloseException() throws Exception {
Statement statement = mock(Statement.class);
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getStatement()).thenReturn(statement);
doThrow(new SQLException("SQL Exception")).when(resultSet).close();
DBUtils.closeQuietly(resultSet);
verify(resultSet, times(1)).close();
verify(statement, times(1)).close();
}
@Test
public void testCloseResultSetQuietly_StatementCloseException() throws Exception {
Statement statement = mock(Statement.class);
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getStatement()).thenReturn(statement);
doThrow(new SQLException("SQL Exception")).when(statement).close();
DBUtils.closeQuietly(resultSet);
verify(resultSet, times(1)).close();
verify(statement, times(1)).close();
}
@Test
public void testCloseStatementQuietly() throws Exception {
Statement statement = mock(Statement.class);
DBUtils.closeQuietly(statement);
verify(statement, times(1)).close();
}
@Test
public void testCloseStatementQuietly_Null() throws Exception {
Statement statement = null;
DBUtils.closeQuietly(statement);
}
@Test
public void testCloseStatementQuietly_Exception() throws Exception {
Statement statement = mock(Statement.class);
doThrow(new SQLException("SQL Exception")).when(statement).close();
DBUtils.closeQuietly(statement);
verify(statement, times(1)).close();
}
@Test
public void testCloseConnectionQuietly() throws Exception {
Connection connection = mock(Connection.class);
DBUtils.closeQuietly(connection);
verify(connection, times(1)).close();
}
@Test
public void testCloseConnectionQuietly_Null() throws Exception {
Connection connection = null;
DBUtils.closeQuietly(connection);
}
@Test
public void testCloseConnectionQuietly_Exception() throws Exception {
Connection connection = mock(Connection.class);
doThrow(new SQLException("SQL Exception")).when(connection).close();
DBUtils.closeQuietly(connection);
verify(connection, times(1)).close();
}
@Test
public void testGetDBTypeForClass() throws Exception {
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Integer.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Long.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Short.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Boolean.class));
Assert.assertEquals("REAL", DBUtils.getDBTypeForClass(Float.class));
Assert.assertEquals("REAL", DBUtils.getDBTypeForClass(Double.class));
Assert.assertEquals("TEXT", DBUtils.getDBTypeForClass(String.class));
Assert.assertEquals("TEXT", DBUtils.getDBTypeForClass(CharSequence.class));
Assert.assertEquals("TEXT", DBUtils.getDBTypeForClass(BigDecimal.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(java.util.Date.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(java.sql.Date.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Time.class));
Assert.assertEquals("INTEGER", DBUtils.getDBTypeForClass(Timestamp.class));
Assert.assertEquals("BLOB", DBUtils.getDBTypeForClass(byte[].class));
}
@Test(expected = IllegalStateException.class)
public void testGetDBTypeForClass_UnsupportedType() throws Exception {
DBUtils.getDBTypeForClass(Calendar.class);
}
@Test
public void testSetValueToPreparedStatement() throws Exception {
PreparedStatement statement = mock(PreparedStatement.class);
// Date / Time
final long now = System.currentTimeMillis();
DBUtils.setValueToPreparedStatement(1,statement, new java.util.Date(now));
verify(statement).setLong(1, now);
DBUtils.setValueToPreparedStatement(2,statement, new java.sql.Date(now));
verify(statement).setLong(2, now);
DBUtils.setValueToPreparedStatement(3,statement, new Time(now));
verify(statement).setLong(3, now);
DBUtils.setValueToPreparedStatement(4,statement, new Timestamp(now));
verify(statement).setLong(4, now);
// String and CharSequence
final String str = "This is a string";
final StringBuilder stringBuilder = new StringBuilder("This is a CharSequence");
DBUtils.setValueToPreparedStatement(5,statement, str);
verify(statement).setString(5, "This is a string");
DBUtils.setValueToPreparedStatement(6,statement, stringBuilder);
verify(statement).setString(6, "This is a CharSequence");
// Others...use setObject
DBUtils.setValueToPreparedStatement(7,statement, Boolean.FALSE);
verify(statement).setObject(7, Boolean.FALSE);
DBUtils.setValueToPreparedStatement(7,statement, Long.MAX_VALUE);
verify(statement).setObject(7, Long.MAX_VALUE);
DBUtils.setValueToPreparedStatement(8,statement, "bytes".getBytes());
verify(statement).setObject(8, "bytes".getBytes());
}
@Test
public void testGetValueFromResultSet() throws Exception{
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getInt(1)).thenReturn(Integer.MAX_VALUE);
DBUtils.getValueFromResultSet(1, resultSet, Integer.class);
verify(resultSet, times(1)).getInt(1);
when(resultSet.getLong(2)).thenReturn(Long.MAX_VALUE);
DBUtils.getValueFromResultSet(2, resultSet, Long.class);
verify(resultSet, times(1)).getLong(2);
when(resultSet.getShort(3)).thenReturn(Short.MAX_VALUE);
DBUtils.getValueFromResultSet(3, resultSet, Short.class);
verify(resultSet, times(1)).getShort(3);
when(resultSet.getBoolean(4)).thenReturn(Boolean.FALSE);
DBUtils.getValueFromResultSet(4, resultSet, Boolean.class);
verify(resultSet, times(1)).getBoolean(4);
when(resultSet.getFloat(5)).thenReturn(Float.MAX_VALUE);
DBUtils.getValueFromResultSet(5, resultSet, Float.class);
verify(resultSet, times(1)).getFloat(5);
when(resultSet.getDouble(6)).thenReturn(Double.MAX_VALUE);
DBUtils.getValueFromResultSet(6, resultSet, Double.class);
verify(resultSet, times(1)).getDouble(6);
when(resultSet.getString(7)).thenReturn("7 string");
DBUtils.getValueFromResultSet(7, resultSet, String.class);
verify(resultSet, times(1)).getString(7);
when(resultSet.getString(8)).thenReturn("8 CharSequence");
DBUtils.getValueFromResultSet(8, resultSet, CharSequence.class);
verify(resultSet, times(1)).getString(8);
when(resultSet.getBigDecimal(9)).thenReturn(new BigDecimal("1"));
DBUtils.getValueFromResultSet(9, resultSet, BigDecimal.class);
verify(resultSet, times(1)).getBigDecimal(9);
final long now = System.currentTimeMillis();
when(resultSet.getLong(10)).thenReturn(now);
DBUtils.getValueFromResultSet(10, resultSet, java.util.Date.class);
verify(resultSet, times(1)).getLong(10);
when(resultSet.getLong(11)).thenReturn(now);
DBUtils.getValueFromResultSet(11, resultSet, java.sql.Date.class);
verify(resultSet, times(1)).getLong(11);
when(resultSet.getLong(12)).thenReturn(now);
DBUtils.getValueFromResultSet(12, resultSet, Time.class);
verify(resultSet, times(1)).getLong(12);
when(resultSet.getLong(13)).thenReturn(now);
DBUtils.getValueFromResultSet(13, resultSet, Timestamp.class);
verify(resultSet, times(1)).getLong(13);
when(resultSet.getBytes(14)).thenReturn("bytes".getBytes());
DBUtils.getValueFromResultSet(14, resultSet, byte[].class);
verify(resultSet, times(1)).getBytes(14);
}
} | 10,148 | 35.117438 | 88 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/navigable/NavigableIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.navigable;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.support.KeyStatistics;
import com.googlecode.cqengine.index.support.KeyStatisticsIndex;
import com.googlecode.cqengine.index.support.SortedKeyStatisticsIndex;
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 com.googlecode.cqengine.testutil.CarFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.testutil.TestUtil.setOf;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class NavigableIndexTest {
@Test
public void testGetDistinctKeysAndCounts() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
SortedKeyStatisticsIndex<String, Car> MODEL_INDEX = NavigableIndex.onAttribute(Car.MODEL);
collection.addIndex(MODEL_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Set<String> distinctModels = setOf(MODEL_INDEX.getDistinctKeys(noQueryOptions()));
assertEquals(asList("Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius", "Taurus"), new ArrayList<String>(distinctModels));
for (String model : distinctModels) {
assertEquals(Integer.valueOf(2), MODEL_INDEX.getCountForKey(model, noQueryOptions()));
}
Set<String> distinctModelsDescending = setOf(MODEL_INDEX.getDistinctKeysDescending(noQueryOptions()));
assertEquals(asList("Taurus", "Prius", "M6", "Insight", "Hilux", "Fusion", "Focus", "Civic", "Avensis", "Accord"), new ArrayList<String>(distinctModelsDescending));
}
@Test
public void testGetCountOfDistinctKeys(){
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
KeyStatisticsIndex<String, Car> MANUFACTURER_INDEX = NavigableIndex.onAttribute(Car.MANUFACTURER);
collection.addIndex(MANUFACTURER_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Assert.assertEquals(Integer.valueOf(4), MANUFACTURER_INDEX.getCountOfDistinctKeys(noQueryOptions()));
}
@Test
public void testGetStatisticsForDistinctKeys(){
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
KeyStatisticsIndex<String, Car> MANUFACTURER_INDEX = NavigableIndex.onAttribute(Car.MANUFACTURER);
collection.addIndex(MANUFACTURER_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Set<KeyStatistics<String>> keyStatistics = setOf(MANUFACTURER_INDEX.getStatisticsForDistinctKeys(noQueryOptions()));
Assert.assertEquals(setOf(
new KeyStatistics<String>("Ford", 6),
new KeyStatistics<String>("Honda", 6),
new KeyStatistics<String>("Toyota", 6),
new KeyStatistics<String>("BMW", 2)
),
keyStatistics);
}
@Test
public void testGetStatisticsForDistinctKeysDescending(){
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
SortedKeyStatisticsIndex<String, Car> MANUFACTURER_INDEX = NavigableIndex.onAttribute(Car.MANUFACTURER);
collection.addIndex(MANUFACTURER_INDEX);
collection.addAll(CarFactory.createCollectionOfCars(20));
Set<KeyStatistics<String>> keyStatistics = setOf(MANUFACTURER_INDEX.getStatisticsForDistinctKeysDescending(noQueryOptions()));
Assert.assertEquals(setOf(
new KeyStatistics<String>("Toyota", 6),
new KeyStatistics<String>("Honda", 6),
new KeyStatistics<String>("Ford", 6),
new KeyStatistics<String>("BMW", 2)
),
keyStatistics);
}
@Test
public void testIndexQuantization_SpanningTwoBucketsMidRange() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
// Merge cost should be 20 because this query spans 2 buckets (each containing 10 objects)...
assertEquals(20, collection.retrieve(between(Car.CAR_ID, 47, 53)).getMergeCost());
// 7 objects match the query (between is inclusive)...
assertEquals(7, collection.retrieve(between(Car.CAR_ID, 47, 53)).size());
// The matching objects are...
List<Integer> carIdsFound = retrieveCarIds(collection, between(Car.CAR_ID, 47, 53));
assertEquals(asList(47, 48, 49, 50, 51, 52, 53), carIdsFound);
}
@Test
public void testIndexQuantization_FirstBucket() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
// Merge cost should be 10, because objects matching this query are in a single bucket...
assertEquals(10, collection.retrieve(between(Car.CAR_ID, 2, 4)).getMergeCost());
// 3 objects match the query...
assertEquals(3, collection.retrieve(between(Car.CAR_ID, 2, 4)).size());
List<Integer> carIdsFound = retrieveCarIds(collection, between(Car.CAR_ID, 2, 4));
assertEquals(asList(2, 3, 4), carIdsFound);
}
@Test
public void testIndexQuantization_LastBucket() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
// Merge cost should be 10, because objects matching this query are in a single bucket...
assertEquals(10, collection.retrieve(between(Car.CAR_ID, 96, 98)).getMergeCost());
// 3 objects match the query...
assertEquals(3, collection.retrieve(between(Car.CAR_ID, 96, 98)).size());
List<Integer> carIdsFound = retrieveCarIds(collection, between(Car.CAR_ID, 96, 98));
assertEquals(asList(96, 97, 98), carIdsFound);
}
@Test
public void testIndexQuantization_LessThan() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
assertEquals(5, collection.retrieve(lessThan(Car.CAR_ID, 5)).size());
assertEquals(15, collection.retrieve(lessThan(Car.CAR_ID, 15)).size());
assertEquals(6, collection.retrieve(lessThanOrEqualTo(Car.CAR_ID, 5)).size());
assertEquals(16, collection.retrieve(lessThanOrEqualTo(Car.CAR_ID, 15)).size());
}
@Test
public void testIndexQuantization_GreaterThan() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
assertEquals(4, collection.retrieve(greaterThan(Car.CAR_ID, 95)).size());
assertEquals(14, collection.retrieve(greaterThan(Car.CAR_ID, 85)).size());
assertEquals(5, collection.retrieve(greaterThanOrEqualTo(Car.CAR_ID, 95)).size());
assertEquals(15, collection.retrieve(greaterThanOrEqualTo(Car.CAR_ID, 85)).size());
}
@Test
public void testIndexQuantization_Between() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
Query<Car> query = between(Car.CAR_ID, 88, 92);
assertEquals(5, collection.retrieve(query).size());
assertEquals(asList(88, 89, 90, 91, 92), retrieveCarIds(collection, query));
query = between(Car.CAR_ID, 88, true, 92, true);
assertEquals(5, collection.retrieve(query).size());
assertEquals(asList(88, 89, 90, 91, 92), retrieveCarIds(collection, query));
query = between(Car.CAR_ID, 88, false, 92, true);
assertEquals(4, collection.retrieve(query).size());
assertEquals(asList(89, 90, 91, 92), retrieveCarIds(collection, query));
query = between(Car.CAR_ID, 88, true, 92, false);
assertEquals(4, collection.retrieve(query).size());
assertEquals(asList(88, 89, 90, 91), retrieveCarIds(collection, query));
query = between(Car.CAR_ID, 88, false, 92, false);
assertEquals(3, collection.retrieve(query).size());
assertEquals(asList(89, 90, 91), retrieveCarIds(collection, query));
}
@Test
public void testIndexQuantization_ComplexQuery() {
IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>();
collection.addIndex(NavigableIndex.withQuantizerOnAttribute(IntegerQuantizer.withCompressionFactor(10), Car.CAR_ID));
collection.addAll(CarFactory.createCollectionOfCars(100));
Query<Car> query = and(between(Car.CAR_ID, 96, 98), greaterThan(Car.CAR_ID, 95));
// Merge cost should be 10, because objects matching this query are in a single bucket...
assertEquals(10, collection.retrieve(query).getMergeCost());
// 3 objects match the query...
assertEquals(3, collection.retrieve(query).size());
List<Integer> carIdsFound = retrieveCarIds(collection, query);
assertEquals(asList(96, 97, 98), carIdsFound);
}
static List<Integer> retrieveCarIds(IndexedCollection<Car> collection, Query<Car> query) {
ResultSet<Car> cars = collection.retrieve(query, queryOptions(orderBy(ascending(Car.CAR_ID))));
List<Integer> carIds = new ArrayList<Integer>();
for (Car car : cars) {
carIds.add(car.getCarId());
}
return carIds;
}
}
| 11,258 | 46.707627 | 172 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/suffix/SuffixTreeIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.suffix;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.SmartArrayBasedNodeFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link SuffixTreeIndex}.
*
* Created by npgall on 13/05/2016.
*/
public class SuffixTreeIndexTest {
@Test
public void testNodeFactory() {
SuffixTreeIndex<String, Car> index1 = SuffixTreeIndex.onAttribute(Car.MANUFACTURER);
SuffixTreeIndex<String, Car> index2 = SuffixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new DefaultCharArrayNodeFactory());
SuffixTreeIndex<String, Car> index3 = SuffixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new SmartArrayBasedNodeFactory());
assertTrue(index1.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index2.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index3.nodeFactory instanceof SmartArrayBasedNodeFactory);
}
} | 1,728 | 40.166667 | 143 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/support/PartialIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.index.AttributeIndex;
import com.googlecode.cqengine.index.disk.PartialDiskIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.navigable.PartialNavigableIndex;
import com.googlecode.cqengine.index.offheap.PartialOffHeapIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.testutil.Car;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
import org.mockito.Mockito;
import static com.googlecode.cqengine.index.support.PartialIndex.supportsQueryInternal;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
/**
* Tests for {@link PartialIndex}.
*
* @author niall.gallagher
*/
public class PartialIndexTest {
@Test
public void testEqualsAndHashCode_PartialNavigableIndex() {
EqualsVerifier.forClass(PartialNavigableIndex.class)
.withNonnullFields("filterQuery", "attribute", "backingIndex")
.withIgnoredFields("attribute", "indexMapFactory", "valueSetFactory")
.suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS)
.verify();
}
@Test
public void testEqualsAndHashCode_PartialDiskIndex() {
EqualsVerifier.forClass(PartialDiskIndex.class)
.withNonnullFields("filterQuery", "attribute", "backingIndex")
.withIgnoredFields("attribute", "tableNameSuffix")
.suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS)
.verify();
}
@Test
public void testEqualsAndHashCode_PartialOffHeapIndex() {
EqualsVerifier.forClass(PartialOffHeapIndex.class)
.withNonnullFields("filterQuery", "attribute", "backingIndex")
.withIgnoredFields("attribute", "tableNameSuffix")
.suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS)
.verify();
}
@Test
public void testGetterMethods() {
PartialIndex partialIndex = PartialNavigableIndex.onAttributeWithFilterQuery(Car.MANUFACTURER, between(Car.CAR_ID, 2, 5));
assertEquals(Car.MANUFACTURER, partialIndex.getAttribute());
assertEquals(between(Car.CAR_ID, 2, 5), partialIndex.getFilterQuery());
assertFalse(partialIndex.isQuantized());
assertTrue(partialIndex.getBackingIndex() instanceof NavigableIndex);
assertTrue(partialIndex.getEffectiveIndex() == partialIndex);
assertTrue(partialIndex.getBackingIndex().getEffectiveIndex() == partialIndex);
}
@Test
public void testClear() {
AttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialIndex<Integer, Car, AttributeIndex<Integer, Car>> index = wrapWithPartialIndex(backingIndex);
index.clear(noQueryOptions());
verify(backingIndex, times(1)).clear(noQueryOptions());
}
@Test
public <O> void testSupportsQuery_Positive_RootQueryEqualsFilterQuery() {
// A partial index on attribute Car.MANUFACTURER, which is filtered to only index Ford and Honda cars.
assertTrue(supportsQueryInternal(
backingIndexSupportsQuery(in(Car.MANUFACTURER, "Ford", "Honda")),
in(Car.MANUFACTURER, "Ford", "Honda"),
in(Car.MANUFACTURER, "Ford", "Honda"),
in(Car.MANUFACTURER, "Ford", "Honda"),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Positive_RootQueryIsAnAndQueryWithFilterQueryAsChild() {
// A partial index on attribute Car.PRICE, which is filtered to only index Ford and Honda cars.
assertTrue(supportsQueryInternal(
backingIndexSupportsQuery(lessThan(Car.PRICE, 5000.0)),
in(Car.MANUFACTURER, "Ford", "Honda"),
and(lessThan(Car.PRICE, 5000.0), in(Car.MANUFACTURER, "Ford", "Honda")),
lessThan(Car.PRICE, 5000.0),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Positive_RootAndFilterQueriesAreBothAndQueriesAndChildrenOfFilterQueryAreChildrenOfRootQuery() {
// A partial index on attribute Car.PRICE, which is filtered to only index "Blue" Ford and Honda cars.
assertTrue(supportsQueryInternal(
backingIndexSupportsQuery(lessThan(Car.PRICE, 5000.0)),
and(in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.BLUE)),
and(lessThan(Car.PRICE, 5000.0), in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.BLUE)),
lessThan(Car.PRICE, 5000.0),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Negative_BackingIndexDoesNotSupportQuery() {
assertFalse(supportsQueryInternal(
backingIndexSupportsQuery(in(Car.MODEL, "Focus", "Civic")),
in(Car.MANUFACTURER, "Ford", "Honda"),
in(Car.MANUFACTURER, "Ford", "Honda"),
in(Car.MANUFACTURER, "Ford", "Honda"),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Negative_RootQueryDoesNotEqualFilterQueryAndRootQueryIsNotAnAndQuery() {
assertFalse(supportsQueryInternal(
backingIndexSupportsQuery(in(Car.MANUFACTURER, "Ford", "Honda")),
or(in(Car.MANUFACTURER, "Ford", "Honda"), in(Car.MODEL, "Focus", "Civic")),
in(Car.MANUFACTURER, "Ford", "Honda"),
in(Car.MANUFACTURER, "Ford", "Honda"),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Negative_RootQueryDoesNotEqualFilterQueryAndFilterQueryIsNotAnAndQuery() {
assertFalse(supportsQueryInternal(
backingIndexSupportsQuery(lessThan(Car.PRICE, 5000.0)),
or(in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.BLUE)),
and(lessThan(Car.PRICE, 5000.0), in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.BLUE)),
lessThan(Car.PRICE, 5000.0),
noQueryOptions()
));
}
@Test
public <O> void testSupportsQuery_Negative_RootAndQueryDoesNotContainChildrenOfAndFilterQuery() {
assertFalse(supportsQueryInternal(
backingIndexSupportsQuery(lessThan(Car.PRICE, 5000.0)),
and(in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.BLUE)),
and(lessThan(Car.PRICE, 5000.0), in(Car.MANUFACTURER, "Ford", "Honda"), equal(Car.COLOR, Car.Color.RED)),
lessThan(Car.PRICE, 5000.0),
noQueryOptions()
));
}
static PartialIndex<Integer, Car, AttributeIndex<Integer, Car>> wrapWithPartialIndex(final AttributeIndex<Integer, Car> mockedBackingIndex) {
return new PartialIndex<Integer, Car, AttributeIndex<Integer, Car>>(Car.CAR_ID, in(Car.MANUFACTURER, "Ford", "Honda")) {
@Override
protected AttributeIndex<Integer, Car> createBackingIndex() {
return mockedBackingIndex;
}
};
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() {
return mock(SortedKeyStatisticsAttributeIndex.class);
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndexSupportsQuery(Query<Car> querySupportedByBackingIndex) {
SortedKeyStatisticsAttributeIndex attributeIndex = mock(SortedKeyStatisticsAttributeIndex.class);
when(attributeIndex.supportsQuery(Mockito.eq(querySupportedByBackingIndex), Mockito.<QueryOptions>any())).thenReturn(true);
return attributeIndex;
}
} | 8,688 | 44.255208 | 145 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/support/PartialSortedKeyStatisticsAttributeIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.mockito.Mockito.*;
/**
* Tests for {@link PartialSortedKeyStatisticsAttributeIndex}.
*
* @author niall.gallagher
*/
public class PartialSortedKeyStatisticsAttributeIndexTest {
@Test
public void testGetDistinctKeys1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(noQueryOptions());
}
@Test
public void testGetDistinctKeys2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeysDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValues1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(noQueryOptions());
}
@Test
public void testGetKeysAndValues2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetCountForKey() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountForKey(1, noQueryOptions());
verify(backingIndex, times(1)).getCountForKey(1, noQueryOptions());
}
@Test
public void testGetCountOfDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountOfDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getCountOfDistinctKeys(noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeys(noQueryOptions());
}
static PartialSortedKeyStatisticsAttributeIndex<Integer, Car> wrapWithPartialIndex(final SortedKeyStatisticsAttributeIndex<Integer, Car> mockedBackingIndex) {
return new PartialSortedKeyStatisticsAttributeIndex<Integer, Car>(Car.CAR_ID, QueryFactory.between(Car.CAR_ID, 2, 5)) {
@Override
protected SortedKeyStatisticsAttributeIndex<Integer, Car> createBackingIndex() {
return mockedBackingIndex;
}
};
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() {
return mock(SortedKeyStatisticsAttributeIndex.class);
}
} | 6,673 | 42.620915 | 162 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/support/UnmodifiableNavigableSetTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.*;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.util.*;
/**
* Unit tests for {@link UnmodifiableNavigableSet}.
* <p/>
* Uses guava-testlib to validate compliance.
*
* @author Niall Gallagher
*/
public class UnmodifiableNavigableSetTest extends TestCase {
public static junit.framework.Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(NavigableSetTestSuiteBuilder.using(testStringSetGenerator())
.named("UnmodifiableNavigableSetAPICompliance")
.withFeatures(CollectionSize.SEVERAL, CollectionFeature.KNOWN_ORDER)
.createTestSuite());
suite.addTestSuite(UnmodifiableNavigableSetTest.class);
return suite;
}
static TestStringSortedSetGenerator testStringSetGenerator() {
return new TestStringSortedSetGenerator() {
@Override protected SortedSet<String> create(String[] elements) {
return new UnmodifiableNavigableSet<String>(new TreeSet<String>(Arrays.asList(elements)));
}
@Override
public List<String> order(List<String> insertionOrder) {
return Ordering.natural().sortedCopy(insertionOrder);
}
};
}
@SuppressWarnings("EmptyCatchBlock")
public void testUnmodifiability() {
TreeSet<Integer> mod = Sets.newTreeSet();
mod.add(1);
mod.add(2);
mod.add(3);
NavigableSet<Integer> unmod = new UnmodifiableNavigableSet<Integer>(mod);
mod.add(4);
assertTrue(unmod.contains(4));
assertTrue(unmod.descendingSet().contains(4));
ensureNotDirectlyModifiable(unmod);
ensureNotDirectlyModifiable(unmod.descendingSet());
ensureNotDirectlyModifiable(unmod.headSet(2));
ensureNotDirectlyModifiable(unmod.headSet(2, true));
ensureNotDirectlyModifiable(unmod.tailSet(2));
ensureNotDirectlyModifiable(unmod.tailSet(2, true));
ensureNotDirectlyModifiable(unmod.subSet(1, 3));
ensureNotDirectlyModifiable(unmod.subSet(1, true, 3, true));
NavigableSet<Integer> reverse = unmod.descendingSet();
try {
reverse.add(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
reverse.addAll(Collections.singleton(4));
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
reverse.remove(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
}
@SuppressWarnings("EmptyCatchBlock")
static void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) {
try {
unmod.add(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.remove(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.addAll(Collections.singleton(4));
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
Iterator<Integer> iterator = unmod.iterator();
iterator.next();
iterator.remove();
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
}
@SuppressWarnings("EmptyCatchBlock")
static void ensureNotDirectlyModifiable(NavigableSet<Integer> unmod) {
try {
unmod.add(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.remove(4);
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.addAll(Collections.singleton(4));
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.pollFirst();
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
unmod.pollLast();
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
Iterator<Integer> iterator = unmod.iterator();
iterator.next();
iterator.remove();
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
try {
Iterator<Integer> iterator = unmod.descendingIterator();
iterator.next();
iterator.remove();
fail("UnsupportedOperationException expected");
} catch (UnsupportedOperationException expected) {
}
}
} | 6,097 | 35.297619 | 106 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/radixreversed/ReversedRadixTreeIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.radixreversed;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.SmartArrayBasedNodeFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for {@link ReversedRadixTreeIndex}.
*
* Created by npgall on 13/05/2016.
*/
public class ReversedRadixTreeIndexTest {
@Test
public void testNodeFactory() {
ReversedRadixTreeIndex<String, Car> index1 = ReversedRadixTreeIndex.onAttribute(Car.MANUFACTURER);
ReversedRadixTreeIndex<String, Car> index2 = ReversedRadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new DefaultCharArrayNodeFactory());
ReversedRadixTreeIndex<String, Car> index3 = ReversedRadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new SmartArrayBasedNodeFactory());
assertTrue(index1.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index2.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index3.nodeFactory instanceof SmartArrayBasedNodeFactory);
}
} | 1,782 | 41.452381 | 157 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/radix/RadixTreeIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.radix;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory;
import com.googlecode.concurrenttrees.radix.node.concrete.SmartArrayBasedNodeFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for {@link RadixTreeIndex}.
*
* Created by npgall on 13/05/2016.
*/
public class RadixTreeIndexTest {
@Test
public void testNodeFactory() {
RadixTreeIndex<String, Car> index1 = RadixTreeIndex.onAttribute(Car.MANUFACTURER);
RadixTreeIndex<String, Car> index2 = RadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new DefaultCharArrayNodeFactory());
RadixTreeIndex<String, Car> index3 = RadixTreeIndex.onAttributeUsingNodeFactory(Car.MANUFACTURER, new SmartArrayBasedNodeFactory());
assertTrue(index1.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index2.nodeFactory instanceof DefaultCharArrayNodeFactory);
assertTrue(index3.nodeFactory instanceof SmartArrayBasedNodeFactory);
}
} | 1,710 | 39.738095 | 141 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/index/unique/UniqueIndexTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.unique;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* @author Niall Gallagher
*/
public class UniqueIndexTest {
@Test
public void testUniqueIndex() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add some indexes...
cars.addIndex(UniqueIndex.onAttribute(Car.CAR_ID));
cars.addIndex(HashIndex.onAttribute(Car.CAR_ID));
// 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, "ford taurus", "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")));
Query<Car> query = equal(Car.CAR_ID, 2);
ResultSet<Car> rs = cars.retrieve(query);
Assert.assertEquals("should prefer unique index over hash index", UniqueIndex.INDEX_RETRIEVAL_COST, rs.getRetrievalCost());
Assert.assertEquals("should retrieve car 2", 2, rs.uniqueResult().carId);
}
@Test(expected = UniqueIndex.UniqueConstraintViolatedException.class)
public void testDuplicateObjectDetection_SimpleAttribute() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add some indexes...
cars.addIndex(UniqueIndex.onAttribute(Car.CAR_ID));
// 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, "ford taurus", "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")));
cars.add(new Car(2, "some other car", "foo", Arrays.asList("bar")));
}
@Test(expected = UniqueIndex.UniqueConstraintViolatedException.class)
public void testDuplicateObjectDetection_MultiValueAttribute() {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add some indexes...
cars.addIndex(UniqueIndex.onAttribute(Car.FEATURES));
// Add some objects to the collection...
cars.add(new Car(1, "ford focus", "foo", Arrays.asList("spare tyre", "sunroof")));
cars.add(new Car(2, "ford taurus", "bar", Arrays.asList("radio", "cd player")));
// Try to add another car which has a cd player, when one car already has a cd player...
cars.add(new Car(3, "honda civic", "baz", Arrays.asList("cd player", "bluetooth")));
}
}
| 3,684 | 41.356322 | 131 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/entity/RegularMapTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.entity;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
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.*;
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 using Map as collection element - indexes, query engine, ordering results.
*
* @author Niall Gallagher
*/
public class RegularMapTest {
private static final Attribute<Map, String> MODEL = mapAttribute("MODEL", String.class);
private static final Attribute<Map, Integer> DOORS = mapAttribute("DOORS", Integer.class);
private static final Attribute<Map, Car.Color> COLOR = mapAttribute("COLOR",Car.Color.class);
private static final Attribute<Map, String> MANUFACTURER = mapAttribute("MANUFACTURER", String.class);
private static final Attribute<Map, Double> PRICE = mapAttribute("PRICE", Double.class);
private static final Attribute<Map, Integer> CAR_ID = mapAttribute("CAR_ID", Integer.class);
@Test
public void testMapFunctionality() {
IndexedCollection<Map> cars = new ConcurrentIndexedCollection<Map>();
cars.addIndex(HashIndex.onAttribute(COLOR));
cars.addIndex(NavigableIndex.onAttribute(DOORS));
cars.addIndex(RadixTreeIndex.onAttribute(MODEL));
cars.addIndex(ReversedRadixTreeIndex.onAttribute(MODEL));
cars.addIndex(InvertedRadixTreeIndex.onAttribute(MODEL));
cars.addIndex(SuffixTreeIndex.onAttribute(MODEL));
cars.add(buildNewCar(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Collections.<String>emptyList()));
cars.add(buildNewCar(2, "Ford", "Fiesta", Car.Color.BLUE, 2, 5000.00, Collections.<String>emptyList()));
cars.add(buildNewCar(3, "Ford", "F-150", Car.Color.RED, 2, 9500.00, Collections.<String>emptyList()));
cars.add(buildNewCar(4, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Collections.<String>emptyList()));
cars.add(buildNewCar(5, "Toyota", "Prius", Car.Color.BLACK, 3, 9700.00, Collections.<String>emptyList()));
// Ford cars...
assertThat(carIdsIn(cars.retrieve(equal(MANUFACTURER, "Ford"))), is(setOf(1, 2, 3)));
// 3-door cars...
assertThat(carIdsIn(cars.retrieve(equal(DOORS, 3))), is(setOf(5)));
// 2 or 3-door cars...
assertThat(carIdsIn(cars.retrieve(between(DOORS, 2, 3))), is(setOf(2, 3, 5)));
// 2 or 5-door cars...
assertThat(carIdsIn(cars.retrieve(in(DOORS, 2, 5))), is(setOf(1, 2, 3, 4)));
// Blue Ford cars...
assertThat(carIdsIn(cars.retrieve(and(equal(COLOR, Car.Color.BLUE),
equal(MANUFACTURER, "Ford")))), is(setOf(1, 2)));
// NOT 3-door cars...
assertThat(carIdsIn(cars.retrieve(not(equal(DOORS, 3)))),
is(setOf(1, 2, 3, 4)));
// Cars which have 5 doors and which are not red...
assertThat(carIdsIn(cars.retrieve(and(equal(DOORS, 5), not(equal(COLOR, Car.Color.RED))))), is(setOf(1)));
// Cars whose model starts with 'F'...
assertThat(carIdsIn(cars.retrieve(startsWith(MODEL, "F"))), is(setOf(1, 2, 3)));
// Cars whose model ends with 's'...
assertThat(carIdsIn(cars.retrieve(endsWith(MODEL, "s"))), is(setOf(1, 5)));
// Cars whose model contains 'i'...
assertThat(carIdsIn(cars.retrieve(contains(MODEL, "i"))), is(setOf(2, 4, 5)));
// Cars whose model is contained in 'Banana, Focus, Civic, Foobar'...
assertThat(carIdsIn(cars.retrieve(isContainedIn(MODEL, "Banana, Focus, Civic, Foobar"))), is(setOf(1, 4)));
// NOT 3-door cars, sorted by doors ascending...
assertThat(
carIdsIn(cars.retrieve(not(equal(DOORS, 3)), queryOptions(orderBy(ascending(DOORS), ascending(MODEL))))).toString(),
is(equalTo(setOf(3, 2, 4, 1).toString()))
);
// NOT 3-door cars, sorted by doors ascending then price descending...
assertThat(
carIdsIn(
cars.retrieve(
not(equal(DOORS, 3)),
queryOptions(
orderBy(ascending(DOORS),
descending(PRICE))
)
)
),
is(equalTo(setOf(3, 2, 1, 4)))
);
}
static Set<Integer> carIdsIn(ResultSet<Map> resultSet) {
return valuesOf(CAR_ID, resultSet);
}
protected Map buildNewCar(int carId, String manufacturer, String model, Car.Color color, int doors, double price, List<String> features) {
return createMap(carId, manufacturer, model, color, doors, price, features);
}
@SuppressWarnings("unchecked")
protected Map createMap(int carId, String manufacturer, String model, Car.Color color, int doors, double price, List<String> features) {
Map map = new HashMap();
map.put("CAR_ID", carId);
map.put("MANUFACTURER", manufacturer);
map.put("MODEL", model);
map.put("COLOR", color);
map.put("DOORS", doors);
map.put("PRICE", price);
map.put("FEATURES", features);
return map;
}
}
| 6,692 | 43.62 | 142 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/entity/MapEntityTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.entity;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.mapEntity;
/**
* Validates general functionality using MapEntity as collection element - indexes, query engine, ordering results.
*
* @author Niall Gallagher
*/
public class MapEntityTest extends RegularMapTest {
@Test
public void testMapFunctionality() {
super.testMapFunctionality();
}
protected Map buildNewCar(int carId, String manufacturer, String model, Car.Color color, int doors, double price, List<String> features) {
return mapEntity(createMap(carId, manufacturer, model, color, doors, price, features));
}
}
| 1,381 | 30.409091 | 142 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/entity/PrimaryKeyedMapEntityTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.entity;
import com.googlecode.cqengine.testutil.Car;
import java.util.List;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.primaryKeyedMapEntity;
/**
* Validates general functionality using PrimaryKeyedMapEntity as collection element - indexes, query engine, ordering
* results.
*
* @author Niall Gallagher
*/
public class PrimaryKeyedMapEntityTest extends MapEntityTest {
@Override
public void testMapFunctionality() {
super.testMapFunctionality();
}
protected Map buildNewCar(int carId, String manufacturer, String model, Car.Color color, int doors, double price, List<String> features) {
return primaryKeyedMapEntity(createMap(carId, manufacturer, model, color, doors, price, features), "CAR_ID");
}
}
| 1,420 | 32.833333 | 142 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/nestedobjects/NestedObjectsExample.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.nestedobjects;
import com.google.common.base.Function;
import com.googlecode.cqengine.*;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.google.common.collect.Iterables.*;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
/**
* Demonstrates how to define attributes which read from nested objects,
* and to search the collection for objects whose nested objects match a query.
* <p/>
* In this example there are User, Order and Product objects.
* A User can have many Orders. An Order can have many Products. Each Product has a name.
* This example shows how to search for Users who have ordered a particular product, by specifying the product's name.
*/
public class NestedObjectsExample {
// For Java 8: A multi-value attribute which returns the names of products ordered by a user
// static final Attribute<User, String> PRODUCT_NAMES_ORDERED = new MultiValueAttribute<User, String>() {
// public Iterable<String> getValues(User user, QueryOptions queryOptions) {
// return user.orders.stream()
// .map(order -> order.products).flatMap(Collection::stream)
// .map(product -> product.name)::iterator;
// }
// };
// For Java 6: A multi-value attribute which returns the names of products ordered by a user
static final Attribute<User, String> PRODUCT_NAMES_ORDERED = new MultiValueAttribute<User, String>() {
public Iterable<String> getValues(User user, QueryOptions queryOptions) {
return concat(transform(user.orders, new Function<Order, Iterable<String>>() {
public Iterable<String> apply(Order order) {
return transform(order.products, new Function<Product, String>() {
public String apply(Product product) {
return product.name;
}
});
}
}));
}
};
public static void main(String[] args) {
Order order1 = new Order(asList(new Product("Diet Coke"), new Product("Snickers Bar")));
Order order2 = new Order(singletonList(new Product("Sprite")));
User user1 = new User(1, asList(order1, order2)); // userId 1
Order order3 = new Order(asList(new Product("Sprite"), new Product("Popcorn")));
User user2 = new User(2, singletonList(order3)); // userId 2
Order order4 = new Order(singletonList(new Product("Snickers Bar")));
User user3 = new User(3, singletonList(order4)); // userId 3
IndexedCollection<User> users = new ConcurrentIndexedCollection<User>();
users.addAll(asList(user1, user2, user3));
for (User user : users.retrieve(equal(PRODUCT_NAMES_ORDERED, "Snickers Bar"))) {
System.out.println(user.userId);
} // ...prints 1, 3
}
// ***** Domain objects... *****
static class User {
final long userId;
final List<Order> orders;
User(long userId, List<Order> orders) {
this.userId = userId;
this.orders = orders;
}
}
static class Order {
final List<Product> products;
Order(List<Product> products) {
this.products = products;
}
}
static class Product {
final String name;
Product(String name) {
this.name = name;
}
}
}
| 4,223 | 37.054054 | 118 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/dynamic/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.examples.dynamic;
/**
* @author Niall Gallagher
*/
public class Car {
public final Integer carId;
public final String manufacturer;
public final String model;
public final Integer doors;
public final Integer horsepower;
public Car(Integer carId, String manufacturer, String model, Integer doors, Integer horsepower) {
this.carId = carId;
this.manufacturer = manufacturer;
this.model = model;
this.doors = doors;
this.horsepower = horsepower;
}
@Override
public String toString() {
return "Car{" +
"carId=" + carId +
", manufacturer='" + manufacturer + '\'' +
", model='" + model + '\'' +
", doors=" + doors +
", horsepower=" + horsepower +
'}';
}
}
| 1,474 | 30.382979 | 101 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/dynamic/DynamicExample.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.dynamic;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* Demonstrates generating attributes on-the-fly using reflection for fields in a POJO, building indexes on those
* attributes on-the-fly, and then running queries against fields in the POJO.
*
* @author ngallagher
* @since 2013-07-05 11:54
*/
public class DynamicExample {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Generate attributes dynamically for fields in the given POJO...
Map<String, Attribute<Car, Comparable>> attributes = DynamicIndexer.generateAttributesForPojo(Car.class);
// Build indexes on the dynamically generated attributes...
IndexedCollection<Car> cars = DynamicIndexer.newAutoIndexedCollection(attributes.values());
// Add some objects to the collection...
cars.add(new Car(1, "ford", "focus", 4, 9000));
cars.add(new Car(2, "ford", "mondeo", 5, 10000));
cars.add(new Car(2, "ford", "fiesta", 3, 2000));
cars.add(new Car(3, "honda", "civic", 5, 11000));
Query<Car> query = and(
equal(attributes.get("manufacturer"), "ford"),
lessThan(attributes.get("doors"), value(5)),
greaterThan(attributes.get("horsepower"), value(3000))
);
ResultSet<Car> results = cars.retrieve(query);
System.out.println("Ford cars with less than 5 doors and horsepower greater than 3000:- ");
System.out.println("Using NavigableIndex: " + (results.getRetrievalCost() == 40));
for (Car car : results) {
System.out.println(car);
}
// Prints:
// Ford cars with less than 5 doors and horsepower greater than 3000:-
// Using NavigableIndex: true
// Car{carId=1, manufacturer='ford', model='focus', doors=4, horsepower=9000}
}
// This method is required for compatibility with Java 8 compiler (not required for Java 6 or 7 compiler)...
static Comparable value(Comparable c) {
return c;
}
}
| 2,929 | 38.066667 | 113 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/dynamic/DynamicIndexer.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.dynamic;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.ReflectiveAttribute;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Methods to generate attributes dynamically for fields in a POJO, and to create IndexedCollections
* configured dynamically to index these attributes.
* <p/>
* @author ngallagher
* @since 2013-07-05 12:43
*/
public class DynamicIndexer {
/**
* Generates attributes dynamically for the fields declared in the given POJO class.
* <p/>
* Implementation is currently limited to generating attributes for Comparable fields (String, Integer etc.).
*
* @param pojoClass A POJO class
* @param <O> Type of the POJO class
* @return Attributes for fields in the POJO
*/
public static <O> Map<String, Attribute<O, Comparable>> generateAttributesForPojo(Class<O> pojoClass) {
Map<String, Attribute<O, Comparable>> generatedAttributes = new LinkedHashMap<String, Attribute<O, Comparable>>();
for (Field field : pojoClass.getDeclaredFields()) {
if (Comparable.class.isAssignableFrom(field.getType())) {
@SuppressWarnings({"unchecked"})
Class<Comparable> fieldType = (Class<Comparable>) field.getType();
generatedAttributes.put(field.getName(), ReflectiveAttribute.forField(pojoClass, fieldType, field.getName()));
}
}
return generatedAttributes;
}
/**
* Creates an IndexedCollection and adds NavigableIndexes for the given attributes.
*
* @param attributes Attributes for which indexes should be added
* @param <O> Type of objects stored in the collection
* @return An IndexedCollection configured with indexes on the given attributes.
*/
public static <O> IndexedCollection<O> newAutoIndexedCollection(Iterable<Attribute<O, Comparable>> attributes) {
IndexedCollection<O> autoIndexedCollection = new ConcurrentIndexedCollection<O>();
for (Attribute<O, ? extends Comparable> attribute : attributes) {
// Add a NavigableIndex...
@SuppressWarnings("unchecked")
NavigableIndex<? extends Comparable, O> index = NavigableIndex.onAttribute(attribute);
autoIndexedCollection.addIndex(index);
}
return autoIndexedCollection;
}
/**
* Private constructor, not used.
*/
DynamicIndexer() {
}
}
| 3,311 | 39.390244 | 126 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/transactions/TransactionalIndexedCollectionDemo.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.transactions;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.TransactionalIndexedCollection;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import static com.googlecode.cqengine.query.QueryFactory.equal;
import static java.util.Arrays.asList;
/**
* Example usage for {@link com.googlecode.cqengine.TransactionalIndexedCollection}.
*
* @author Niall Gallagher
*/
public class TransactionalIndexedCollectionDemo {
public static void main(String[] args) {
// Create example Car objects...
Car car1 = CarFactory.createCar(1); // "Ford Fusion"
Car car2 = CarFactory.createCar(2); // "Ford Taurus"
Car car3 = CarFactory.createCar(3); // "Honda Civic"
Car car4 = CarFactory.createCar(4); // "Honda Accord"
// We will store the cars in TransactionalIndexedCollection, which provides MVCC support...
IndexedCollection<Car> cars = new TransactionalIndexedCollection<Car>(Car.class);
// ===== Examples of modifying the collection using MVCC transactions... =====
// Add 4 cars in a single transaction...
cars.addAll(asList(car1, car2, car3, car4));
// Remove 2 cars in a single transaction...
cars.removeAll(asList(car3, car4));
// Replace 1 car with 2 other cars in a single transaction...
cars.update(asList(car2), asList(car3, car4));
// ===== Examples of querying the collection using MVCC transactions... =====
// Retrieve with READ_COMMITTED transaction isolation...
ResultSet<Car> results = cars.retrieve(equal(Car.MANUFACTURER, "Ford"));
try {
for (Car car : results) {
System.out.println(car); // prints car 1 ("Ford Fusion")
}
}
finally {
results.close(); // ..close the ResultSet when finished reading!
}
}
}
| 2,684 | 37.357143 | 99 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/inheritance/InheritanceExample.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.inheritance;
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.index.hash.HashIndex;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import static com.googlecode.cqengine.query.QueryFactory.*;
import java.util.Arrays;
/**
* @author Niall Gallagher
*/
public class InheritanceExample {
static final Attribute<Car, Class<? extends Car>> CAR_TYPE = new SimpleAttribute<Car, Class<? extends Car>>() {
public Class<? extends Car> getValue(Car car, QueryOptions queryOptions) { return car.getClass(); }
};
public static void main(String[] args) {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add some indexes...
cars.addIndex(NavigableIndex.onAttribute(Car.CAR_ID));
cars.addIndex(SuffixTreeIndex.onAttribute(Car.NAME));
cars.addIndex(SuffixTreeIndex.onAttribute(Car.DESCRIPTION));
cars.addIndex(HashIndex.onAttribute(Car.FEATURES));
// Index which applies only to SportsCar subclass...
cars.addIndex(NavigableIndex.onAttribute(SportsCar.HORSEPOWER));
// Add some objects to the collection...
cars.add(new Car(1, "mazda 6", "great condition, low mileage", Arrays.asList("nitro boost", "sunroof")));
cars.add(new Car(2, "honda civic", "has a flat tyre and high mileage", Arrays.asList("radio")));
cars.add(new SportsCar(3, "mazda mx-5", "red and sporty", Arrays.asList("radio"), 9000));
cars.add(new SportsCar(4, "porsche 911", "really fast", Arrays.asList("cd player"), 10000));
System.out.println("Cars which have nitro boost or have a horsepower attribute:- ");
Query<Car> carsWithNitroBoostOrAHorsepowerAttribute = or(
equal(Car.FEATURES, "nitro boost"),
has(SportsCar.HORSEPOWER)
);
for (Car car : cars.retrieve(carsWithNitroBoostOrAHorsepowerAttribute)) {
System.out.println(car); // prints mazda 6, mazda mx-5, porsche 911
}
System.out.println();
System.out.println("Cars which are SportsCars but are not a Mazda:- ");
Query<Car> sportsCarsButNotMazda = and(
equal(CAR_TYPE, SportsCar.class),
not(contains(Car.NAME, "mazda"))
);
for (Car car : cars.retrieve(sportsCarsButNotMazda)) {
System.out.println(car); // prints porsche 911
}
System.out.println();
System.out.println("Cars which are a Honda or have horsepower above 9000:- ");
Query<Car> hondaOrHorsepowerAbove9000 = or(
contains(Car.NAME, "honda"),
greaterThan(SportsCar.HORSEPOWER, 9000)
);
for (Car car : cars.retrieve(hondaOrHorsepowerAbove9000)) {
System.out.println(car); // prints honda civic, porsche 911
}
}
}
| 3,837 | 42.613636 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/inheritance/SportsCar.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.inheritance;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class SportsCar extends Car {
final int horsepower;
public SportsCar(int carId, String name, String description, List<String> features, int horsepower) {
super(carId, name, description, features);
this.horsepower = horsepower;
}
@Override
public String toString() {
return "SportsCar{carId=" + carId + ", name='" + name + "', description='" + description + "', features=" + features + ", horsepower=" + horsepower + "}";
}
public static final Attribute<Car, Integer> HORSEPOWER = new SimpleNullableAttribute<Car, Integer>("horsepower") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car instanceof SportsCar ? ((SportsCar)car).horsepower : null; }
};
}
| 1,647 | 35.622222 | 162 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/inheritance/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.examples.inheritance;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.MultiValueAttribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.persistence.support.serialization.PersistenceConfig;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.List;
/**
* A Car object which is configured with polymorphic = true.
*
* @author Niall Gallagher
*/
@PersistenceConfig(polymorphic = true)
public class Car {
public final int carId;
public final String name;
public final String description;
public final List<String> features;
public Car(int carId, String name, String description, List<String> features) {
this.carId = carId;
this.name = name;
this.description = description;
this.features = features;
}
@Override
public String toString() {
return "Car{carId=" + carId + ", name='" + name + "', description='" + description + "', features=" + features + "}";
}
// -------------------------- Attributes --------------------------
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> NAME = new SimpleAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) { return car.name; }
};
public static final SimpleAttribute<Car, String> DESCRIPTION = new SimpleAttribute<Car, String>("description") {
public String getValue(Car car, QueryOptions queryOptions) { return car.description; }
};
public static final Attribute<Car, String> FEATURES = new MultiValueAttribute<Car, String>("features") {
public List<String> getValues(Car car, QueryOptions queryOptions) { return car.features; }
};
}
| 2,603 | 37.294118 | 125 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/introduction/Introduction.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.introduction;
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.radixreversed.ReversedRadixTreeIndex;
import com.googlecode.cqengine.index.suffix.SuffixTreeIndex;
import com.googlecode.cqengine.query.Query;
import java.util.Arrays;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* An introductory example which demonstrates usage using a Car analogy.
*
* @author Niall Gallagher
*/
public class Introduction {
public static void main(String[] args) {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add some indexes...
cars.addIndex(NavigableIndex.onAttribute(Car.CAR_ID));
cars.addIndex(ReversedRadixTreeIndex.onAttribute(Car.NAME));
cars.addIndex(SuffixTreeIndex.onAttribute(Car.DESCRIPTION));
cars.addIndex(HashIndex.onAttribute(Car.FEATURES));
// 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, "ford taurus", "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")));
// -------------------------- Run some queries --------------------------
System.out.println("Cars whose name ends with 'vic' or whose id is less than 2:");
Query<Car> query1 = or(endsWith(Car.NAME, "vic"), lessThan(Car.CAR_ID, 2));
cars.retrieve(query1).forEach(System.out::println);
System.out.println("\nCars whose flat tyre can be replaced:");
Query<Car> query2 = and(contains(Car.DESCRIPTION, "flat tyre"), equal(Car.FEATURES, "spare tyre"));
cars.retrieve(query2).forEach(System.out::println);
System.out.println("\nCars which have a sunroof or a radio but are not dirty:");
Query<Car> query3 = and(in(Car.FEATURES, "sunroof", "radio"), not(contains(Car.DESCRIPTION, "dirty")));
cars.retrieve(query3).forEach(System.out::println);
}
}
| 3,042 | 45.106061 | 117 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/introduction/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.examples.introduction;
import com.googlecode.cqengine.attribute.Attribute;
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 final int carId;
public final String name;
public final String description;
public final List<String> features;
public Car(int carId, String name, String description, List<String> features) {
this.carId = carId;
this.name = name;
this.description = description;
this.features = features;
}
@Override
public String toString() {
return "Car{carId=" + carId + ", name='" + name + "', description='" + description + "', features=" + features + "}";
}
// -------------------------- Attributes --------------------------
public static final Attribute<Car, Integer> CAR_ID = new SimpleAttribute<Car, Integer>("carId") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car.carId; }
};
public static final Attribute<Car, String> NAME = new SimpleAttribute<Car, String>("name") {
public String getValue(Car car, QueryOptions queryOptions) { return car.name; }
};
public static final Attribute<Car, String> DESCRIPTION = new SimpleAttribute<Car, String>("description") {
public String getValue(Car car, QueryOptions queryOptions) { return car.description; }
};
public static final Attribute<Car, String> FEATURES = new MultiValueAttribute<Car, String>("features") {
public List<String> getValues(Car car, QueryOptions queryOptions) { return car.features; }
};
}
| 2,398 | 37.079365 | 125 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/codegen/GenerateSeparateAttributesClass.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.codegen;
import com.googlecode.cqengine.codegen.AttributeSourceGenerator;
/**
* Demonstrates how to auto-generate source code for a complete class containing CQEngine attributes which access fields
* in a given target class.
*
* @author Niall Gallagher
*/
public class GenerateSeparateAttributesClass {
public static void main(String[] args) {
System.out.println(AttributeSourceGenerator.generateSeparateAttributesClass(Car.class, Car.class.getPackage()));
}
}
| 1,130 | 34.34375 | 120 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/codegen/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.examples.codegen;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class Car {
final int carId;
final String manufacturer;
final String model;
final double[] prices;
final String[] extras;
final List<String> features;
public Car(int carId, String manufacturer, String model, double[] prices, String[] extras, List<String> features) {
this.carId = carId;
this.manufacturer = manufacturer;
this.model = model;
this.prices = prices;
this.extras = extras;
this.features = features;
}
}
| 1,217 | 29.45 | 119 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/codegen/GenerateAttributeByteCode.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.codegen;
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.codegen.AttributeBytecodeGenerator;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* Demonstrates how to auto-generate bytecode for CQEngine attributes which access fields in a given class, which
* can then be used directly at runtime.
*
* @author Niall Gallagher
*/
public class GenerateAttributeByteCode {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
// Generate an attribute from bytecode to read the Car.model field...
Map<String, ? extends Attribute<Car, ?>> attributes = AttributeBytecodeGenerator.createAttributes(Car.class);
Attribute<Car, String> MODEL = (Attribute<Car, String>) attributes.get("model");
// Create a collection of 10 Car objects (Ford Focus, Honda Civic etc.)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(10));
// Retrieve the cars whose Car.model field is "Civic" (i.e. the Honda Civic)...
ResultSet<Car> results = cars.retrieve(equal(MODEL, "Civic"));
for (Car car : results) {
System.out.println(car);
}
// ..prints:
// Car{carId=3, manufacturer='Honda', model='Civic', color=WHITE, doors=5, price=4000.0, features=[grade b]}
}
}
| 2,406 | 40.5 | 117 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/codegen/GenerateAttributesForCopyPaste.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.codegen;
import com.googlecode.cqengine.codegen.AttributeSourceGenerator;
/**
* Demonstrates how to auto-generate source code for CQEngine attributes which access fields in a given class, which
* can then be copy-pasted into the target class.
*
* @author Niall Gallagher
*/
public class GenerateAttributesForCopyPaste {
public static void main(String[] args) {
System.out.println(AttributeSourceGenerator.generateAttributesForPastingIntoTargetClass(Car.class));
}
}
| 1,135 | 34.5 | 116 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/ordering/IndexOrderingDemo.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.ordering;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.index.navigable.NavigableIndex;
import com.googlecode.cqengine.resultset.ResultSet;
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.INDEX_ORDERING_SELECTIVITY;
/**
* An example of how to enable the <i>index</i> ordering strategy, to order results by an attribute which does not
* provide values for every object. In this example, some Car objects have features, and some do not.
*
* @author Niall Gallagher
*/
public class IndexOrderingDemo {
public static void main(String[] args) {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addIndex(NavigableIndex.onAttribute(Car.FEATURES));
cars.addIndex(NavigableIndex.onAttribute(forObjectsMissing(Car.FEATURES)));
cars.addAll(CarFactory.createCollectionOfCars(100));
ResultSet<Car> results = cars.retrieve(
between(Car.CAR_ID, 40, 50),
queryOptions(
orderBy(ascending(missingLast(Car.FEATURES))),
applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0))
)
);
for (Car car : results) {
System.out.println(car); // prints cars 40 -> 50, using the index on Car.FEATURES to accelerate ordering
}
}
}
| 2,235 | 40.407407 | 116 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/replace/Replace.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.replace;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.DeduplicatingResultSet;
import static com.googlecode.cqengine.query.QueryFactory.*;
/**
* Demonstrates how to concurrently replace a Car in a collection, using multi-version concurrency control (MVCC).
* <p/>
* This is an alternative to simply removing the old Car object and adding a new Car object with the same carId,
* which is susceptible to a race condition where reading threads might momentarily observe the collection not
* containing any car with the carId.
* <p/>
* In this approach, a new <i>version</i> of the car is added to the collection <i>before removing the old
* version</i>. Filtering on read is applied, such that reading threads will find either the old version or
* the new version of the car (but always exactly one version of it), and will never observe the collection
* <i>not</i> containing the car.
* <p/>
* See also the modified {@link Car} class for this example, which has automatic versioning.
*
* @author Niall Gallagher
*/
public class Replace {
/**
* Demonstrates how to concurrently replace a Car in a collection, using multi-version concurrency control.
* <p/>
* Prints:
* <pre>
* The only car in the collection, before the replacement: Car{carId=1, name='Ford Focus', version=1}
* Collection contains 2 cars, but we filtered the duplicate: Car{carId=1, name='New Ford Focus', version=2}
* Collection contains 1 car again: Car{carId=1, name='New Ford Focus', version=2}
* </pre>
*
* @param args Not used
*/
public static void main(String[] args) {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Add a car with carId 1...
cars.add(new Car(1, "Ford Focus"));
// Test the retrieval...
Car carFound = retrieveOnlyOneVersion(cars, 1);
System.out.println("The only car in the collection, before the replacement: " + carFound);
// Update the name of the Car with carId 1, by replacing it using MVCC...
Car oldVersion = cars.retrieve(equal(Car.CAR_ID, 1)).uniqueResult(); // Retrieve the existing version
Car newVersion = new Car(1, "New Ford Focus"); // Create a new car, same carId, different version
cars.add(newVersion); // Collection now contains two versions of the same car
// Test the retrieval (collection contains both versions, should retrieve only one of them)...
carFound = retrieveOnlyOneVersion(cars, 1);
System.out.println("Collection contains " + cars.size() + " cars, but we filtered the duplicate: " + carFound);
cars.remove(oldVersion); // Remove the old version, collection now only contains new version
// Test the retrieval...
carFound = retrieveOnlyOneVersion(cars, 1);
System.out.println("Collection contains " + cars.size() + " car again: " + carFound);
}
static Car retrieveOnlyOneVersion(IndexedCollection<Car> cars, int carId) {
Query<Car> query = equal(Car.CAR_ID, carId);
ResultSet<Car> multipleCarVersions = cars.retrieve(query);
// Wrap in a result set which will return only one car per version number...
ResultSet<Car> deduplicatedCars = new DeduplicatingResultSet<Car, Integer>(Car.CAR_ID, multipleCarVersions, query, noQueryOptions());
return deduplicatedCars.uniqueResult();
}
}
| 4,259 | 45.813187 | 141 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/replace/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.examples.replace;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.concurrent.atomic.AtomicLong;
/**
* A modified implementation of a Car object, which implements automatic versioning for use with the
* concurrent replace approach in the {@link Replace} example.
*
* @author Niall Gallagher
*/
public class Car {
static final AtomicLong VERSION_GENERATOR = new AtomicLong();
final int carId;
final String name;
// Version field should have a value such that if two objects with the same carId are created,
// their version numbers will be different.
// We cheat on this point, by simply assigning a unique version number to every car...
final long version = VERSION_GENERATOR.incrementAndGet();
public Car(int carId, String name) {
this.carId = carId;
this.name = name;
}
// Return hashCode as normal, ignoring the version field...
@Override
public int hashCode() {
return carId;
}
// Implement equals, to return true only if carIds are equal AND version fields are equal
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Car)) return false;
Car other = (Car) o;
return this.carId == other.carId && this.version == other.version;
}
@Override
public String toString() {
return "Car{carId=" + carId + ", name='" + name + "', version=" + version + "}";
}
// -------------------------- Attributes --------------------------
public static final Attribute<Car, Integer> CAR_ID = new SimpleAttribute<Car, Integer>("carId") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car.carId; }
};
}
| 2,498 | 33.708333 | 101 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/join/SqlExistsBasedJoin.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.join;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.query.Query;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
/**
* Demonstrates a join between two indexed collections. Given a collection of Cars, and a collections of Garages,
* find cars which are convertible or which have a sunroof, which can be serviced by garages in Dublin, along with
* the names of those garages.
*
* @author Niall Gallagher
*/
public class SqlExistsBasedJoin {
public static void main(String[] args) {
// Create an indexed collection of cars...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.add(new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof")));
cars.add(new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio")));
cars.add(new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio")));
cars.add(new Car(4, "BMW M3", "2013 model", asList("radio", "convertible")));
// Create an indexed collection of garages...
final IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
garages.add(new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic")));
garages.add(new Garage(2, "Jane's garage", "Dublin", asList("BMW M3")));
garages.add(new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus")));
garages.add(new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus")));
// Query: Cars which are convertible or which have a sunroof, which can be serviced in Dublin...
Query<Car> carsQuery = and(
in(Car.FEATURES, "sunroof", "convertible"),
existsIn(garages,
Car.NAME,
Garage.BRANDS_SERVICED,
equal(Garage.LOCATION, "Dublin")
)
);
for (Car car : cars.retrieve(carsQuery)) {
Query<Garage> garagesWhichServiceThisCarInDublin
= and(equal(Garage.BRANDS_SERVICED, car.name), equal(Garage.LOCATION, "Dublin"));
boolean first = true;
for (Garage garage : garages.retrieve(garagesWhichServiceThisCarInDublin)) {
if (first) {
// Print this only when we have actually retrieved the first garage, in case the
// collection was modified removing the first garage before the inner loop :)...
System.out.println(car.name + " has a sunroof or is convertible, " +
"and can be serviced in Dublin at the following garages:- " );
first = false;
}
System.out.println("---> " + garage);
}
System.out.println();
}
/* ..prints:
BMW M3 has a sunroof or is convertible, and can be serviced in Dublin at the following garages:-
---> Garage{garageId=2, name='Jane's garage', location='Dublin', brandsServiced=[BMW M3]}
Ford Focus has a sunroof or is convertible, and can be serviced in Dublin at the following garages:-
---> Garage{garageId=3, name='John's garage', location='Dublin', brandsServiced=[Ford Focus, Ford Taurus]}
---> Garage{garageId=4, name='Jill's garage', location='Dublin', brandsServiced=[Ford Focus]}
*/
}
} | 4,297 | 49.564706 | 118 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/join/ThreeWayJoin.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.join;
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 static com.googlecode.cqengine.query.QueryFactory.*;
/**
* Demonstrates a JOIN between three IndexedCollections.
* <p/>
* Given:
* a collection of Users (having a userId + userName),
* a collections of Roles (having roleId + roleName),
* and a collection of UserRoles (having userId + roleId),
* ...find users who have the roleName "Manager".
*
* @author npgall
*/
public class ThreeWayJoin {
public static void main(String[] args) {
IndexedCollection<User> users = new ConcurrentIndexedCollection<User>();
users.add(new User(1, "Joe"));
users.add(new User(2, "Jane"));
users.add(new User(3, "Jesse"));
IndexedCollection<Role> roles = new ConcurrentIndexedCollection<Role>();
roles.add(new Role(1, "CEO"));
roles.add(new Role(2, "Manager"));
roles.add(new Role(3, "Employee"));
IndexedCollection<UserRole> userRoles = new ConcurrentIndexedCollection<UserRole>();
userRoles.add(new UserRole(1, 3)); // Joe is an Employee
userRoles.add(new UserRole(2, 2)); // Jane is a Manager
userRoles.add(new UserRole(3, 2)); // Jesse is a Manager
// Retrieve Users who are managers...
Query<User> usersWhoAreManagers =
existsIn(userRoles, User.USER_ID, UserRole.USER_ID,
existsIn(roles, UserRole.ROLE_ID, Role.ROLE_ID, equal(Role.ROLE_NAME, "Manager")));
for (User u : users.retrieve(usersWhoAreManagers)) {
System.out.println(u.userName);
}
// ..prints: Jane, Jesse
}
// === Domain objects ===
static class User {
final int userId;
final String userName;
public User(int userId, String userName) {
this.userId = userId;
this.userName = userName;
}
static final Attribute<User, Integer> USER_ID = new SimpleAttribute<User, Integer>() {
public Integer getValue(User user, QueryOptions queryOptions) { return user.userId; }
};
static final Attribute<User, String> USER_NAME = new SimpleAttribute<User, String>() {
public String getValue(User user, QueryOptions queryOptions) { return user.userName; }
};
}
static class Role {
final int roleId;
final String roleName;
public Role(int roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
static final Attribute<Role, Integer> ROLE_ID = new SimpleAttribute<Role, Integer>() {
public Integer getValue(Role role, QueryOptions queryOptions) { return role.roleId; }
};
static final Attribute<Role, String> ROLE_NAME = new SimpleAttribute<Role, String>() {
public String getValue(Role role, QueryOptions queryOptions) { return role.roleName; }
};
}
static class UserRole {
final int userId;
final int roleId;
public UserRole(int userId, int roleId) {
this.userId = userId;
this.roleId = roleId;
}
static final Attribute<UserRole, Integer> USER_ID = new SimpleAttribute<UserRole, Integer>() {
public Integer getValue(UserRole userRole, QueryOptions queryOptions) { return userRole.userId; }
};
static final Attribute<UserRole, Integer> ROLE_ID = new SimpleAttribute<UserRole, Integer>() {
public Integer getValue(UserRole userRole, QueryOptions queryOptions) { return userRole.roleId; }
};
}
}
| 4,513 | 36 | 109 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/join/Garage.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.join;
import com.googlecode.cqengine.attribute.Attribute;
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 Garage {
public final int garageId;
public final String name;
public final String location;
public final List<String> brandsServiced;
public Garage(int garageId, String name, String location, List<String> brandsServiced) {
this.garageId = garageId;
this.name = name;
this.location = location;
this.brandsServiced = brandsServiced;
}
@Override
public String toString() {
return "Garage{" +
"garageId=" + garageId +
", name='" + name + '\'' +
", location='" + location + '\'' +
", brandsServiced=" + brandsServiced +
'}';
}
public static final Attribute<Garage, Integer> GARAGE_ID = new SimpleAttribute<Garage, Integer>("garageId") {
public Integer getValue(Garage garage, QueryOptions queryOptions) { return garage.garageId; }
};
public static final Attribute<Garage, String> NAME = new SimpleAttribute<Garage, String>("name") {
public String getValue(Garage garage, QueryOptions queryOptions) { return garage.name; }
};
public static final Attribute<Garage, String> LOCATION = new SimpleAttribute<Garage, String>("location") {
public String getValue(Garage garage, QueryOptions queryOptions) { return garage.location; }
};
public static final Attribute<Garage, String> BRANDS_SERVICED = new MultiValueAttribute<Garage, String>("brandsServiced") {
public List<String> getValues(Garage garage, QueryOptions queryOptions) { return garage.brandsServiced; }
};
}
| 2,537 | 38.046154 | 127 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/join/SqlExists.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.join;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.query.Query;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static java.util.Arrays.asList;
/**
* Demonstrates a query between two indexed collections. Given a collection of Cars, and a collections of Garages,
* find cars which are convertible or which have a sunroof, which can be serviced by garages in Dublin.
*
* @author Niall Gallagher
*/
public class SqlExists {
public static void main(String[] args) {
// Create an indexed collection of cars...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.add(new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof")));
cars.add(new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio")));
cars.add(new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio")));
cars.add(new Car(4, "BMW M3", "2013 model", asList("radio", "convertible")));
// Create an indexed collection of garages...
final IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
garages.add(new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic")));
garages.add(new Garage(2, "Jane's garage", "Dublin", asList("BMW M3")));
garages.add(new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus")));
garages.add(new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus")));
// Query: Cars which are convertible or which have a sunroof, which can be serviced in Dublin...
Query<Car> carsQuery = and(
in(Car.FEATURES, "sunroof", "convertible"),
existsIn(garages,
Car.NAME,
Garage.BRANDS_SERVICED,
equal(Garage.LOCATION, "Dublin")
)
);
for (Car car : cars.retrieve(carsQuery)) {
System.out.println(car.name + " has a sunroof or is convertible, and can be serviced in Dublin");
}
/* ..prints:
BMW M3 has a sunroof or is convertible, and can be serviced in Dublin
Ford Focus has a sunroof or is convertible, and can be serviced in Dublin
*/
}
} | 3,123 | 45.626866 | 114 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/wildcard/Wildcard.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.wildcard;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SelfAttribute;
import com.googlecode.cqengine.index.radix.RadixTreeIndex;
import com.googlecode.cqengine.index.radixreversed.ReversedRadixTreeIndex;
import com.googlecode.cqengine.query.Query;
import com.googlecode.cqengine.query.option.QueryOptions;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.resultset.filter.FilteringResultSet;
import java.util.Arrays;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* Demonstrates how to perform wildcard queries in CQEngine as of CQEngine ~1.0.3.
* This will be further simplified in later versions.
* <p/>
* These queries can be accelerated by adding both {@link RadixTreeIndex} and {@link ReversedRadixTreeIndex}.
*
* @author Niall Gallagher
*/
public class Wildcard {
public static void main(String[] args) {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(Arrays.asList("TEAM", "TEST", "TOAST", "T", "TT"));
IndexedCollection<String> collection = indexedCollection;
collection.addIndex(RadixTreeIndex.onAttribute(SELF));
collection.addIndex(ReversedRadixTreeIndex.onAttribute(SELF));
for (String match : retrieveWildcardMatches(collection, "T", "T")) {
System.out.println(match); // TOAST, TEST, TT
}
}
public static ResultSet<String> retrieveWildcardMatches(IndexedCollection<String> collection, final String prefix, final String suffix) {
Query<String> query = and(startsWith(SELF, prefix), endsWith(SELF, suffix));
ResultSet<String> candidates = collection.retrieve(query);
return new FilteringResultSet<String>(candidates, query, noQueryOptions()) {
@Override
public boolean isValid(String candidate, QueryOptions queryOptions) {
return candidate.length() >= prefix.length() + suffix.length();
}
};
}
static final Attribute<String, String> SELF = new SelfAttribute<String>(String.class);
}
| 2,979 | 40.971831 | 141 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/parser/SQLQueryDemo.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.parser;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.codegen.AttributeBytecodeGenerator;
import com.googlecode.cqengine.query.parser.sql.SQLParser;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import static com.googlecode.cqengine.codegen.AttributeBytecodeGenerator.createAttributes;
/**
* Demonstrates creating a collection and running an SQL query on it.
* <p/>
* Attribute are generated automatically using {@link AttributeBytecodeGenerator}.
*
* @author niall.gallagher
*/
public class SQLQueryDemo {
public static void main(String[] args) {
SQLParser<Car> parser = SQLParser.forPojoWithAttributes(Car.class, createAttributes(Car.class));
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(10));
ResultSet<Car> results = parser.retrieve(cars, "SELECT * FROM cars WHERE (" +
"(manufacturer = 'Ford' OR manufacturer = 'Honda') " +
"AND price <= 5000.0 " +
"AND color NOT IN ('GREEN', 'WHITE')) " +
"ORDER BY manufacturer DESC, price ASC");
results.forEach(System.out::println); // Prints: Honda Accord, Ford Fusion, Ford Focus
}
}
| 2,163 | 41.431373 | 104 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/examples/parser/CQNQueryDemo.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.examples.parser;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.codegen.AttributeBytecodeGenerator;
import com.googlecode.cqengine.query.parser.cqn.CQNParser;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import com.googlecode.cqengine.testutil.CarFactory;
import static com.googlecode.cqengine.codegen.AttributeBytecodeGenerator.createAttributes;
/**
* Demonstrates creating a collection and running an CQN query on it.
* <p/>
* Attribute are generated automatically using {@link AttributeBytecodeGenerator}.
*
* @author niall.gallagher
*/
public class CQNQueryDemo {
public static void main(String[] args) {
CQNParser<Car> parser = CQNParser.forPojoWithAttributes(Car.class, createAttributes(Car.class));
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
cars.addAll(CarFactory.createCollectionOfCars(10));
ResultSet<Car> results = parser.retrieve(cars,
"and(" +
"or(equal(\"manufacturer\", \"Ford\"), equal(\"manufacturer\", \"Honda\")), " +
"lessThanOrEqualTo(\"price\", 5000.0), " +
"not(in(\"color\", GREEN, WHITE))" +
")");
results.forEach(System.out::println); // Prints: Ford Focus, Ford Fusion, Honda Accord
}
}
| 2,195 | 41.230769 | 123 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/ResultSetTest.java | package com.googlecode.cqengine.resultset;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.QueryFactory.selfAttribute;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
/**
* Unit tests for the base {@link ResultSet}.
*/
public class ResultSetTest {
@Test
public void testStream() {
List<String> input = asList("a", "b", "c", "d");
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(input);
ResultSet<String> resultSet = indexedCollection.retrieve(all(String.class), queryOptions(orderBy(ascending(selfAttribute(String.class)))));
Stream<String> stream = resultSet.stream();
List<String> output = stream.collect(toList());
assertEquals(input, output);
}
@Test
public void testStreamClose() {
AtomicBoolean closeCalled = new AtomicBoolean();
ResultSet<Integer> resultSet = new StoredSetBasedResultSet<Integer>(emptySet()) {
@Override
public void close() {
super.close();
closeCalled.set(true);
}
};
Stream<Integer> stream = resultSet.stream();
assertFalse(closeCalled.get());
stream.close();
assertTrue(closeCalled.get());
}
} | 1,791 | 31.581818 | 147 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/ResultSetsTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.resultset.common.ResultSets;
import com.googlecode.cqengine.resultset.iterator.IteratorUtil;
import org.junit.Test;
import java.util.Collection;
import static com.googlecode.cqengine.query.QueryFactory.all;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
public class ResultSetsTest {
@Test
public void testAsCollection() throws Exception {
IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
indexedCollection.addAll(asList("how", "now", "brown", "cow"));
ResultSet<String> resultSet = indexedCollection.retrieve(all(String.class));
Collection<String> collection = ResultSets.asCollection(resultSet);
assertEquals(resultSet.size(), collection.size());
assertEquals(resultSet.size(), IteratorUtil.countElements(collection));
assertEquals(resultSet.isEmpty(), collection.isEmpty());
assertTrue(collection.contains("now"));
assertFalse(collection.contains("baz"));
}
} | 1,807 | 38.304348 | 96 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/iterator/MarkableIteratorTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.iterator;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
/**
* @author niall.gallagher
*/
public class MarkableIteratorTest {
@Test
public void testMarkAndResetDuringRead() {
List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MarkableIterator<Integer> markableIterator= new MarkableIterator<Integer>(input.iterator());
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Advance 5...
Assert.assertEquals(5, Iterators.advance(markableIterator, 5));
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Mark this position...
markableIterator.mark(Integer.MAX_VALUE);
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Advance 3...
Assert.assertEquals(3, Iterators.advance(markableIterator, 3));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Reset to position 5...
markableIterator.reset();
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
Assert.assertEquals(Arrays.asList(5, 6, 7, 8, 9), Lists.newArrayList(markableIterator));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
}
@Test
public void testMarkAndResetDuringReplay() {
List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MarkableIterator<Integer> markableIterator= new MarkableIterator<Integer>(input.iterator());
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Advance 5...
Assert.assertEquals(5, Iterators.advance(markableIterator, 5));
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Mark this position...
markableIterator.mark(Integer.MAX_VALUE);
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Advance 3...
Assert.assertEquals(3, Iterators.advance(markableIterator, 3));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Reset to position 5...
markableIterator.reset();
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Advance/replay 1 (should find integer 5)...
Assert.assertEquals(Collections.singletonList(5), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Mark this position 6...
markableIterator.mark(Integer.MAX_VALUE);
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Advance 2 (should find integers 6 & 7)...
Assert.assertEquals(Arrays.asList(6, 7), Lists.newArrayList(Iterators.limit(markableIterator, 2)));
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Advance 1 (should find integer 8)...
Assert.assertEquals(Collections.singletonList(8), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Reset to position 6...
markableIterator.reset();
// Replay the remainder of the buffer...
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
Assert.assertEquals(Arrays.asList(6, 7), Lists.newArrayList(Iterators.limit(markableIterator, 2)));
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Then read the next object from the backing iterator, and note that state changes...
Assert.assertEquals(Collections.singletonList(8), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Read the rest of the stream from backing iterator...
Assert.assertEquals(Collections.singletonList(9), Lists.newArrayList(markableIterator));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
}
@Test
public void testMarkAndResetDuringBuffer() {
List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MarkableIterator<Integer> markableIterator= new MarkableIterator<Integer>(input.iterator());
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Advance 5...
Assert.assertEquals(Arrays.asList(0, 1, 2, 3, 4), Lists.newArrayList(Iterators.limit(markableIterator, 5)));
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
// Mark this position...
markableIterator.mark(1);
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Advance 1...
Assert.assertEquals(Collections.singletonList(5), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Mark this position...
markableIterator.mark(2);
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Advance 1...
Assert.assertEquals(Collections.singletonList(6), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
// Reset to position 6...
markableIterator.reset();
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
// Replay the remainder of the buffer...
Assert.assertEquals(Collections.singletonList(6), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.REPLAY, markableIterator.state);
Assert.assertEquals(Collections.singletonList(7), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
Assert.assertEquals(Collections.singletonList(8), Lists.newArrayList(Iterators.limit(markableIterator, 1)));
// Mark is invalidated...
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
Assert.assertEquals(Collections.singletonList(9), Lists.newArrayList(markableIterator));
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
}
@Test(expected = IllegalStateException.class)
public void testResetWithoutMark() {
List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MarkableIterator<Integer> markableIterator= new MarkableIterator<Integer>(input.iterator());
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
markableIterator.reset();
}
@Test(expected = IllegalStateException.class)
public void testMarkInvalidated() {
List<Integer> input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
MarkableIterator<Integer> markableIterator= new MarkableIterator<Integer>(input.iterator());
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
markableIterator.mark(1);
Assert.assertEquals(MarkableIterator.State.BUFFER, markableIterator.state);
Assert.assertEquals(Arrays.asList(0, 1), Lists.newArrayList(Iterators.limit(markableIterator, 2)));
Assert.assertEquals(MarkableIterator.State.READ, markableIterator.state);
markableIterator.reset();
}
} | 8,392 | 46.151685 | 116 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/common/IteratorCachingResultSetTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.common;
import com.googlecode.cqengine.resultset.ResultSet;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.Iterator;
import static com.googlecode.cqengine.testutil.CarFactory.createCar;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;
/**
* Tests for {@link IteratorCachingResultSet}.
*
* @author niall.gallagher
*/
public class IteratorCachingResultSetTest {
@Test
@SuppressWarnings("unchecked")
public void testIteratorCaching() {
ResultSet<Car> backingResultSet = mock(ResultSet.class);
when(backingResultSet.iterator()).thenReturn(mock(Iterator.class), mock(Iterator.class), mock(Iterator.class), mock(Iterator.class), mock(Iterator.class), mock(Iterator.class), mock(Iterator.class));
IteratorCachingResultSet<Car> iteratorCachingResultSet = new IteratorCachingResultSet<Car>(backingResultSet);
Iterator<Car> i1 = iteratorCachingResultSet.iterator();
Iterator<Car> i2 = iteratorCachingResultSet.iterator();
assertSame(i1, i2);
i2.hasNext();
i2.hasNext();
Iterator<Car> i3 = iteratorCachingResultSet.iterator();
assertSame(i1, i3);
i3.next();
Iterator<Car> i4 = iteratorCachingResultSet.iterator();
assertNotSame(i3, i4);
i4.remove();
Iterator<Car> i5 = iteratorCachingResultSet.iterator();
assertNotSame(i4, i5);
i5.hasNext();
i5.hasNext();
Iterator<Car> i6 = iteratorCachingResultSet.iterator();
assertSame(i5, i6);
iteratorCachingResultSet.isEmpty();
iteratorCachingResultSet.isNotEmpty();
Iterator<Car> i7 = iteratorCachingResultSet.iterator();
assertSame(i6, i7);
}
@Test
@SuppressWarnings("unchecked")
public void testDelegatingMethods() {
ResultSet<Car> backingResultSet = mock(ResultSet.class);
IteratorCachingResultSet<Car> iteratorCachingResultSet = new IteratorCachingResultSet<Car>(backingResultSet);
iteratorCachingResultSet.contains(createCar(1));
verify(backingResultSet, times(1)).contains(createCar(1));
iteratorCachingResultSet.matches(createCar(2));
verify(backingResultSet, times(1)).matches(createCar(2));
iteratorCachingResultSet.getQuery();
verify(backingResultSet, times(1)).getQuery();
iteratorCachingResultSet.getQueryOptions();
verify(backingResultSet, times(1)).getQueryOptions();
iteratorCachingResultSet.getRetrievalCost();
verify(backingResultSet, times(1)).getRetrievalCost();
iteratorCachingResultSet.getMergeCost();
verify(backingResultSet, times(1)).getMergeCost();
iteratorCachingResultSet.size();
verify(backingResultSet, times(1)).size();
iteratorCachingResultSet.close();
verify(backingResultSet, times(1)).close();
}
} | 3,615 | 34.80198 | 207 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/order/AttributeOrdersComparatorTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.order;
import com.googlecode.cqengine.query.option.OrderByOption;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* @author Roberto Socrates
* @author Niall Gallagher
*/
public class AttributeOrdersComparatorTest {
@Test
public void testSortAscending() {
List<Car> cars = Arrays.asList(
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 7000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(2, "BMW", "M6", Car.Color.RED, 2, 9000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.WHITE, 5, 6000.00, Collections.<String>emptyList(), Collections.emptyList())
);
OrderByOption<Car> ordering = orderBy(ascending(Car.MANUFACTURER), ascending(Car.PRICE));
Collections.sort(cars, new AttributeOrdersComparator<Car>(ordering.getAttributeOrders(), noQueryOptions()));
List<Car> expected = Arrays.asList(
new Car(2, "BMW", "M6", Car.Color.RED, 2, 9000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 7000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.WHITE, 5, 6000.00, Collections.<String>emptyList(), Collections.emptyList())
);
Assert.assertEquals(expected, cars);
}
@Test
public void testSortDescending() {
List<Car> cars = Arrays.asList(
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 7000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(2, "BMW", "M6", Car.Color.RED, 2, 9000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.WHITE, 5, 6000.00, Collections.<String>emptyList(), Collections.emptyList())
);
OrderByOption<Car> ordering = orderBy(descending(Car.MANUFACTURER), descending(Car.PRICE));
Collections.sort(cars, new AttributeOrdersComparator<Car>(ordering.getAttributeOrders(), noQueryOptions()));
List<Car> expected = Arrays.asList(
new Car(3, "Honda", "Civic", Car.Color.WHITE, 5, 6000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 7000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 5000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(2, "BMW", "M6", Car.Color.RED, 2, 9000.00, Collections.<String>emptyList(), Collections.emptyList())
);
Assert.assertEquals(expected, cars);
}
@Test
public void testSortMixed() {
List<Car> cars = Arrays.asList(
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 2000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Taurus", Car.Color.BLACK, 4, 1000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.BLACK, 4, 4000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.BLACK, 4, 3000.00, Collections.<String>emptyList(), Collections.emptyList())
);
OrderByOption<Car> ordering = orderBy(descending(Car.MANUFACTURER), ascending(Car.PRICE));
Collections.sort(cars, new AttributeOrdersComparator<Car>(ordering.getAttributeOrders(), noQueryOptions()));
List<Car> expected = Arrays.asList(
new Car(3, "Honda", "Civic", Car.Color.BLACK, 4, 3000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(3, "Honda", "Civic", Car.Color.BLACK, 4, 4000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(1, "Ford", "Taurus", Car.Color.BLACK, 4, 1000.00, Collections.<String>emptyList(), Collections.emptyList()),
new Car(0, "Ford", "Taurus", Car.Color.BLACK, 4, 2000.00, Collections.<String>emptyList(), Collections.emptyList())
);
Assert.assertEquals(expected, cars);
}
}
| 5,538 | 54.39 | 133 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/order/MaterializedDeduplicatedResultSetTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.order;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
import org.junit.Test;
import org.junit.Assert;
import java.util.Collections;
import java.util.Iterator;
/**
* @author dsmith
*/
public class MaterializedDeduplicatedResultSetTest {
@Test
public void testMaterializingResultSetIterator() throws Exception {
final MaterializedDeduplicatedResultSet<Object> set = new MaterializedDeduplicatedResultSet<Object>(new StoredSetBasedResultSet<Object>(Collections.<Object>singleton(this)));
final Iterator<Object> it = set.iterator();
Assert.assertTrue(it.hasNext());
Assert.assertTrue(it.hasNext());
}
}
| 1,320 | 34.702703 | 182 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/filter/DeduplicatingResultSetTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.IndexedCollectionFunctionalTest;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.resultset.stored.StoredSetBasedResultSet;
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 java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
public class DeduplicatingResultSetTest {
@Test
public void testDeduplicatingResultSet() {
Collection<Car> cars = CarFactory.createCollectionOfCars(10);
DeduplicatingResultSet<Car, String> deduplicatingResultSet = new DeduplicatingResultSet<Car, String>(
Car.MANUFACTURER,
new StoredSetBasedResultSet<Car>(new LinkedHashSet<Car>(cars)),
QueryFactory.all(Car.class), QueryFactory.noQueryOptions()
);
List<Integer> carIdsReturned = new ArrayList<Integer>();
IndexedCollectionFunctionalTest.extractCarIds(deduplicatingResultSet, carIdsReturned);
// Should return the first distinct Manufacturer...
Assert.assertEquals(4, deduplicatingResultSet.size());
Assert.assertEquals(0, deduplicatingResultSet.getRetrievalCost());
Assert.assertEquals(10, deduplicatingResultSet.getMergeCost());
Assert.assertEquals(4, carIdsReturned.size());
Assert.assertEquals(0, carIdsReturned.get(0).intValue());
Assert.assertEquals(3, carIdsReturned.get(1).intValue());
Assert.assertEquals(6, carIdsReturned.get(2).intValue());
Assert.assertEquals(9, carIdsReturned.get(3).intValue());
Assert.assertTrue(deduplicatingResultSet.contains(CarFactory.createCar(0)));
Assert.assertTrue(deduplicatingResultSet.contains(CarFactory.createCar(3)));
Assert.assertTrue(deduplicatingResultSet.contains(CarFactory.createCar(6)));
Assert.assertTrue(deduplicatingResultSet.contains(CarFactory.createCar(9)));
Assert.assertFalse(deduplicatingResultSet.contains(CarFactory.createCar(1)));
deduplicatingResultSet.close(); // No op.
}
} | 2,819 | 43.0625 | 109 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/resultset/filter/FilteringIteratorTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.resultset.filter;
import com.googlecode.cqengine.query.option.QueryOptions;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
public class FilteringIteratorTest {
@Test
public void testHasNextDoesNotAdvanceIterator(){
List<String> testList = Arrays.asList("abc", "bcd", "cde");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return true;
}
};
iterator.hasNext();
iterator.hasNext();
iterator.hasNext();
assertThat(iterator.next(), is("abc"));
}
@Test
public void testNextPopulatedWithoutCallingHasNext(){
List<String> testList = Arrays.asList("abc", "bcd", "cde");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return true;
}
};
assertThat(iterator.next(), is("abc"));
}
@Test
public void testDelegatedIteratorHasNulls() {
List<String> testList = Arrays.asList("abc", null, "cde");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return true;
}
};
assertThat(iterator.next(), is("abc"));
assertThat(iterator.next(), nullValue());
assertThat(iterator.next(), is("cde"));
assertThat(iterator.hasNext(), is(false));
}
@Test
public void testFiltering() {
List<String> testList = Arrays.asList("aaa", "bbb", "aab", "bba");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return object.startsWith("aa");
}
};
assertThat(iterator.next(), is("aaa"));
assertThat(iterator.next(), is("aab"));
assertThat(iterator.hasNext(), is(false));
}
@Test
public void testFilteringState() {
List<String> testList = Arrays.asList("aaa", "bbb", "aab", "bba");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return false;
}
};
assertThat(iterator.hasNext(), is(false));
assertThat(iterator.hasNext(), is(false));
}
@Test
public void testFilterNullValues() {
List<String> testList = Arrays.asList("aaa", null, "aab", "bba");
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return true;
}
};
assertThat(iterator.hasNext(), is(true));
assertThat("first string value", iterator.next(), is("aaa"));
assertThat(iterator.hasNext(), is(true));
assertThat("second null value", iterator.next(), nullValue());
assertThat(iterator.hasNext(), is(true));
}
@Test(expected = NoSuchElementException.class)
public void testEmptyDelegate() {
List<String> testList = Arrays.asList();
FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
@Override
public boolean isValid(String object, QueryOptions queryOptions) {
return true;
}
};
iterator.next();
}
}
| 4,887 | 36.6 | 115 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/attribute/ReflectiveAttributeTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.ConcurrentIndexedCollection;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.index.hash.HashIndex;
import com.googlecode.cqengine.query.QueryFactory;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Arrays;
import static com.googlecode.cqengine.query.QueryFactory.equal;
/**
* @author Niall Gallagher
*/
public class ReflectiveAttributeTest {
@Test
public void testReflectiveAttribute() {
// Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
// Define an attribute which will use reflection...
Attribute<Car, String> NAME = ReflectiveAttribute.forField(Car.class, String.class, "name");
cars.addIndex(HashIndex.onAttribute(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, "ford taurus", "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(equal(NAME, "honda civic")).size(), 1);
}
@Test
public void testGetInheritedField() throws NoSuchFieldException {
Assert.assertEquals("foo", ReflectiveAttribute.getField(Bar.class, "foo").getName());
Assert.assertEquals("bar", ReflectiveAttribute.getField(Bar.class, "bar").getName());
NoSuchFieldException expected = null;
try {
ReflectiveAttribute.getField(Bar.class, "baz");
}
catch (NoSuchFieldException nsfe) {
expected = nsfe;
}
Assert.assertNotNull(expected);
}
@Test
public void testEqualsAndHashCode() throws NoSuchFieldException {
EqualsVerifier.forClass(ReflectiveAttribute.class)
.withRedefinedSuperclass()
.withPrefabValues(Field.class, Foo.class.getDeclaredField("foo"), Bar.class.getDeclaredField("bar"))
.withCachedHashCode("cachedHashCode", "calcHashCode", null)
.suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE, Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)
.verify();
}
@Test(expected = IllegalStateException.class)
public void testInvalidField() {
ReflectiveAttribute.forField(Foo.class, int.class, "baz");
}
@Test(expected = IllegalStateException.class)
public void testInvalidFieldType() {
ReflectiveAttribute.forField(Foo.class, double.class, "foo");
}
@Test(expected = IllegalStateException.class)
@SuppressWarnings("unchecked")
public void testGetValueInvalidObject() {
ReflectiveAttribute reflectiveAttribute = ReflectiveAttribute.forField(Foo.class, int.class, "foo");
reflectiveAttribute.getValue("", QueryFactory.noQueryOptions());
}
static class Foo {
private int foo;
}
static class Bar extends Foo {
private int bar;
}
}
| 4,017 | 37.266667 | 117 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/attribute/SimpleNullableMapAttributeTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.concurrenttrees.common.Iterables;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.googlecode.cqengine.query.QueryFactory.mapAttribute;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
/**
* Created by npgall on 23/05/2016.
*/
public class SimpleNullableMapAttributeTest {
@Test
@SuppressWarnings("unchecked")
public void testSimpleNullableMapAttribute() {
Map map = new HashMap();
map.put("foo", 1);
map.put("bar", 2.5);
map.put(1.5F, "baz");
Attribute<Map, Integer> FOO = mapAttribute("foo", Integer.class);
Attribute<Map, Double> BAR = mapAttribute("bar", Double.class);
Attribute<Map, String> ONE_POINT_FIVE = mapAttribute(1.5F, String.class);
Attribute<Map, String> NON_EXISTENT = mapAttribute("foobar", String.class);
Assert.assertEquals("[1]", Iterables.toString(FOO.getValues(map, noQueryOptions())));
Assert.assertEquals("[2.5]", Iterables.toString(BAR.getValues(map, noQueryOptions())));
Assert.assertEquals("[baz]", Iterables.toString(ONE_POINT_FIVE.getValues(map, noQueryOptions())));
Assert.assertEquals("[]", Iterables.toString(NON_EXISTENT.getValues(map, noQueryOptions())));
}
} | 1,976 | 35.611111 | 106 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/attribute/LambdaFunctionalAttributesTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute;
import com.googlecode.cqengine.attribute.support.MultiValueFunction;
import com.googlecode.cqengine.attribute.support.SimpleFunction;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import java.util.List;
import static com.googlecode.cqengine.query.QueryFactory.*;
import static org.junit.Assert.*;
/**
* Tests creation of CQEngine attributes from lambda expressions.
*
* @author npgall
*/
public class LambdaFunctionalAttributesTest {
// ====== Java 8... ======
// final SimpleFunction<Car, Integer> carIdFunction = Car::getCarId;
//
// final MultiValueFunction<Car, String, List<String>> featuresFunction = Car::getFeatures;
// =======================
// ====== Java 6... ======
final SimpleFunction<Car, Integer> carIdFunction = new SimpleFunction<Car, Integer>() {
public Integer apply(Car car) { return car.getCarId(); }
};
final MultiValueFunction<Car, String, List<String>> featuresFunction = new MultiValueFunction<Car, String, List<String>>() {
public List<String> apply(Car car) { return car.getFeatures(); }
};
// =======================
@Test
public void testFunctionalSimpleAttribute() {
SimpleAttribute<Car, Integer> CAR_ID = attribute(carIdFunction);
assertEquals(Car.class, CAR_ID.getObjectType());
assertEquals(Integer.class, CAR_ID.getAttributeType());
assertTrue(CAR_ID.getAttributeName().startsWith(this.getClass().getName() + "$"));
}
@Test
public void testFunctionalSimpleNullableAttribute() {
SimpleNullableAttribute<Car, Integer> CAR_ID = nullableAttribute(carIdFunction);
assertEquals(Car.class, CAR_ID.getObjectType());
assertEquals(Integer.class, CAR_ID.getAttributeType());
assertTrue(CAR_ID.getAttributeName().startsWith(this.getClass().getName() + "$"));
}
@Test
public void testFunctionalMultiValueAttribute() {
MultiValueAttribute<Car, String> CAR_ID = attribute(String.class, featuresFunction);
assertEquals(Car.class, CAR_ID.getObjectType());
assertEquals(String.class, CAR_ID.getAttributeType());
assertTrue(CAR_ID.getAttributeName().startsWith(this.getClass().getName() + "$"));
}
@Test
public void testFunctionalMultiValueNullableAttribute() {
MultiValueNullableAttribute<Car, String> CAR_ID = nullableAttribute(String.class, featuresFunction);
assertEquals(Car.class, CAR_ID.getObjectType());
assertEquals(String.class, CAR_ID.getAttributeType());
assertTrue(CAR_ID.getAttributeName().startsWith(this.getClass().getName() + "$"));
}
}
| 3,287 | 37.682353 | 128 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/attribute/support/AbstractAttributeTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.attribute.support;
import com.googlecode.cqengine.attribute.SimpleAttribute;
import com.googlecode.cqengine.query.option.QueryOptions;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class AbstractAttributeTest {
static class ValidAttribute extends SimpleAttribute<Integer, String> {
@Override
public String getValue(Integer object, QueryOptions queryOptions) {
return String.valueOf(object);
}
};
static class ValidAttribute2 extends SimpleAttribute<Integer, String> {
@Override
public String getValue(Integer object, QueryOptions queryOptions) {
return String.valueOf(object);
}
};
static class ValidAttributeWithParameterizedTypes extends SimpleAttribute<Set<Integer>, List<String>> {
@Override
public List<String> getValue(Set<Integer> object, QueryOptions queryOptions) {
return Arrays.asList(String.valueOf(object));
}
};
static class ValidAttributeMultipleConstructors extends SimpleAttribute<Integer, String> {
public ValidAttributeMultipleConstructors() {
}
public ValidAttributeMultipleConstructors(String attributeName) {
super(attributeName);
}
public ValidAttributeMultipleConstructors(Class<Integer> objectType, Class<String> attributeType) {
super(objectType, attributeType);
}
public ValidAttributeMultipleConstructors(Class<Integer> objectType, Class<String> attributeType, String attributeName) {
super(objectType, attributeType, attributeName);
}
@Override
public String getValue(Integer object, QueryOptions queryOptions) {
return String.valueOf(object);
}
};
static class InvalidAttribute extends SimpleAttribute {
@Override
public Object getValue(Object object, QueryOptions queryOptions) {
return String.valueOf(object);
}
};
@Test
public void testReadGenericObjectType() throws Exception {
//noinspection AssertEqualsBetweenInconvertibleTypes
Assert.assertEquals(Integer.class, AbstractAttribute.readGenericObjectType(ValidAttribute.class, "foo"));
//noinspection AssertEqualsBetweenInconvertibleTypes
Assert.assertEquals(Set.class, AbstractAttribute.readGenericObjectType(ValidAttributeWithParameterizedTypes.class, "foo"));
}
@Test(expected = IllegalStateException.class)
public void testReadGenericObjectType_InvalidAttribute() throws Exception {
AbstractAttribute.readGenericObjectType(InvalidAttribute.class, "foo");
}
@Test
public void testReadGenericAttributeType() throws Exception {
//noinspection AssertEqualsBetweenInconvertibleTypes
Assert.assertEquals(String.class, AbstractAttribute.readGenericAttributeType(ValidAttribute.class, "foo"));
//noinspection AssertEqualsBetweenInconvertibleTypes
Assert.assertEquals(List.class, AbstractAttribute.readGenericAttributeType(ValidAttributeWithParameterizedTypes.class, "foo"));
}
@Test(expected = IllegalStateException.class)
public void testReadGenericAttributeType_InvalidAttribute() throws Exception {
AbstractAttribute.readGenericAttributeType(InvalidAttribute.class, "foo");
}
@Test
public void testConstructors() {
ValidAttributeMultipleConstructors a1, a2, a3, a4;
a1 = new ValidAttributeMultipleConstructors();
a2 = new ValidAttributeMultipleConstructors("foo");
a3 = new ValidAttributeMultipleConstructors(Integer.class, String.class);
a4 = new ValidAttributeMultipleConstructors(Integer.class, String.class, "foo");
Assert.assertEquals(Integer.class, a1.getObjectType());
Assert.assertEquals(Integer.class, a2.getObjectType());
Assert.assertEquals(Integer.class, a3.getObjectType());
Assert.assertEquals(Integer.class, a4.getObjectType());
Assert.assertEquals(String.class, a1.getAttributeType());
Assert.assertEquals(String.class, a2.getAttributeType());
Assert.assertEquals(String.class, a3.getAttributeType());
Assert.assertEquals(String.class, a4.getAttributeType());
Assert.assertEquals("<Unnamed attribute, class com.googlecode.cqengine.attribute.support.AbstractAttributeTest$ValidAttributeMultipleConstructors>", a1.getAttributeName());
Assert.assertEquals("foo", a2.getAttributeName());
Assert.assertEquals("<Unnamed attribute, class com.googlecode.cqengine.attribute.support.AbstractAttributeTest$ValidAttributeMultipleConstructors>", a3.getAttributeName());
Assert.assertEquals("foo", a4.getAttributeName());
}
} | 5,528 | 41.206107 | 180 | java |
cqengine | cqengine-master/code/src/test/java/com/googlecode/cqengine/codegen/AttributeBytecodeGeneratorTest.java | /**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.codegen;
import com.googlecode.cqengine.attribute.*;
import com.googlecode.cqengine.examples.inheritance.SportsCar;
import org.junit.Test;
import java.util.*;
import static com.googlecode.cqengine.codegen.AttributeBytecodeGenerator.*;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
public class AttributeBytecodeGeneratorTest {
// ====== Tests for SimpleAttribute ======
static class PojoWithField {
final String foo = "bar";
}
static class PojoWithPrimitiveField {
final int foo = 5;
}
static class PojoWithGetter {
String getFoo() {
return "bar";
}
}
static class PojoWithParameterizedGetter {
String getFoo(String name) {
return "bar_" + name;
}
}
static class AnotherPojoWithGetter {
Integer getBar() { return 1; }
}
static class SuperCar extends SportsCar { // ...SportCar in turn extends Car
final double[] tyrePressures;
final Float[] wheelSpeeds;
public Float[] getWheelSpeeds() { return wheelSpeeds; }
public SuperCar(int carId, String name, String description, List<String> features, int horsepower, double[] tyrePressures, Float[] wheelSpeeds) {
super(carId, name, description, features, horsepower);
this.tyrePressures = tyrePressures;
this.wheelSpeeds = wheelSpeeds;
}
}
@Test
@SuppressWarnings("unchecked")
public void testCreateAttributesForFields() {
SuperCar car1 = new SuperCar(0, "Ford Focus", "Blue", Arrays.asList("sunroof", "radio"), 5000, new double[] {1536.5, 1782.9}, new Float[] {56700.9F, 83321.0F});
SuperCar car2 = new SuperCar(1, "Ford Fusion", "Red", Arrays.asList("coupe", "cd player"), 6000, new double[] {12746.2, 2973.1}, new Float[] {43424.4F, 61232.7F});
Map<String, ? extends Attribute<SuperCar, ?>> attributes = AttributeBytecodeGenerator.createAttributes(SuperCar.class);
assertFalse(attributes.containsKey("horsepower")); // horsepower is not accessible from the subclass
// 2 fields in SuperCar, plus 0 fields inherited from SportsCar, plus 4 inherited from Car...
assertEquals(6, attributes.size());
// Validate attributes reading fields from car1...
validateAttribute(((Attribute<SuperCar, Integer>)attributes.get("carId")), SuperCar.class, Integer.class, "carId", car1, Collections.singletonList(0));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("name")), SuperCar.class, String.class, "name", car1, Collections.singletonList("Ford Focus"));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("description")), SuperCar.class, String.class, "description", car1, Collections.singletonList("Blue"));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("features")), SuperCar.class, String.class, "features", car1, Arrays.asList("sunroof", "radio"));
validateAttribute(((Attribute<SuperCar, Double>)attributes.get("tyrePressures")), SuperCar.class, Double.class, "tyrePressures", car1, Arrays.asList(1536.5, 1782.9));
validateAttribute(((Attribute<SuperCar, Float>)attributes.get("wheelSpeeds")), SuperCar.class, Float.class, "wheelSpeeds", car1, Arrays.asList(56700.9F, 83321.0F));
// Validate attributes reading fields from car2...
validateAttribute(((Attribute<SuperCar, Integer>)attributes.get("carId")), SuperCar.class, Integer.class, "carId", car2, Collections.singletonList(1));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("name")), SuperCar.class, String.class, "name", car2, Collections.singletonList("Ford Fusion"));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("description")), SuperCar.class, String.class, "description", car2, Collections.singletonList("Red"));
validateAttribute(((Attribute<SuperCar, String>)attributes.get("features")), SuperCar.class, String.class, "features", car2, Arrays.asList("coupe", "cd player"));
validateAttribute(((Attribute<SuperCar, Double>)attributes.get("tyrePressures")), SuperCar.class, Double.class, "tyrePressures", car2, Arrays.asList(12746.2, 2973.1));
validateAttribute(((Attribute<SuperCar, Float>)attributes.get("wheelSpeeds")), SuperCar.class, Float.class, "wheelSpeeds", car2, Arrays.asList(43424.4F, 61232.7F));
}
@Test
@SuppressWarnings("unchecked")
public void testCreateAttributesForGetterMethods() {
SuperCar car1 = new SuperCar(0, "Ford Focus", "Blue", Arrays.asList("sunroof", "radio"), 5000, new double[] {1536.5, 1782.9}, new Float[] {56700.9F, 83321.0F});
SuperCar car2 = new SuperCar(1, "Ford Fusion", "Red", Arrays.asList("coupe", "cd player"), 6000, new double[] {12746.2, 2973.1}, new Float[] {43424.4F, 61232.7F});
Map<String, ? extends Attribute<SuperCar, ?>> attributes = AttributeBytecodeGenerator.createAttributes(SuperCar.class, MemberFilters.GETTER_METHODS_ONLY);
assertEquals(1, attributes.size());
// Validate attributes reading fields from car1...
validateAttribute(((Attribute<SuperCar, Float>)attributes.get("getWheelSpeeds")), SuperCar.class, Float.class, "getWheelSpeeds", car1, Arrays.asList(56700.9F, 83321.0F));
// Validate attributes reading fields from car2...
validateAttribute(((Attribute<SuperCar, Float>)attributes.get("getWheelSpeeds")), SuperCar.class, Float.class, "getWheelSpeeds", car2, Arrays.asList(43424.4F, 61232.7F));
}
@Test
@SuppressWarnings("unchecked")
public void testCreateAttributesForGetterMethods_HumanReadable() {
AnotherPojoWithGetter pojo = new AnotherPojoWithGetter();
Map<String, ? extends Attribute<AnotherPojoWithGetter, ?>> attributes = AttributeBytecodeGenerator.createAttributes(AnotherPojoWithGetter.class, MemberFilters.GETTER_METHODS_ONLY, AttributeNameProducers.USE_HUMAN_READABLE_NAMES_FOR_GETTERS);
assertEquals(1, attributes.size());
validateAttribute(((Attribute<AnotherPojoWithGetter, Integer>)attributes.get("bar")), AnotherPojoWithGetter.class, Integer.class, "bar", pojo, Collections.singletonList(1));
}
@Test
public void testGenerateSimpleAttributeForField() throws Exception {
Class<? extends SimpleAttribute<PojoWithField, String>> attributeClass = generateSimpleAttributeForField(PojoWithField.class, String.class, "foo", "foo");
SimpleAttribute<PojoWithField, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithField.class, String.class, "foo", new PojoWithField(), asList("bar"));
}
@Test
public void testGenerateSimpleAttributeForField_PrimitiveField() throws Exception {
Class<? extends SimpleAttribute<PojoWithPrimitiveField, Integer>> attributeClass = generateSimpleAttributeForField(PojoWithPrimitiveField.class, Integer.class, "foo", "foo");
SimpleAttribute<PojoWithPrimitiveField, Integer> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithPrimitiveField.class, Integer.class, "foo", new PojoWithPrimitiveField(), asList(5));
}
@Test
public void testGenerateSimpleAttributeForGetterMethod() throws Exception {
Class<? extends SimpleAttribute<PojoWithGetter, String>> attributeClass = generateSimpleAttributeForGetter(PojoWithGetter.class, String.class, "getFoo", "foo");
SimpleAttribute<PojoWithGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithGetter.class, String.class, "foo", new PojoWithGetter(), asList("bar"));
}
@Test
public void testGenerateSimpleAttributeForParameterizedGetterMethod() throws Exception {
Class<? extends SimpleAttribute<PojoWithParameterizedGetter, String>> attributeClass = generateSimpleAttributeForParameterizedGetter(PojoWithParameterizedGetter.class, String.class, "getFoo", "baz", "foo");
SimpleAttribute<PojoWithParameterizedGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithParameterizedGetter.class, String.class, "foo", new PojoWithParameterizedGetter(), asList("bar_baz"));
}
@Test(expected = IllegalStateException.class)
public void testGenerateSimpleAttributeForField_ExceptionHandling1() throws Exception {
generateSimpleAttributeForField(null, String.class, "foo", "foo");
}
@Test(expected = IllegalStateException.class)
public void testGenerateSimpleAttributeForField_ExceptionHandling2() throws Exception {
generateSimpleAttributeForField(PojoWithField.class, null, "foo", "foo");
}
// ====== Tests for SimpleNullableAttribute ======
static class NullablePojoWithField {
final String foo = null;
}
static class NullablePojoWithGetter {
String getFoo() {
return null;
}
}
static class NullablePojoWithParameterizedGetter {
String getFoo(String name) {
return null;
}
}
@Test
public void testGenerateSimpleNullableAttributeForField() throws Exception {
Class<? extends SimpleNullableAttribute<NullablePojoWithField, String>> attributeClass = generateSimpleNullableAttributeForField(NullablePojoWithField.class, String.class, "foo", "foo");
SimpleNullableAttribute<NullablePojoWithField, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithField.class, String.class, "foo", new NullablePojoWithField(), Collections.<String>emptyList());
}
@Test
public void testGenerateSimpleNullableAttributeForGetter() throws Exception {
Class<? extends SimpleNullableAttribute<NullablePojoWithGetter, String>> attributeClass = generateSimpleNullableAttributeForGetter(NullablePojoWithGetter.class, String.class, "getFoo", "foo");
SimpleNullableAttribute<NullablePojoWithGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithGetter.class, String.class, "foo", new NullablePojoWithGetter(), Collections.<String>emptyList());
}
@Test
public void testGenerateSimpleNullableAttributeForParameterizedGetter() throws Exception {
Class<? extends SimpleNullableAttribute<NullablePojoWithParameterizedGetter, String>> attributeClass = generateSimpleNullableAttributeForParameterizedGetter(NullablePojoWithParameterizedGetter.class, String.class, "getFoo", "baz", "foo");
SimpleNullableAttribute<NullablePojoWithParameterizedGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithParameterizedGetter.class, String.class, "foo", new NullablePojoWithParameterizedGetter(), Collections.<String>emptyList());
}
@Test(expected = IllegalStateException.class)
public void testGenerateSimpleNullableAttributeForField_ExceptionHandling1() throws Exception {
generateSimpleNullableAttributeForField(null, String.class, "foo", "foo");
}
// ====== Tests for MultiValueAttribute ======
static class PojoWithMultiValueField {
final List<String> foo = asList("bar1", "bar2");
}
static class PojoWithMultiValuePrimitiveArrayField {
final int[] foo = {5, 6};
}
static class PojoWithMultiValueObjectArrayField {
final String[] foo = {"bar1", "bar2"};
}
static class PojoWithMultiValueGetter {
List<String> getFoo() {
return asList("bar1", "bar2");
}
}
static class PojoWithMultiValueParameterizedGetter {
List<String> getFoo(String name) {
return asList("bar1_" + name, "bar2_" + name);
}
}
@Test
public void testGenerateMultiValueAttributeForField_ListField() throws Exception {
Class<? extends MultiValueAttribute<PojoWithMultiValueField, String>> attributeClass = generateMultiValueAttributeForField(PojoWithMultiValueField.class, String.class, "foo", "foo");
MultiValueAttribute<PojoWithMultiValueField, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithMultiValueField.class, String.class, "foo", new PojoWithMultiValueField(), asList("bar1", "bar2"));
}
@Test
public void testGenerateMultiValueAttributeForField_PrimitiveArrayField() throws Exception {
Class<? extends MultiValueAttribute<PojoWithMultiValuePrimitiveArrayField, Integer>> attributeClass = generateMultiValueAttributeForField(PojoWithMultiValuePrimitiveArrayField.class, Integer.class, "foo", "foo");
MultiValueAttribute<PojoWithMultiValuePrimitiveArrayField, Integer> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithMultiValuePrimitiveArrayField.class, Integer.class, "foo", new PojoWithMultiValuePrimitiveArrayField(), asList(5, 6));
}
@Test
public void testGenerateMultiValueAttributeForField_ObjectArrayField() throws Exception {
Class<? extends MultiValueAttribute<PojoWithMultiValueObjectArrayField, String>> attributeClass = generateMultiValueAttributeForField(PojoWithMultiValueObjectArrayField.class, String.class, "foo", "foo");
MultiValueAttribute<PojoWithMultiValueObjectArrayField, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithMultiValueObjectArrayField.class, String.class, "foo", new PojoWithMultiValueObjectArrayField(), asList("bar1", "bar2"));
}
@Test
public void testGenerateMultiValueAttributeForGetter() throws Exception {
Class<? extends MultiValueAttribute<PojoWithMultiValueGetter, String>> attributeClass = generateMultiValueAttributeForGetter(PojoWithMultiValueGetter.class, String.class, "getFoo", "foo");
MultiValueAttribute<PojoWithMultiValueGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithMultiValueGetter.class, String.class, "foo", new PojoWithMultiValueGetter(), asList("bar1", "bar2"));
}
@Test
public void testGenerateMultiValueAttributeForParameterizedGetter() throws Exception {
Class<? extends MultiValueAttribute<PojoWithMultiValueParameterizedGetter, String>> attributeClass = generateMultiValueAttributeForParameterizedGetter(PojoWithMultiValueParameterizedGetter.class, String.class, "getFoo", "baz", "foo");
MultiValueAttribute<PojoWithMultiValueParameterizedGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, PojoWithMultiValueParameterizedGetter.class, String.class, "foo", new PojoWithMultiValueParameterizedGetter(), asList("bar1_baz", "bar2_baz"));
}
@Test(expected = IllegalStateException.class)
public void testGenerateMultiValueAttributeForField_ExceptionHandling1() throws Exception {
generateMultiValueAttributeForField(null, String.class, "foo", "object.foo");
}
@Test(expected = IllegalStateException.class)
public void testGenerateMultiValueAttributeForField_ExceptionHandling2() throws Exception {
generateMultiValueAttributeForField(PojoWithMultiValueField.class, null, "foo", "foo");
}
// ====== Tests for MultiValueNullableAttribute ======
static class NullablePojoWithMultiValueField {
final List<String> foo = null;
}
static class NullablePojoWithMultiValueGetter {
List<String> getFoo() {
return null;
}
}
static class NullablePojoWithMultiValueParameterizedGetter {
List<String> getFoo(String name) {
return null;
}
}
@Test
public void testGenerateMultiValueNullableAttributeForField() throws Exception {
Class<? extends MultiValueNullableAttribute<NullablePojoWithMultiValueField, String>> attributeClass = generateMultiValueNullableAttributeForField(NullablePojoWithMultiValueField.class, String.class, "foo", true, "foo");
MultiValueNullableAttribute<NullablePojoWithMultiValueField, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithMultiValueField.class, String.class, "foo", new NullablePojoWithMultiValueField(), Collections.<String>emptyList());
}
@Test
public void testGenerateMultiValueNullableAttributeForGetter() throws Exception {
Class<? extends MultiValueNullableAttribute<NullablePojoWithMultiValueGetter, String>> attributeClass = generateMultiValueNullableAttributeForGetter(NullablePojoWithMultiValueGetter.class, String.class, "getFoo", true, "foo");
MultiValueNullableAttribute<NullablePojoWithMultiValueGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithMultiValueGetter.class, String.class, "foo", new NullablePojoWithMultiValueGetter(), Collections.<String>emptyList());
}
@Test
public void testGenerateMultiValueNullableAttributeForParameterizedGetter() throws Exception {
Class<? extends MultiValueNullableAttribute<NullablePojoWithMultiValueParameterizedGetter, String>> attributeClass = generateMultiValueNullableAttributeForParameterizedGetter(NullablePojoWithMultiValueParameterizedGetter.class, String.class, "getFoo", "baz", true, "foo");
MultiValueNullableAttribute<NullablePojoWithMultiValueParameterizedGetter, String> attribute = attributeClass.newInstance();
validateAttribute(attribute, NullablePojoWithMultiValueParameterizedGetter.class, String.class, "foo", new NullablePojoWithMultiValueParameterizedGetter(), Collections.<String>emptyList());
}
@Test(expected = IllegalStateException.class)
public void testGenerateMultiValueNullableAttributeForField_ExceptionHandling1() throws Exception {
generateMultiValueNullableAttributeForField(null, String.class, "foo", true, "object.foo");
}
@Test(expected = IllegalStateException.class)
public void testGenerateMultiValueNullableAttributeForField_ExceptionHandling2() throws Exception {
generateMultiValueNullableAttributeForField(NullablePojoWithMultiValueField.class, null, "foo", true, "foo");
}
// ====== Tests for support methods ======
@Test(expected = IllegalStateException.class)
public void testEnsureFieldExists_Negative() {
ensureFieldExists(String.class, Integer.class, "xxxxxxxxxx", "na");
}
@Test(expected = IllegalStateException.class)
public void testEnsureGetterExists_Negative() {
ensureGetterExists(String.class, Integer.class, "xxxxxxxxxx", "na");
}
@Test(expected = IllegalStateException.class)
public void testEnsureParameterizedGetterExists_Negative1() {
ensureParameterizedGetterExists(String.class, Integer.class, "xxxxxxxxxx", "x", "na");
}
@Test(expected = IllegalStateException.class)
public void testEnsureParameterizedGetterExists_Negative2() {
ensureParameterizedGetterExists(String.class, Integer.class, "xxxxxxxxxx", "\"foo\"", "na");
}
@Test(expected = IllegalStateException.class)
public void testEnsureParameterizedGetterExists_Negative3() {
ensureParameterizedGetterExists(String.class, Integer.class, "xxxxxxxxxx", "\\foo", "na");
}
@Test
public void testConstructor() {
assertNotNull(new AttributeBytecodeGenerator());
}
@Test(expected = IllegalStateException.class)
public void testGetWrapperForPrimitive_NonPrimitiveHandling() {
AttributeBytecodeGenerator.getWrapperForPrimitive(String.class);
}
// ====== Test helper methods ======
static <O, A, T extends Attribute<O, A>> void validateAttribute(T attribute, Class<O> pojoClass, Class<A> attributeType, String attributeName, O pojo, List<A> expectedPojoValues) {
Object values = attribute.getValues(pojo, noQueryOptions());
assertNotNull("getValues() should not return null", values);
assertEquals(pojoClass, attribute.getObjectType());
assertEquals(attributeType, attribute.getAttributeType());
assertEquals(attributeName, attribute.getAttributeName());
assertTrue("getValues() should return a List, actual was: " + values.getClass().getName(), Iterable.class.isAssignableFrom(values.getClass()));
List<A> actualAttributeValues = new ArrayList<A>();
for (A actualValue : attribute.getValues(pojo, noQueryOptions())) {
actualAttributeValues.add(actualValue);
}
assertEquals(expectedPojoValues, actualAttributeValues);
}
} | 21,236 | 55.632 | 280 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.