Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
3,400
|
public class MandatoryTransactionsForIndexCreatorTests
extends AbstractMandatoryTransactionsTest<IndexCreator>
{
@Test
public void shouldRequireTransactionsWhenCallingMethodsOnIndexCreators() throws Exception
{
assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_INDEX_CREATOR_FACADE_METHODS );
}
@Override
protected IndexCreator obtainEntityInTransaction( GraphDatabaseService graphDatabaseService )
{
return graphDatabaseService
.schema()
.indexFor( DynamicLabel.label( "Label" ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForIndexCreatorTests.java
|
3,401
|
public class MandatoryTransactionsForGraphDatabaseServiceTests extends
AbstractMandatoryTransactionsTest<GraphDatabaseService>
{
@Test
public void shouldRequireTransactionsWhenCallingMethodsOnGraphDatabaseService() throws Exception
{
assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_NON_TRANSACTIONAL_GRAPH_DATABASE_METHODS );
}
@Override
protected GraphDatabaseService obtainEntityInTransaction( GraphDatabaseService graphDatabaseService )
{
return graphDatabaseService;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForGraphDatabaseServiceTests.java
|
3,402
|
public class MandatoryTransactionsForGlobalGraphOperations
extends AbstractMandatoryTransactionsTest<GlobalGraphOperations>
{
@Test
public void shouldRequireTransactionsWhenCallingMethodsConstraintCreators() throws Exception
{
assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_GLOBAL_GRAPH_OPERATIONS_FACADE_METHODS );
}
@Override
protected GlobalGraphOperations obtainEntityInTransaction( GraphDatabaseService graphDatabaseService )
{
return GlobalGraphOperations.at( graphDatabaseService );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForGlobalGraphOperations.java
|
3,403
|
public class MandatoryTransactionsForConstraintDefinitionTests
extends AbstractMandatoryTransactionsTest<ConstraintDefinition>
{
@Test
public void shouldRequireTransactionsWhenCallingMethodsOnIndexDefinitions() throws Exception
{
assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_CONSTRAINT_DEFINITION_FACADE_METHODS );
}
@Override
protected ConstraintDefinition obtainEntityInTransaction( GraphDatabaseService graphDatabaseService )
{
return graphDatabaseService
.schema()
.constraintFor( DynamicLabel.label( "Label" ) )
.assertPropertyIsUnique( "property" )
.create();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForConstraintDefinitionTests.java
|
3,404
|
public class MandatoryTransactionsForConstraintCreatorTests
extends AbstractMandatoryTransactionsTest<ConstraintCreator>
{
@Test
public void shouldRequireTransactionsWhenCallingMethodsConstraintCreators() throws Exception
{
assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_CONSTRAINT_CREATOR_FACADE_METHODS );
}
@Override
protected ConstraintCreator obtainEntityInTransaction( GraphDatabaseService graphDatabaseService )
{
return graphDatabaseService
.schema()
.constraintFor( DynamicLabel.label( "Label" ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForConstraintCreatorTests.java
|
3,405
|
{
@Override
protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
{
Set<T> expected = asSet( expectedObjects );
Set<T> found = asSet( nodes.collection() );
if ( !expected.equals( found ) )
{
description.appendText( "found " + found.toString() );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( "exactly " + asSet( expectedObjects ) );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,406
|
{
@Override
protected boolean matchesSafely( Neo4jMatchers.Deferred<IndexDefinition> indexes, Description description )
{
for ( IndexDefinition current : indexes.collection() )
{
Schema.IndexState currentState = db.schema().getIndexState( current );
if ( !currentState.equals( expectedState ) )
{
description.appendValue( current ).appendText( " has state " ).appendValue( currentState );
return false;
}
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( "all indexes have state " + expectedState );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,407
|
{
@Override
public void call( Node node )
{
consume( node.getRelationships( BOTH, FOO, BAR ) );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
|
3,408
|
{
@Override
protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
{
Set<T> expected = asSet( expectedObjects );
Set<T> found = asSet( nodes.collection() );
if ( !found.containsAll( expected ) )
{
description.appendText( "found " + found.toString() );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( "contains " + asSet( expectedObjects ) );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,409
|
{
@Override
public void call( Node node )
{
consume( node.getRelationships( FOO, BAR ) );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
|
3,410
|
{
@Override
public void call( Node node )
{
node.hasProperty( "foo" );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
|
3,411
|
@SuppressWarnings("UnusedDeclaration")
public class NodeFacadeMethods
{
private static final DynamicRelationshipType FOO = withName( "foo" );
private static final DynamicRelationshipType BAR = withName( "bar" );
private static final DynamicRelationshipType BAZ = withName( "baz" );
private static final Label QUUX = label( "quux" );
private static final FacadeMethod<Node> HAS_PROPERTY = new FacadeMethod<Node>( "boolean hasProperty( " +
"String key )" )
{
@Override
public void call( Node node )
{
node.hasProperty( "foo" );
}
};
private static final FacadeMethod<Node> GET_PROPERTY = new FacadeMethod<Node>( "Object getProperty( String key )" )
{
@Override
public void call( Node node )
{
node.getProperty( "foo" );
}
};
private static final FacadeMethod<Node> GET_PROPERTY_WITH_DEFAULT = new FacadeMethod<Node>( "Object getProperty( " +
"String key, Object defaultValue )" )
{
@Override
public void call( Node node )
{
node.getProperty( "foo", 42 );
}
};
private static final FacadeMethod<Node> SET_PROPERTY = new FacadeMethod<Node>( "void setProperty( String key, " +
"Object value )" )
{
@Override
public void call( Node node )
{
node.setProperty( "foo", 42 );
}
};
private static final FacadeMethod<Node> REMOVE_PROPERTY = new FacadeMethod<Node>(
"Object removeProperty( String key )" )
{
@Override
public void call( Node node )
{
node.removeProperty( "foo" );
}
};
private static final FacadeMethod<Node> GET_PROPERTY_KEYS = new FacadeMethod<Node>(
"Iterable<String> getPropertyKeys()" )
{
@Override
public void call( Node node )
{
consume( node.getPropertyKeys() );
}
};
private static final FacadeMethod<Node> DELETE = new FacadeMethod<Node>( "void delete()" )
{
@Override
public void call( Node node )
{
node.delete();
}
};
private static final FacadeMethod<Node> GET_RELATIONSHIPS = new FacadeMethod<Node>(
"Iterable<Relationship> getRelationships()" )
{
@Override
public void call( Node node )
{
consume( node.getRelationships() );
}
};
private static final FacadeMethod<Node> HAS_RELATIONSHIP = new FacadeMethod<Node>( "boolean hasRelationship()" )
{
@Override
public void call( Node node )
{
node.hasRelationship();
}
};
private static final FacadeMethod<Node> GET_RELATIONSHIPS_BY_TYPE = new FacadeMethod<Node>(
"Iterable<Relationship> getRelationships( RelationshipType... types )" )
{
@Override
public void call( Node node )
{
consume( node.getRelationships( FOO, BAR ) );
}
};
private static final FacadeMethod<Node> GET_RELATIONSHIPS_BY_DIRECTION_AND_TYPES = new FacadeMethod<Node>(
"Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types )" )
{
@Override
public void call( Node node )
{
consume( node.getRelationships( BOTH, FOO, BAR ) );
}
};
private static final FacadeMethod<Node> HAS_RELATIONSHIP_BY_TYPE = new FacadeMethod<Node>( "boolean " +
"hasRelationship( RelationshipType... types )" )
{
@Override
public void call( Node node )
{
node.hasRelationship( FOO );
}
};
private static final FacadeMethod<Node> HAS_RELATIONSHIP_BY_DIRECTION_AND_TYPE = new FacadeMethod<Node>( "boolean " +
"hasRelationship( Direction direction, RelationshipType... types )" )
{
@Override
public void call( Node node )
{
node.hasRelationship( BOTH, FOO );
}
};
private static final FacadeMethod<Node> GET_RELATIONSHIPS_BY_DIRECTION = new FacadeMethod<Node>(
"Iterable<Relationship> getRelationships( Direction dir )" )
{
@Override
public void call( Node node )
{
consume( node.getRelationships( BOTH ) );
}
};
private static final FacadeMethod<Node> HAS_RELATIONSHIP_BY_DIRECTION = new FacadeMethod<Node>( "boolean " +
"hasRelationship( Direction dir )" )
{
@Override
public void call( Node node )
{
node.hasRelationship( BOTH );
}
};
private static final FacadeMethod<Node> GET_RELATIONSHIPS_BY_TYPE_AND_DIRECTION = new FacadeMethod<Node>(
"Iterable<Relationship> getRelationships( RelationshipType type, Direction dir );" )
{
@Override
public void call( Node node )
{
consume( node.getRelationships( FOO, BOTH ) );
}
};
private static final FacadeMethod<Node> HAS_RELATIONSHIP_BY_TYPE_AND_DIRECTION = new FacadeMethod<Node>( "boolean " +
"hasRelationship( RelationshipType type, Direction dir )" )
{
@Override
public void call( Node node )
{
node.hasRelationship( FOO, BOTH );
}
};
private static final FacadeMethod<Node> GET_SINGLE_RELATIONSHIP = new FacadeMethod<Node>( "Relationship " +
"getSingleRelationship( RelationshipType type, Direction dir )" )
{
@Override
public void call( Node node )
{
node.getSingleRelationship( FOO, BOTH );
}
};
private static final FacadeMethod<Node> CREATE_RELATIONSHIP_TO = new FacadeMethod<Node>( "Relationship " +
"createRelationshipTo( Node otherNode, RelationshipType type )" )
{
@Override
public void call( Node node )
{
node.createRelationshipTo( node, FOO );
}
};
private static final FacadeMethod<Node> TRAVERSE_USING_ONE_TYPE_AND_DIRECTION = new FacadeMethod<Node>( "Traverser " +
"traverse( Traverser.Order " +
"traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, " +
"RelationshipType relationshipType, Direction direction )" )
{
@Override
public void call( Node node )
{
//noinspection deprecation
node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH );
}
};
private static final FacadeMethod<Node> TRAVERSE_USING_TWO_TYPES_AND_DIRECTIONS = new FacadeMethod<Node>( "Traverser " +
"traverse( Traverser.Order " +
"traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, " +
"RelationshipType firstRelationshipType, Direction firstDirection, " +
"RelationshipType secondRelationshipType, Direction secondDirection )" )
{
@Override
public void call( Node node )
{
//noinspection deprecation
node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH, BAR, OUTGOING );
}
};
private static final FacadeMethod<Node> TRAVERSE_USING_ANY_NUMBER_OF_TYPES_AND_DIRECTIONS = new FacadeMethod<Node>(
"Traverser traverse( Traverser.Order " +
"traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, " +
"Object... relationshipTypesAndDirections )" )
{
@Override
public void call( Node node )
{
//noinspection deprecation
node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH, BAR, OUTGOING, BAZ, INCOMING );
}
};
private static final FacadeMethod<Node> ADD_LABEL = new FacadeMethod<Node>( "void addLabel( Label label )" )
{
@Override
public void call( Node node )
{
node.addLabel( QUUX );
}
};
private static final FacadeMethod<Node> REMOVE_LABEL = new FacadeMethod<Node>( "void removeLabel( Label label )" )
{
@Override
public void call( Node node )
{
node.removeLabel( QUUX );
}
};
private static final FacadeMethod<Node> HAS_LABEL = new FacadeMethod<Node>( "boolean hasLabel( Label label )" )
{
@Override
public void call( Node node )
{
node.hasLabel( QUUX );
}
};
private static final FacadeMethod<Node> GET_LABELS = new FacadeMethod<Node>( "ResourceIterable<Label> getLabels()" )
{
@Override
public void call( Node node )
{
consume( node.getLabels() );
}
};
static final Iterable<FacadeMethod<Node>> ALL_NODE_FACADE_METHODS = unmodifiableCollection( asList(
HAS_PROPERTY,
GET_PROPERTY,
GET_PROPERTY_WITH_DEFAULT,
SET_PROPERTY,
REMOVE_PROPERTY,
GET_PROPERTY_KEYS,
DELETE, GET_RELATIONSHIPS,
HAS_RELATIONSHIP,
GET_RELATIONSHIPS_BY_TYPE,
GET_RELATIONSHIPS_BY_DIRECTION_AND_TYPES,
HAS_RELATIONSHIP_BY_TYPE,
HAS_RELATIONSHIP_BY_DIRECTION_AND_TYPE,
GET_RELATIONSHIPS_BY_DIRECTION,
HAS_RELATIONSHIP_BY_DIRECTION,
GET_RELATIONSHIPS_BY_TYPE_AND_DIRECTION,
HAS_RELATIONSHIP_BY_TYPE_AND_DIRECTION,
GET_SINGLE_RELATIONSHIP, CREATE_RELATIONSHIP_TO,
TRAVERSE_USING_ONE_TYPE_AND_DIRECTION,
TRAVERSE_USING_TWO_TYPES_AND_DIRECTIONS,
TRAVERSE_USING_ANY_NUMBER_OF_TYPES_AND_DIRECTIONS,
ADD_LABEL,
REMOVE_LABEL,
HAS_LABEL,
GET_LABELS
) );
private static void consume( Iterable<?> iterable )
{
for ( Object o : iterable )
{
assertNotNull( o );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
|
3,412
|
{
@Override
public PrimitiveIntIterator answer( InvocationOnMock invocation ) throws Throwable
{
return toPrimitiveIntIterator( values.iterator() );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMockitoHelpers.java
|
3,413
|
{
@Override
public PrimitiveLongIterator answer( InvocationOnMock invocation ) throws Throwable
{
return toPrimitiveLongIterator( values.iterator() );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMockitoHelpers.java
|
3,414
|
{
@Override
public Iterator<T> answer( InvocationOnMock invocation ) throws Throwable
{
return values.iterator();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMockitoHelpers.java
|
3,415
|
public class Neo4jMockitoHelpers
{
public static <T> Answer<Iterator<T>> answerAsIteratorFrom( final Iterable<T> values )
{
return new Answer<Iterator<T>>()
{
@Override
public Iterator<T> answer( InvocationOnMock invocation ) throws Throwable
{
return values.iterator();
}
};
}
public static Answer<PrimitiveLongIterator> answerAsPrimitiveLongIteratorFrom( final Iterable<Long> values )
{
return new Answer<PrimitiveLongIterator>()
{
@Override
public PrimitiveLongIterator answer( InvocationOnMock invocation ) throws Throwable
{
return toPrimitiveLongIterator( values.iterator() );
}
};
}
public static Answer<PrimitiveIntIterator> answerAsPrimitiveIntIteratorFrom( final Iterable<Integer> values )
{
return new Answer<PrimitiveIntIterator>()
{
@Override
public PrimitiveIntIterator answer( InvocationOnMock invocation ) throws Throwable
{
return toPrimitiveIntIterator( values.iterator() );
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMockitoHelpers.java
|
3,416
|
public static class PropertyValueMatcher extends TypeSafeDiagnosingMatcher<PropertyContainer>
{
private final PropertyMatcher propertyMatcher;
private final String propertyName;
private final Object expectedValue;
private PropertyValueMatcher( PropertyMatcher propertyMatcher, String propertyName, Object expectedValue )
{
this.propertyMatcher = propertyMatcher;
this.propertyName = propertyName;
this.expectedValue = expectedValue;
}
@Override
protected boolean matchesSafely( PropertyContainer propertyContainer, Description mismatchDescription )
{
if ( !propertyMatcher.matchesSafely( propertyContainer, mismatchDescription ) )
{
return false;
}
Object foundValue = propertyContainer.getProperty( propertyName );
if ( !propertyValuesEqual( expectedValue, foundValue ) )
{
mismatchDescription.appendText( "found value " + formatValue( foundValue ) );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
propertyMatcher.describeTo( description );
description.appendText( String.format( "having value %s", formatValue( expectedValue ) ) );
}
private boolean propertyValuesEqual( Object expected, Object readValue )
{
if ( expected.getClass().isArray() )
{
return arrayAsCollection( expected ).equals( arrayAsCollection( readValue ) );
} else
{
return expected.equals( readValue );
}
}
private String formatValue(Object v)
{
if (v instanceof String)
{
return String.format("'%s'", v.toString());
}
return v.toString();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,417
|
public static class PropertyMatcher extends TypeSafeDiagnosingMatcher<PropertyContainer>
{
public final String propertyName;
private PropertyMatcher( String propertyName )
{
this.propertyName = propertyName;
}
@Override
protected boolean matchesSafely( PropertyContainer propertyContainer, Description mismatchDescription )
{
if ( !propertyContainer.hasProperty( propertyName ) )
{
mismatchDescription.appendText( String.format( "found property container with property keys: %s",
asSet( propertyContainer.getPropertyKeys() ) ) );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( String.format( "property container with property name '%s' ", propertyName ) );
}
public PropertyValueMatcher withValue( Object value )
{
return new PropertyValueMatcher( this, propertyName, value );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,418
|
public static abstract class Deferred<T>
{
private final GraphDatabaseService db;
public Deferred( GraphDatabaseService db )
{
this.db = db;
}
protected abstract Iterable<T> manifest();
public Collection<T> collection()
{
try ( Transaction ignore = db.beginTx() )
{
return asCollection( manifest() );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,419
|
{
@Override
protected Iterable<IndexDefinition> manifest()
{
return db.schema().getIndexes( label );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,420
|
{
@Override
protected Iterable<Node> manifest()
{
return db.findNodesByLabelAndProperty( label, propertyName, propertyValue );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,421
|
{
int len = 0;
String actualText = null;
String expectedText = null;
@Override
protected boolean matchesSafely( Iterator<Long> expected, Description actualDescription )
{
if ( actualText != null )
{
actualDescription.appendText( actualText );
}
// compare iterators element-wise
while ( expected.hasNext() && actual.hasNext() )
{
len++;
Long expectedNext = expected.next();
long actualNext = actual.next();
if ( !(expectedNext.equals( actualNext )) )
{
actualText = format( "Element %d at position %d", actualNext, len );
expectedText = format( "Element %d at position %d", expectedNext, len );
return false;
}
}
// check that the iterators do not have a different length
if ( expected.hasNext() )
{
actualText = format("Length %d", len );
expectedText = format( "Length %d", len + 1 );
return false;
}
if ( actual.hasNext() )
{
actualText = format("Length %d", len + 1 );
expectedText = format( "Length %d", len );
return false;
}
return true;
}
@Override
public void describeTo( Description expectedDescription )
{
if ( expectedText != null )
{
expectedDescription.appendText( expectedText );
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,422
|
{
@Override
public String apply( Label from )
{
return from.name();
}
}, enums ) );
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,423
|
{
@Override
protected boolean matchesSafely( GlobalGraphOperations glops, Description mismatchDescription )
{
Set<Node> expected = asSet( expectedNodes );
Set<Node> found = asSet( glops.getAllNodesWithLabel( withLabel ) );
if ( !expected.equals( found ) )
{
mismatchDescription.appendText( "found " + found.toString() );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( asSet( expectedNodes ).toString() + " with label " + withLabel );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,424
|
{
@Override
protected boolean matchesSafely( GlobalGraphOperations glops, Description mismatchDescription )
{
Set<Node> found = asSet( glops.getAllNodesWithLabel( withLabel ) );
if ( !found.isEmpty() )
{
mismatchDescription.appendText( "found " + found.toString() );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( "no nodes with label " + withLabel );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,425
|
{
private Set<String> foundLabels;
@Override
public void describeTo( Description description )
{
description.appendText( expectedLabels.toString() );
}
@Override
protected boolean matchesSafely( Node item, Description mismatchDescription )
{
foundLabels = asLabelNameSet( item.getLabels() );
if ( foundLabels.size() == expectedLabels.size() && foundLabels.containsAll( expectedLabels ) )
{
return true;
}
mismatchDescription.appendText( "was " + foundLabels.toString() );
return false;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,426
|
{
@Override
public void describeTo( Description description )
{
description.appendValue( myLabel );
}
@Override
protected boolean matchesSafely( Node item, Description mismatchDescription )
{
boolean result = item.hasLabel( myLabel );
if ( !result )
{
Set<String> labels = asLabelNameSet( item.getLabels() );
mismatchDescription.appendText( labels.toString() );
}
return result;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,427
|
{
@Override
protected boolean matchesSafely( Deferred<?> deferred, Description description )
{
Collection<?> collection = deferred.collection();
if(!collection.isEmpty())
{
description.appendText( "was " + collection.toString() );
return false;
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendText( "empty collection" );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
|
3,428
|
{
@Override
public void call( Relationship relationship )
{
relationship.getProperty( "foo", 42 );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,429
|
{
@Override
public void call( Relationship relationship )
{
relationship.setProperty( "foo", 42 );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,430
|
{
@Override
public void call( Relationship relationship )
{
relationship.removeProperty( "foo" );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,431
|
SHORTEST_PATH
{
@Override
public BranchCollisionDetector create( Evaluator evaluator )
{
return new ShortestPathsBranchCollisionDetector( evaluator );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchCollisionPolicies.java
|
3,432
|
abstract class AbstractUniquenessFilter implements BidirectionalUniquenessFilter
{
final PrimitiveTypeFetcher type;
AbstractUniquenessFilter( PrimitiveTypeFetcher type )
{
this.type = type;
}
public boolean checkFirst( TraversalBranch branch )
{
return type == PrimitiveTypeFetcher.RELATIONSHIP ? true : check( branch );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_AbstractUniquenessFilter.java
|
3,433
|
public class LimitedFilesystemAbstraction implements FileSystemAbstraction
{
private final FileSystemAbstraction inner;
private boolean outOfSpace;
public LimitedFilesystemAbstraction(FileSystemAbstraction wrapped)
{
this.inner = wrapped;
}
@Override
public StoreChannel open( File fileName, String mode ) throws IOException
{
return new LimitedFileChannel( inner.open( fileName, mode ), this );
}
@Override
public OutputStream openAsOutputStream( File fileName, boolean append ) throws IOException
{
return new ChannelOutputStream( open( fileName, "rw" ), append );
}
@Override
public InputStream openAsInputStream( File fileName ) throws IOException
{
return new ChannelInputStream( open( fileName, "r" ) );
}
@Override
public Reader openAsReader( File fileName, String encoding ) throws IOException
{
return new InputStreamReader( openAsInputStream( fileName ), encoding );
}
@Override
public Writer openAsWriter( File fileName, String encoding, boolean append ) throws IOException
{
return new OutputStreamWriter( openAsOutputStream( fileName, append ) );
}
@Override
public FileLock tryLock( File fileName, StoreChannel channel ) throws IOException
{
return inner.tryLock( fileName, channel );
}
@Override
public StoreChannel create( File fileName ) throws IOException
{
ensureHasSpace();
return new LimitedFileChannel( inner.create( fileName ), this );
}
@Override
public boolean fileExists( File fileName )
{
return inner.fileExists( fileName );
}
@Override
public long getFileSize( File fileName )
{
return inner.getFileSize( fileName );
}
@Override
public boolean deleteFile( File fileName )
{
return inner.deleteFile( fileName );
}
@Override
public void deleteRecursively( File directory ) throws IOException
{
inner.deleteRecursively( directory );
}
@Override
public boolean mkdir( File fileName )
{
return inner.mkdir( fileName );
}
@Override
public void mkdirs( File fileName ) throws IOException
{
ensureHasSpace();
inner.mkdirs( fileName );
}
@Override
public boolean renameFile( File from, File to ) throws IOException
{
ensureHasSpace();
return inner.renameFile( from, to );
}
public void runOutOfDiskSpace()
{
outOfSpace = true;
}
public void ensureHasSpace() throws IOException
{
if( outOfSpace )
{
throw new IOException( "No space left on device" );
}
}
@Override
public File[] listFiles( File directory )
{
return inner.listFiles( directory );
}
@Override
public boolean isDirectory( File file )
{
return inner.isDirectory( file );
}
@Override
public void moveToDirectory( File file, File toDirectory ) throws IOException
{
inner.moveToDirectory( file, toDirectory );
}
@Override
public void copyFile( File from, File to ) throws IOException
{
inner.copyFile( from, to );
}
@Override
public void copyRecursively( File fromDirectory, File toDirectory ) throws IOException
{
inner.copyRecursively( fromDirectory, toDirectory );
}
@Override
public <K extends ThirdPartyFileSystem> K getOrCreateThirdPartyFileSystem(
Class<K> clazz, Function<Class<K>, K> creator )
{
return inner.getOrCreateThirdPartyFileSystem( clazz, creator );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_mockfs_LimitedFilesystemAbstraction.java
|
3,434
|
@SuppressWarnings("deprecation")
public class LimitedFileSystemGraphDatabase extends ImpermanentGraphDatabase
{
private LimitedFilesystemAbstraction fs;
@Override
protected FileSystemAbstraction createFileSystemAbstraction()
{
return fs = new LimitedFilesystemAbstraction( super.createFileSystemAbstraction() );
}
public void runOutOfDiskSpaceNao()
{
this.fs.runOutOfDiskSpace();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_mockfs_LimitedFileSystemGraphDatabase.java
|
3,435
|
public class LimitedFileChannel implements StoreChannel
{
private final StoreChannel inner;
private LimitedFilesystemAbstraction fs;
public LimitedFileChannel( StoreChannel inner, LimitedFilesystemAbstraction limitedFilesystemAbstraction )
{
this.inner = inner;
fs = limitedFilesystemAbstraction;
}
@Override
public int read( ByteBuffer byteBuffer ) throws IOException
{
return inner.read( byteBuffer );
}
@Override
public long read( ByteBuffer[] byteBuffers, int i, int i1 ) throws IOException
{
return inner.read( byteBuffers, i, i1 );
}
@Override
public long read( ByteBuffer[] dsts ) throws IOException
{
return 0;
}
@Override
public int write( ByteBuffer byteBuffer ) throws IOException
{
fs.ensureHasSpace();
return inner.write( byteBuffer );
}
@Override
public long write( ByteBuffer[] byteBuffers, int i, int i1 ) throws IOException
{
fs.ensureHasSpace();
return inner.write( byteBuffers, i, i1 );
}
@Override
public long write( ByteBuffer[] srcs ) throws IOException
{
return 0;
}
@Override
public long position() throws IOException
{
return inner.position();
}
@Override
public LimitedFileChannel position( long l ) throws IOException
{
return new LimitedFileChannel( inner.position( l ), fs );
}
@Override
public long size() throws IOException
{
return inner.size();
}
@Override
public LimitedFileChannel truncate( long l ) throws IOException
{
return new LimitedFileChannel( inner.truncate( l ), fs );
}
@Override
public void force( boolean b ) throws IOException
{
fs.ensureHasSpace();
inner.force( b );
}
@Override
public int read( ByteBuffer byteBuffer, long l ) throws IOException
{
return inner.read( byteBuffer, l );
}
@Override
public FileLock tryLock() throws IOException
{
return inner.tryLock();
}
@Override
public int write( ByteBuffer byteBuffer, long l ) throws IOException
{
return inner.write( byteBuffer, l );
}
@Override
public MappedByteBuffer map( FileChannel.MapMode mapMode, long l, long l1 ) throws IOException
{
return inner.map( mapMode, l, l1 );
}
@Override
public boolean isOpen()
{
return inner.isOpen();
}
@Override
public void close() throws IOException
{
inner.close();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_mockfs_LimitedFileChannel.java
|
3,436
|
public class BreakableFileSystemAbstraction implements FileSystemAbstraction, FileSystemGuard
{
private final FileSystemGuard guard;
public void checkOperation( OperationType operationType, File onFile, int bytesWrittenTotal, int bytesWrittenThisCall, long channelPosition ) throws IOException
{
guard.checkOperation( operationType, onFile, bytesWrittenTotal, bytesWrittenThisCall, channelPosition );
}
private final FileSystemAbstraction inner;
public BreakableFileSystemAbstraction( FileSystemAbstraction inner, FileSystemGuard guard )
{
this.inner = inner;
this.guard = guard;
}
@Override
public StoreChannel open( File fileName, String mode ) throws IOException
{
return new BreakableFileChannel( inner.open( fileName, mode ), fileName, this );
}
@Override
public OutputStream openAsOutputStream( File fileName, boolean append ) throws IOException
{
return new ChannelOutputStream( open( fileName, "rw" ), append );
}
@Override
public InputStream openAsInputStream( File fileName ) throws IOException
{
return new ChannelInputStream( open( fileName, "r" ) );
}
@Override
public Reader openAsReader( File fileName, String encoding ) throws IOException
{
return new InputStreamReader( openAsInputStream( fileName ), encoding );
}
@Override
public Writer openAsWriter( File fileName, String encoding, boolean append ) throws IOException
{
return new OutputStreamWriter( openAsOutputStream( fileName, append ) );
}
@Override
public FileLock tryLock( File fileName, StoreChannel channel ) throws IOException
{
return inner.tryLock( fileName, channel );
}
@Override
public StoreChannel create( File fileName ) throws IOException
{
return new BreakableFileChannel( inner.create( fileName ), fileName, this );
}
@Override
public boolean fileExists( File fileName )
{
return inner.fileExists( fileName );
}
@Override
public long getFileSize( File fileName )
{
return inner.getFileSize( fileName );
}
@Override
public boolean deleteFile( File fileName )
{
return inner.deleteFile( fileName );
}
@Override
public void deleteRecursively( File directory ) throws IOException
{
inner.deleteRecursively( directory );
}
@Override
public boolean mkdir( File fileName )
{
return inner.mkdir( fileName );
}
@Override
public void mkdirs( File fileName ) throws IOException
{
inner.mkdirs( fileName );
}
@Override
public boolean renameFile( File from, File to ) throws IOException
{
return inner.renameFile( from, to );
}
@Override
public File[] listFiles( File directory )
{
return inner.listFiles( directory );
}
@Override
public boolean isDirectory( File file )
{
return inner.isDirectory( file );
}
@Override
public void moveToDirectory( File file, File toDirectory ) throws IOException
{
inner.moveToDirectory( file, toDirectory );
}
@Override
public void copyFile( File from, File to ) throws IOException
{
inner.copyFile( from, to );
}
@Override
public void copyRecursively( File fromDirectory, File toDirectory ) throws IOException
{
inner.copyRecursively( fromDirectory, toDirectory );
}
@Override
public <K extends ThirdPartyFileSystem> K getOrCreateThirdPartyFileSystem( Class<K> clazz, Function<Class<K>, K>
creator )
{
return inner.getOrCreateThirdPartyFileSystem( clazz, creator );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_mockfs_BreakableFileSystemAbstraction.java
|
3,437
|
public class BreakableFileChannel implements StoreChannel
{
private final StoreChannel inner;
private final File theFile;
private FileSystemGuard fs;
private int bytesWritten = 0;
public BreakableFileChannel( StoreChannel open, File theFile, FileSystemGuard guard )
{
this.inner = open;
this.theFile = theFile;
this.fs = guard;
}
@Override
public int read( ByteBuffer byteBuffer ) throws IOException
{
return inner.read( byteBuffer );
}
@Override
public long read( ByteBuffer[] byteBuffers, int i, int i1 ) throws IOException
{
return inner.read( byteBuffers, i, i1 );
}
@Override
public long read( ByteBuffer[] dsts ) throws IOException
{
return inner.read( dsts );
}
@Override
public int write( ByteBuffer byteBuffer ) throws IOException
{
return inner.write( byteBuffer );
}
@Override
public long write( ByteBuffer[] byteBuffers, int i, int i1 ) throws IOException
{
return inner.write( byteBuffers, i, i1 );
}
@Override
public long write( ByteBuffer[] srcs ) throws IOException
{
return inner.write( srcs );
}
@Override
public long position() throws IOException
{
return inner.position();
}
@Override
public BreakableFileChannel position( long l ) throws IOException
{
inner.position( l );
return this;
}
@Override
public long size() throws IOException
{
return inner.size();
}
@Override
public BreakableFileChannel truncate( long l ) throws IOException
{
inner.truncate( l );
return this;
}
@Override
public void force( boolean b ) throws IOException
{
inner.force( b );
}
@Override
public int read( ByteBuffer byteBuffer, long l ) throws IOException
{
return inner.read( byteBuffer, l );
}
@Override
public FileLock tryLock() throws IOException
{
return inner.tryLock();
}
@Override
public int write( ByteBuffer byteBuffer, long l ) throws IOException
{
int writtenInThisCall = 0;
for ( int i = 0; i < byteBuffer.limit(); i++ )
{
fs.checkOperation( BreakableFileSystemAbstraction.OperationType.WRITE, theFile, bytesWritten, 1, inner.position() );
ByteBuffer toWrite = byteBuffer.slice();
toWrite.limit( 1 );
inner.write( toWrite, l + writtenInThisCall );
byteBuffer.get();
bytesWritten++;
writtenInThisCall++;
}
return writtenInThisCall;
}
@Override
public MappedByteBuffer map( FileChannel.MapMode mode, long position, long size ) throws IOException
{
return inner.map( mode, position, size );
}
@Override
public boolean isOpen()
{
return inner.isOpen();
}
@Override
public void close() throws IOException
{
inner.close();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_mockfs_BreakableFileChannel.java
|
3,438
|
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
fail( "we did not create the node, so it should not be initialized" );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_index_UniqueFactoryTest.java
|
3,439
|
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
initializeCalled.set( true );
assertEquals( Collections.singletonMap( "key1", "value1" ), properties );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_index_UniqueFactoryTest.java
|
3,440
|
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
initializeCalled.set( true );
assertEquals( Collections.singletonMap( "key1", "value1" ), properties );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_index_UniqueFactoryTest.java
|
3,441
|
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
fail( "we did not create the node, so it should not be initialized" );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_index_UniqueFactoryTest.java
|
3,442
|
@Ignore
public class UniqueFactoryTest
{
@Test
public void shouldUseConcurrentlyCreatedNode()
{
// given
GraphDatabaseService graphdb = mock( GraphDatabaseService.class );
@SuppressWarnings( "unchecked" )
Index<Node> index = mock( Index.class );
Transaction tx = mock( Transaction.class );
when( graphdb.beginTx() ).thenReturn( tx );
when( index.getGraphDatabase() ).thenReturn( graphdb );
@SuppressWarnings( "unchecked" )
IndexHits<Node> getHits = mock( IndexHits.class );
when( index.get( "key1", "value1" ) ).thenReturn( getHits );
Node createdNode = mock( Node.class );
when( graphdb.createNode() ).thenReturn( createdNode );
Node concurrentNode = mock( Node.class );
when( index.putIfAbsent( createdNode, "key1", "value1" ) ).thenReturn( concurrentNode );
UniqueFactory.UniqueNodeFactory unique = new UniqueFactory.UniqueNodeFactory( index )
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
fail( "we did not create the node, so it should not be initialized" );
}
};
// when
UniqueEntity<Node> node = unique.getOrCreateWithOutcome( "key1", "value1" );
// then
assertSame(node.entity(), concurrentNode);
assertFalse( node.wasCreated() );
verify( index ).get( "key1", "value1" );
verify( index ).putIfAbsent( createdNode, "key1", "value1" );
verify( graphdb, times( 1 ) ).createNode();
verify( tx ).success();
}
@Test
public void shouldCreateNodeAndIndexItIfMissing()
{
// given
GraphDatabaseService graphdb = mock( GraphDatabaseService.class );
@SuppressWarnings( "unchecked" )
Index<Node> index = mock( Index.class );
Transaction tx = mock( Transaction.class );
when( graphdb.beginTx() ).thenReturn( tx );
when( index.getGraphDatabase() ).thenReturn( graphdb );
@SuppressWarnings( "unchecked" )
IndexHits<Node> indexHits = mock( IndexHits.class );
when( index.get( "key1", "value1" ) ).thenReturn( indexHits );
Node indexedNode = mock( Node.class );
when( graphdb.createNode() ).thenReturn( indexedNode );
final AtomicBoolean initializeCalled = new AtomicBoolean( false );
UniqueFactory.UniqueNodeFactory unique = new UniqueFactory.UniqueNodeFactory( index )
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
initializeCalled.set( true );
assertEquals( Collections.singletonMap( "key1", "value1" ), properties );
}
};
// when
Node node = unique.getOrCreate( "key1", "value1" );
// then
assertSame(node, indexedNode);
verify( index ).get( "key1", "value1" );
verify( index ).putIfAbsent( indexedNode, "key1", "value1" );
verify( graphdb, times( 1 ) ).createNode();
verify( tx ).success();
assertTrue( "Node not initialized", initializeCalled.get() );
}
@Test
public void shouldCreateNodeWithOutcomeAndIndexItIfMissing()
{
// given
GraphDatabaseService graphdb = mock( GraphDatabaseService.class );
@SuppressWarnings( "unchecked" )
Index<Node> index = mock( Index.class );
Transaction tx = mock( Transaction.class );
when( graphdb.beginTx() ).thenReturn( tx );
when( index.getGraphDatabase() ).thenReturn( graphdb );
@SuppressWarnings( "unchecked" )
IndexHits<Node> indexHits = mock( IndexHits.class );
when( index.get( "key1", "value1" ) ).thenReturn( indexHits );
Node indexedNode = mock( Node.class );
when( graphdb.createNode() ).thenReturn( indexedNode );
final AtomicBoolean initializeCalled = new AtomicBoolean( false );
UniqueFactory.UniqueNodeFactory unique = new UniqueFactory.UniqueNodeFactory( index )
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
initializeCalled.set( true );
assertEquals( Collections.singletonMap( "key1", "value1" ), properties );
}
};
// when
UniqueEntity<Node> node = unique.getOrCreateWithOutcome( "key1", "value1" );
// then
assertSame(node.entity(), indexedNode);
assertTrue( node.wasCreated() );
verify( index ).get( "key1", "value1" );
verify( index ).putIfAbsent( indexedNode, "key1", "value1" );
verify( graphdb, times( 1 ) ).createNode();
verify( tx ).success();
assertTrue( "Node not initialized", initializeCalled.get() );
}
@Test
public void shouldNotTouchTransactionsIfAlreadyInIndex()
{
GraphDatabaseService graphdb = mock( GraphDatabaseService.class );
@SuppressWarnings( "unchecked" )
Index<Node> index = mock( Index.class );
when( index.getGraphDatabase() ).thenReturn( graphdb );
@SuppressWarnings( "unchecked" )
IndexHits<Node> getHits = mock( IndexHits.class );
when( index.get( "key1", "value1" ) ).thenReturn( getHits );
Node indexedNode = mock( Node.class );
when( getHits.getSingle() ).thenReturn( indexedNode );
UniqueFactory.UniqueNodeFactory unique = new UniqueFactory.UniqueNodeFactory( index )
{
@Override
protected void initialize( Node created, Map<String, Object> properties )
{
fail( "we did not create the node, so it should not be initialized" );
}
};
// when
Node node = unique.getOrCreate( "key1", "value1" );
// then
assertSame( node, indexedNode );
verify( index ).get( "key1", "value1" );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_index_UniqueFactoryTest.java
|
3,443
|
public static abstract class UniqueRelationshipFactory extends UniqueFactory<Relationship>
{
/**
* Create a new {@link UniqueFactory} for relationships.
*
* @param index the index to store entities uniquely in.
*/
public UniqueRelationshipFactory( Index<Relationship> index )
{
super( index );
}
/**
* Create a new {@link UniqueFactory} for relationships.
*
* @param graphdb the graph database to get the index from.
* @param index the name of the index to store entities uniquely in.
*/
public UniqueRelationshipFactory( GraphDatabaseService graphdb, String index )
{
super( graphdb.index().forRelationships( index ) );
}
/**
* Default implementation of {@link UniqueFactory#initialize(PropertyContainer, Map)}, does nothing
* for {@link Relationship Relationships}. Override to perform some action with the guarantee that this method
* is only invoked for the transaction that succeeded in creating the {@link Relationship}.
*
* @see UniqueFactory#initialize(PropertyContainer, Map)
* @see UniqueFactory#create(Map)
*/
@Override
protected void initialize( Relationship relationship, Map<String, Object> properties )
{
// this class has the create() method, initialize() is optional
}
/**
* Default implementation of {@link UniqueFactory#delete(PropertyContainer)}. Invokes
* {@link Relationship#delete()}.
*
* @see UniqueFactory#delete(PropertyContainer)
*/
@Override
protected void delete( Relationship relationship )
{
relationship.delete();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_index_UniqueFactory.java
|
3,444
|
public static abstract class UniqueNodeFactory extends UniqueFactory<Node>
{
/**
* Create a new {@link UniqueFactory} for nodes.
*
* @param index the index to store entities uniquely in.
*/
public UniqueNodeFactory( Index<Node> index )
{
super( index );
}
/**
* Create a new {@link UniqueFactory} for nodes.
*
* @param graphdb the graph database to get the index from.
* @param index the name of the index to store entities uniquely in.
*/
public UniqueNodeFactory( GraphDatabaseService graphdb, String index )
{
super( graphdb.index().forNodes( index ) );
}
/**
* Default implementation of {@link UniqueFactory#create(Map)}, creates a plain node. Override to
* retrieve the node to add to the index by some other means than by creating it. For initialization of the
* {@link Node}, use the {@link UniqueFactory#initialize(PropertyContainer, Map)} method.
*
* @see UniqueFactory#create(Map)
* @see UniqueFactory#initialize(PropertyContainer, Map)
*/
@Override
protected Node create( Map<String, Object> properties )
{
return graphDatabase().createNode();
}
/**
* Default implementation of {@link UniqueFactory#delete(PropertyContainer)}. Invokes
* {@link Node#delete()}.
*
* @see UniqueFactory#delete(PropertyContainer)
*/
@Override
protected void delete( Node node )
{
node.delete();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_index_UniqueFactory.java
|
3,445
|
public static class UniqueEntity<T extends PropertyContainer>
{
private final T entity;
private final boolean created;
UniqueEntity( T entity, boolean created )
{
this.entity = entity;
this.created = created;
}
public T entity()
{
return this.entity;
}
public boolean wasCreated()
{
return this.created;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_index_UniqueFactory.java
|
3,446
|
public abstract class UniqueFactory<T extends PropertyContainer>
{
public static class UniqueEntity<T extends PropertyContainer>
{
private final T entity;
private final boolean created;
UniqueEntity( T entity, boolean created )
{
this.entity = entity;
this.created = created;
}
public T entity()
{
return this.entity;
}
public boolean wasCreated()
{
return this.created;
}
}
/**
* Implementation of {@link UniqueFactory} for {@link Node}.
*
* @author Tobias Lindaaker <tobias.lindaaker@neotechnology.com>
*/
public static abstract class UniqueNodeFactory extends UniqueFactory<Node>
{
/**
* Create a new {@link UniqueFactory} for nodes.
*
* @param index the index to store entities uniquely in.
*/
public UniqueNodeFactory( Index<Node> index )
{
super( index );
}
/**
* Create a new {@link UniqueFactory} for nodes.
*
* @param graphdb the graph database to get the index from.
* @param index the name of the index to store entities uniquely in.
*/
public UniqueNodeFactory( GraphDatabaseService graphdb, String index )
{
super( graphdb.index().forNodes( index ) );
}
/**
* Default implementation of {@link UniqueFactory#create(Map)}, creates a plain node. Override to
* retrieve the node to add to the index by some other means than by creating it. For initialization of the
* {@link Node}, use the {@link UniqueFactory#initialize(PropertyContainer, Map)} method.
*
* @see UniqueFactory#create(Map)
* @see UniqueFactory#initialize(PropertyContainer, Map)
*/
@Override
protected Node create( Map<String, Object> properties )
{
return graphDatabase().createNode();
}
/**
* Default implementation of {@link UniqueFactory#delete(PropertyContainer)}. Invokes
* {@link Node#delete()}.
*
* @see UniqueFactory#delete(PropertyContainer)
*/
@Override
protected void delete( Node node )
{
node.delete();
}
}
/**
* Implementation of {@link UniqueFactory} for {@link Relationship}.
*
* @author Tobias Lindaaker <tobias.lindaaker@neotechnology.com>
*/
public static abstract class UniqueRelationshipFactory extends UniqueFactory<Relationship>
{
/**
* Create a new {@link UniqueFactory} for relationships.
*
* @param index the index to store entities uniquely in.
*/
public UniqueRelationshipFactory( Index<Relationship> index )
{
super( index );
}
/**
* Create a new {@link UniqueFactory} for relationships.
*
* @param graphdb the graph database to get the index from.
* @param index the name of the index to store entities uniquely in.
*/
public UniqueRelationshipFactory( GraphDatabaseService graphdb, String index )
{
super( graphdb.index().forRelationships( index ) );
}
/**
* Default implementation of {@link UniqueFactory#initialize(PropertyContainer, Map)}, does nothing
* for {@link Relationship Relationships}. Override to perform some action with the guarantee that this method
* is only invoked for the transaction that succeeded in creating the {@link Relationship}.
*
* @see UniqueFactory#initialize(PropertyContainer, Map)
* @see UniqueFactory#create(Map)
*/
@Override
protected void initialize( Relationship relationship, Map<String, Object> properties )
{
// this class has the create() method, initialize() is optional
}
/**
* Default implementation of {@link UniqueFactory#delete(PropertyContainer)}. Invokes
* {@link Relationship#delete()}.
*
* @see UniqueFactory#delete(PropertyContainer)
*/
@Override
protected void delete( Relationship relationship )
{
relationship.delete();
}
}
/**
* Implement this method to create the {@link Node} or {@link Relationship} to index.
*
* This method will be invoked exactly once per transaction that attempts to create an entry in the index.
* The created entity might be discarded if another thread creates an entity with the same mapping concurrently.
*
* @param properties the properties that this entity will is to be indexed uniquely with.
* @return the entity to add to the index.
*/
protected abstract T create( Map<String, Object> properties );
/**
* Implement this method to initialize the {@link Node} or {@link Relationship} created for being stored in the index.
*
* This method will be invoked exactly once per created unique entity.
*
* The created entity might be discarded if another thread creates an entity concurrently.
* This method will however only be invoked in the transaction that succeeds in creating the node.
*
* @param created the created entity to initialize.
* @param properties the properties that this entity was indexed uniquely with.
*/
protected abstract void initialize( T created, Map<String, Object> properties );
/**
* Invoked after a new entity has been {@link #create(Map) created}, but adding it to the index failed (due to being
* added by another transaction concurrently). The purpose of this method is to undo the {@link #create(Map)
* creation of the entity}, the default implementations of this method remove the entity. Override this method to
* define a different behavior.
*
* @param created the entity that was created but was not added to the index.
*/
protected abstract void delete( T created );
/**
* Get the indexed entity, creating it (exactly once) if no indexed entity exists.
* @param key the key to find the entity under in the index.
* @param value the value the key is mapped to for the entity in the index.
* @return the unique entity in the index.
*/
public final T getOrCreate( String key, Object value )
{
return getOrCreateWithOutcome( key, value ).entity();
}
/**
* Get the indexed entity, creating it (exactly once) if no indexed entity exists.
* Includes the outcome, i.e. whether the entity was created or not.
* @param key the key to find the entity under in the index.
* @param value the value the key is mapped to for the entity in the index.
* @return the unique entity in the index as well as whether or not it was created,
* wrapped in a {@link UniqueEntity}.
*/
public final UniqueEntity<T> getOrCreateWithOutcome( String key, Object value )
{
// Index reads implies asserting we're in a transaction.
T result = index.get( key, value ).getSingle();
boolean wasCreated = false;
if ( result == null )
{
try ( Transaction tx = graphDatabase().beginTx() )
{
Map<String, Object> properties = Collections.singletonMap( key, value );
T created = create( properties );
result = index.putIfAbsent( created, key, value );
if ( result == null )
{
initialize( created, properties );
result = created;
wasCreated = true;
}
else
{
delete( created );
}
tx.success();
}
}
return new UniqueEntity<>( result, wasCreated );
}
/**
* Get the {@link GraphDatabaseService graph database} of the referenced index.
* @return the {@link GraphDatabaseService graph database} of the referenced index.
*/
protected final GraphDatabaseService graphDatabase()
{
return index.getGraphDatabase();
}
/**
* Get the referenced index.
* @return the referenced index.
*/
protected final Index<T> index()
{
return index;
}
private final Index<T> index;
private UniqueFactory( Index<T> index )
{
this.index = index;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_index_UniqueFactory.java
|
3,447
|
public class SettingsResourceBundle
extends ResourceBundle
{
private final Class settingsClass;
public SettingsResourceBundle( Class settingsClass )
{
this.settingsClass = settingsClass;
}
@Override
protected Object handleGetObject( String key )
{
if ( key.equals( "description" ) )
{
Description description = (Description) settingsClass.getAnnotation( Description.class );
return description.value();
}
String name = key.substring( 0, key.lastIndexOf( "." ) );
if ( key.endsWith( ".description" ) )
{
Field settingField = getField( name );
return settingField.getAnnotation( Description.class ).value();
}
if ( key.endsWith( ".title" ) )
{
Field settingField = getField( name );
@SuppressWarnings("deprecation")
Title annotation = settingField.getAnnotation( Title.class );
if ( annotation != null )
{
return annotation.value();
}
else
{
// read_only -> Read only
name = name.replace( '_', ' ' );
name = name.substring( 0, 1 ).toUpperCase() + name.substring( 1 );
return name;
}
}
if ( key.endsWith( ".default" ) )
{
try
{
return getFieldValue( name ).apply( Functions.<String, String>nullFunction() ).toString();
}
catch ( Exception e )
{
// Ignore
}
}
throw new IllegalResourceException( "Could not find resource for property " + key );
}
private Setting<?> getFieldValue( String name ) throws IllegalAccessException
{
return (Setting<?>) getField( name ).get( null );
}
private Field getField( String name )
{
for ( Field field : settingsClass.getFields() )
{
if ( Setting.class.isAssignableFrom( field.getType() ) )
{
try
{
Setting setting = (Setting) field.get( null );
if ( setting.name().equals( name ) )
{
return field;
}
}
catch ( Exception e )
{
// Ignore
}
}
}
throw new IllegalResourceException( "Could not find resource for property with prefix " + name );
}
@Override
public Enumeration<String> getKeys()
{
return Collections.enumeration( keySet() );
}
@Override
public Set<String> keySet()
{
Set<String> keys = new LinkedHashSet<String>();
{
Description description = (Description) settingsClass.getAnnotation( Description.class );
if ( description != null )
{
keys.add( "description" );
}
}
for ( Field field : settingsClass.getFields() )
{
try
{
Setting<?> setting = (Setting<?>) field.get( null );
if ( field.getAnnotation( Description.class ) != null )
{
keys.add( setting.name() + ".description" );
if ( setting.apply( Functions.<String, String>nullFunction() ) != null )
{
keys.add( setting.name() + ".default" );
}
}
}
catch ( Exception e )
{
// Ignore
}
}
return keys;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_SettingsResourceBundle.java
|
3,448
|
public class SetCacheProvidersTest
{
@Test
public void testSetNoCache()
{
ArrayList<CacheProvider> cacheList = new ArrayList<>();
TestGraphDatabaseFactory gdbf = new TestGraphDatabaseFactory();
gdbf.setCacheProviders( cacheList );
try
{
gdbf.newImpermanentDatabase();
}
catch ( IllegalArgumentException iae )
{
assertTrue( iae.getMessage().contains( "No provider for cache type" ) );
assertTrue( iae.getMessage().contains( "register" ) );
assertTrue( iae.getMessage().contains( "missing" ) );
}
}
@Test
public void testSetSoftRefCache()
{
ArrayList<CacheProvider> cacheList = new ArrayList<>();
TestGraphDatabaseFactory gdbf = new TestGraphDatabaseFactory();
cacheList.add( new SoftCacheProvider() );
gdbf.setCacheProviders( cacheList );
GraphDatabaseAPI db = (GraphDatabaseAPI) gdbf.newImpermanentDatabase();
assertEquals( SoftCacheProvider.NAME, db.getDependencyResolver().resolveDependency( NodeManager.class )
.getCacheType().getName() );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_factory_SetCacheProvidersTest.java
|
3,449
|
{
@Override
public GraphDatabaseService newDatabase( Map<String, String> config )
{
config.put( "ephemeral", "false" );
return new HighlyAvailableGraphDatabase( path, config, state.databaseDependencies() );
}
} );
| false
|
enterprise_ha_src_main_java_org_neo4j_graphdb_factory_HighlyAvailableGraphDatabaseFactory.java
|
3,450
|
public class HighlyAvailableGraphDatabaseFactory extends GraphDatabaseFactory
{
public GraphDatabaseService newHighlyAvailableDatabase( String path )
{
return newEmbeddedDatabaseBuilder( path ).newGraphDatabase();
}
public GraphDatabaseBuilder newHighlyAvailableDatabaseBuilder( final String path )
{
final GraphDatabaseFactoryState state = getStateCopy();
return new GraphDatabaseBuilder( new GraphDatabaseBuilder.DatabaseCreator()
{
@Override
public GraphDatabaseService newDatabase( Map<String, String> config )
{
config.put( "ephemeral", "false" );
return new HighlyAvailableGraphDatabase( path, config, state.databaseDependencies() );
}
} );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_graphdb_factory_HighlyAvailableGraphDatabaseFactory.java
|
3,451
|
STANDARD
{
@Override
public BranchCollisionDetector create( Evaluator evaluator )
{
return new StandardBranchCollisionDetector( evaluator );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchCollisionPolicies.java
|
3,452
|
PREORDER_DEPTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return new PreorderDepthFirstSelector( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchOrderingPolicies.java
|
3,453
|
{
@Override
public void call( Relationship relationship )
{
for ( String key : relationship.getPropertyKeys() )
{
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,454
|
POSTORDER_DEPTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return new PostorderDepthFirstSelector( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchOrderingPolicies.java
|
3,455
|
class GloballyUnique extends AbstractUniquenessFilter
{
private final Set<Long> visited = new HashSet<Long>();
GloballyUnique( PrimitiveTypeFetcher type )
{
super( type );
}
public boolean check( TraversalBranch branch )
{
return visited.add( type.getId( branch ) );
}
@Override
public boolean checkFull( Path path )
{
// Since this is for bidirectional uniqueness checks and
// uniqueness is enforced through the shared "visited" set
// this uniqueness contract is fulfilled automatically.
return true;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_GloballyUnique.java
|
3,456
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
return endNodes.contains( path.endNode() ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,457
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
return target.equals( path.endNode() ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,458
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Relationship lastRelationship = path.lastRelationship();
if ( lastRelationship == null )
{
return evaluationIfNoMatch;
}
return expectedTypes.contains( lastRelationship.getType().name() ) ?
evaluationIfMatch : evaluationIfNoMatch;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,459
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Relationship rel = path.lastRelationship();
return rel != null && rel.isType( type ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,460
|
{
public Evaluation evaluate( Path path, BranchState state )
{
int length = path.length();
return Evaluation.of( length >= minDepth && length <= maxDepth, length < maxDepth );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,461
|
{
public Evaluation evaluate( Path path, BranchState state )
{
return path.length() == depth ? Evaluation.INCLUDE_AND_PRUNE : Evaluation.EXCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,462
|
{
public Evaluation evaluate( Path path, BranchState state )
{
return Evaluation.ofIncludes( path.length() >= depth );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,463
|
{
public Evaluation evaluate( Path path, BranchState state )
{
int pathLength = path.length();
return Evaluation.of( pathLength <= depth, pathLength < depth );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,464
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( Evaluator evaluator : evaluators )
{
if ( evaluator.evaluate( path ).includes() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,465
|
{
@SuppressWarnings( "unchecked" )
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( PathEvaluator evaluator : evaluators )
{
if ( evaluator.evaluate( path, state ).includes() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,466
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Set<Node> set = new HashSet<Node>( fullSet );
for ( Node node : path.reverseNodes() )
{
if ( set.remove( node ) && set.isEmpty() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,467
|
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( Node node : path.reverseNodes() )
{
if ( node.equals( nodes[0] ) )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,468
|
{
public Evaluation evaluate( Path path, BranchState state )
{
return INCLUDE_AND_CONTINUE;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,469
|
public abstract class Evaluators
{
@SuppressWarnings( "rawtypes" )
private static final PathEvaluator ALL = new PathEvaluator.Adapter()
{
public Evaluation evaluate( Path path, BranchState state )
{
return INCLUDE_AND_CONTINUE;
}
};
@SuppressWarnings( "rawtypes" )
private static final PathEvaluator ALL_BUT_START_POSITION = fromDepth( 1 );
/**
* @return an evaluator which includes everything it encounters and doesn't prune
* anything.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator all()
{
return ALL;
}
/**
* @return an evaluator which never prunes and includes everything except
* the first position, i.e. the the start node.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator excludeStartPosition()
{
return ALL_BUT_START_POSITION;
}
/**
* Returns an {@link Evaluator} which includes positions down to {@code depth}
* and prunes everything deeper than that.
*
* @param depth the max depth to traverse to.
* @return Returns an {@link Evaluator} which includes positions down to
* {@code depth} and prunes everything deeper than that.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator toDepth( final int depth )
{
return new PathEvaluator.Adapter()
{
public Evaluation evaluate( Path path, BranchState state )
{
int pathLength = path.length();
return Evaluation.of( pathLength <= depth, pathLength < depth );
}
};
}
/**
* Returns an {@link Evaluator} which only includes positions from {@code depth}
* and deeper and never prunes anything.
*
* @param depth the depth to start include positions from.
* @return Returns an {@link Evaluator} which only includes positions from
* {@code depth} and deeper and never prunes anything.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator fromDepth( final int depth )
{
return new PathEvaluator.Adapter()
{
public Evaluation evaluate( Path path, BranchState state )
{
return Evaluation.ofIncludes( path.length() >= depth );
}
};
}
/**
* Returns an {@link Evaluator} which only includes positions at {@code depth}
* and prunes everything deeper than that.
*
* @param depth the depth to start include positions from.
* @return Returns an {@link Evaluator} which only includes positions at
* {@code depth} and prunes everything deeper than that.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator atDepth( final int depth )
{
return new PathEvaluator.Adapter()
{
public Evaluation evaluate( Path path, BranchState state )
{
return path.length() == depth ? Evaluation.INCLUDE_AND_PRUNE : Evaluation.EXCLUDE_AND_CONTINUE;
}
};
}
/**
* Returns an {@link Evaluator} which only includes positions between
* depths {@code minDepth} and {@code maxDepth}. It prunes everything deeper
* than {@code maxDepth}.
*
* @param minDepth minimum depth a position must have to be included.
* @param maxDepth maximum depth a position must have to be included.
* @return Returns an {@link Evaluator} which only includes positions between
* depths {@code minDepth} and {@code maxDepth}. It prunes everything deeper
* than {@code maxDepth}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includingDepths( final int minDepth, final int maxDepth )
{
return new PathEvaluator.Adapter()
{
public Evaluation evaluate( Path path, BranchState state )
{
int length = path.length();
return Evaluation.of( length >= minDepth && length <= maxDepth, length < maxDepth );
}
};
}
/**
* Returns an {@link Evaluator} which compares the type of the last relationship
* in a {@link Path} to a given set of relationship types (one or more).If the type of
* the last relationship in a path is of one of the given types then
* {@code evaluationIfMatch} will be returned, otherwise
* {@code evaluationIfNoMatch} will be returned.
*
* @param evaluationIfMatch the {@link Evaluation} to return if the type of the
* last relationship in the path matches any of the given types.
* @param evaluationIfNoMatch the {@link Evaluation} to return if the type of the
* last relationship in the path doesn't match any of the given types.
* @param type the (first) type (of possibly many) to match the last relationship
* in paths with.
* @param orAnyOfTheseTypes additional types to match the last relationship in
* paths with.
* @return an {@link Evaluator} which compares the type of the last relationship
* in a {@link Path} to a given set of relationship types.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator lastRelationshipTypeIs( final Evaluation evaluationIfMatch,
final Evaluation evaluationIfNoMatch, final RelationshipType type, RelationshipType... orAnyOfTheseTypes )
{
if ( orAnyOfTheseTypes.length == 0 )
{
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Relationship rel = path.lastRelationship();
return rel != null && rel.isType( type ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
}
final Set<String> expectedTypes = new HashSet<String>();
expectedTypes.add( type.name() );
for ( RelationshipType otherType : orAnyOfTheseTypes )
{
expectedTypes.add( otherType.name() );
}
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Relationship lastRelationship = path.lastRelationship();
if ( lastRelationship == null )
{
return evaluationIfNoMatch;
}
return expectedTypes.contains( lastRelationship.getType().name() ) ?
evaluationIfMatch : evaluationIfNoMatch;
}
};
}
/**
* @deprecated use {@link #includeWhereLastRelationshipTypeIs(RelationshipType, RelationshipType...)}
*/
public static Evaluator returnWhereLastRelationshipTypeIs( RelationshipType type,
RelationshipType... orAnyOfTheseTypes )
{
return includeWhereLastRelationshipTypeIs( type, orAnyOfTheseTypes );
}
/**
* @param type the (first) type (of possibly many) to match the last relationship
* in paths with.
* @param orAnyOfTheseTypes types to match the last relationship in paths with. If any matches
* it's considered a match.
* @return an {@link Evaluator} which compares the type of the last relationship
* in a {@link Path} to a given set of relationship types.
* @see #lastRelationshipTypeIs(Evaluation, Evaluation, RelationshipType, RelationshipType...).
* Uses {@link Evaluation#INCLUDE_AND_CONTINUE} for {@code evaluationIfMatch}
* and {@link Evaluation#EXCLUDE_AND_CONTINUE} for {@code evaluationIfNoMatch}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includeWhereLastRelationshipTypeIs( RelationshipType type,
RelationshipType... orAnyOfTheseTypes )
{
return lastRelationshipTypeIs( Evaluation.INCLUDE_AND_CONTINUE, Evaluation.EXCLUDE_AND_CONTINUE,
type, orAnyOfTheseTypes );
}
/**
* @param type the (first) type (of possibly many) to match the last relationship
* in paths with.
* @param orAnyOfTheseTypes types to match the last relationship in paths with. If any matches
* it's considered a match.
* @return an {@link Evaluator} which compares the type of the last relationship
* in a {@link Path} to a given set of relationship types.
* @see #lastRelationshipTypeIs(Evaluation, Evaluation, RelationshipType, RelationshipType...).
* Uses {@link Evaluation#INCLUDE_AND_PRUNE} for {@code evaluationIfMatch}
* and {@link Evaluation#INCLUDE_AND_CONTINUE} for {@code evaluationIfNoMatch}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator pruneWhereLastRelationshipTypeIs( RelationshipType type,
RelationshipType... orAnyOfTheseTypes )
{
return lastRelationshipTypeIs( Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE,
type, orAnyOfTheseTypes );
}
/**
* An {@link Evaluator} which will return {@code evaluationIfMatch} if {@link Path#endNode()}
* for a given path is any of {@code nodes}, else {@code evaluationIfNoMatch}.
*
* @param evaluationIfMatch the {@link Evaluation} to return if the {@link Path#endNode()}
* is any of the nodes in {@code nodes}.
* @param evaluationIfNoMatch the {@link Evaluation} to return if the {@link Path#endNode()}
* doesn't match any of the nodes in {@code nodes}.
* @param possibleEndNodes a set of nodes to match to end nodes in paths.
* @return an {@link Evaluator} which will return {@code evaluationIfMatch} if
* {@link Path#endNode()} for a given path is any of {@code nodes},
* else {@code evaluationIfNoMatch}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator endNodeIs( final Evaluation evaluationIfMatch, final Evaluation evaluationIfNoMatch,
Node... possibleEndNodes )
{
if ( possibleEndNodes.length == 1 )
{
final Node target = possibleEndNodes[0];
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
return target.equals( path.endNode() ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
}
final Set<Node> endNodes = new HashSet<Node>( asList( possibleEndNodes ) );
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
return endNodes.contains( path.endNode() ) ? evaluationIfMatch : evaluationIfNoMatch;
}
};
}
/**
* @deprecated use {@link #includeWhereEndNodeIs(Node...)}
*/
public static Evaluator returnWhereEndNodeIs( Node... nodes )
{
return includeWhereEndNodeIs( nodes );
}
/**
* @param nodes end nodes for paths to be included in the result.
* @see this#endNodeIs(Evaluation, Evaluation, Node...), uses
* {@link Evaluation#INCLUDE_AND_CONTINUE} for
* {@code evaluationIfMatch} and
* {@link Evaluation#EXCLUDE_AND_CONTINUE} for
* {@code evaluationIfNoMatch}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includeWhereEndNodeIs( Node... nodes )
{
return endNodeIs( Evaluation.INCLUDE_AND_CONTINUE, Evaluation.EXCLUDE_AND_CONTINUE, nodes );
}
@SuppressWarnings( "rawtypes" )
public static PathEvaluator pruneWhereEndNodeIs( Node... nodes )
{
return endNodeIs( Evaluation.INCLUDE_AND_PRUNE, Evaluation.EXCLUDE_AND_CONTINUE, nodes );
}
/**
* Evaluator which decides to include a {@link Path} if all the
* {@code nodes} exist in it.
*
* @param nodes {@link Node}s that must exist in a {@link Path} for it
* to be included.
* @return {@link Evaluation#INCLUDE_AND_CONTINUE} if all {@code nodes}
* exist in a given {@link Path}, otherwise
* {@link Evaluation#EXCLUDE_AND_CONTINUE}.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includeIfContainsAll( final Node... nodes )
{
if ( nodes.length == 1 )
{
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( Node node : path.reverseNodes() )
{
if ( node.equals( nodes[0] ) )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
}
else
{
final Set<Node> fullSet = new HashSet<Node>( asList( nodes ) );
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
Set<Node> set = new HashSet<Node>( fullSet );
for ( Node node : path.reverseNodes() )
{
if ( set.remove( node ) && set.isEmpty() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
}
}
/**
* Whereas adding {@link Evaluator}s to a {@link TraversalDescription} puts those
* evaluators in {@code AND-mode} this can group many evaluators in {@code OR-mode}.
*
* @param evaluators represented as one evaluators. If any of the evaluators decides
* to include a path it will be included.
* @return an {@link Evaluator} which decides to include a path if any of the supplied
* evaluators wants to include it.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includeIfAcceptedByAny( final PathEvaluator... evaluators )
{
return new PathEvaluator.Adapter()
{
@SuppressWarnings( "unchecked" )
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( PathEvaluator evaluator : evaluators )
{
if ( evaluator.evaluate( path, state ).includes() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
}
/**
* Whereas adding {@link Evaluator}s to a {@link TraversalDescription} puts those
* evaluators in {@code AND-mode} this can group many evaluators in {@code OR-mode}.
*
* @param evaluators represented as one evaluators. If any of the evaluators decides
* to include a path it will be included.
* @return an {@link Evaluator} which decides to include a path if any of the supplied
* evaluators wants to include it.
*/
@SuppressWarnings( "rawtypes" )
public static PathEvaluator includeIfAcceptedByAny( final Evaluator... evaluators )
{
return new PathEvaluator.Adapter()
{
@Override
public Evaluation evaluate( Path path, BranchState state )
{
for ( Evaluator evaluator : evaluators )
{
if ( evaluator.evaluate( path ).includes() )
{
return Evaluation.INCLUDE_AND_CONTINUE;
}
}
return Evaluation.EXCLUDE_AND_CONTINUE;
}
};
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluators.java
|
3,470
|
class AsPathEvaluator<STATE> implements PathEvaluator<STATE>
{
private final Evaluator evaluator;
public AsPathEvaluator( Evaluator evaluator )
{
this.evaluator = evaluator;
}
@Override
public Evaluation evaluate( Path path, BranchState<STATE> state )
{
return evaluator.evaluate( path );
}
@Override
public Evaluation evaluate( Path path )
{
return evaluator.evaluate( path );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Evaluator.java
|
3,471
|
{
@Override
public Object getState()
{
throw new IllegalStateException( "Branch state disabled, pass in an initial state to enable it" );
}
@Override
public void setState( Object state )
{
throw new IllegalStateException( "Branch state disabled, pass in an initial state to enable it" );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchState.java
|
3,472
|
POSTORDER_BREADTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return new PostorderBreadthFirstSelector( startSource, expander );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchOrderingPolicies.java
|
3,473
|
PREORDER_BREADTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return new PreorderBreadthFirstSelector( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_traversal_BranchOrderingPolicies.java
|
3,474
|
public class GraphDatabaseSettingsResourceBundle
extends SettingsResourceBundle
{
public GraphDatabaseSettingsResourceBundle()
{
super( GraphDatabaseSettings.class );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseSettingsResourceBundle.java
|
3,475
|
@Description("Settings for the Community edition of Neo4j")
public abstract class GraphDatabaseSettings
{
@Migrator
private static final ConfigurationMigrator migrator = new GraphDatabaseConfigurationMigrator();
@Title("Read only database")
@Description("Only allow read operations from this Neo4j instance. This mode still requires write access to the directory for lock purposes")
public static final Setting<Boolean> read_only = setting( "read_only", BOOLEAN, FALSE );
@Description("The type of cache to use for nodes and relationships. "
+ "Note that the Neo4j Enterprise Edition has the additional 'hpc' cache type (High-Performance Cache). "
+ "See the chapter on caches in the manual for more information.")
public static final Setting<String> cache_type = setting( "cache_type", options( availableCaches() ), availableCaches()[0] );
@Description("Print out the effective Neo4j configuration after startup.")
public static final Setting<Boolean> dump_configuration = setting("dump_configuration", BOOLEAN, FALSE );
@Description("The name of the Transaction Manager service to use as defined in the TM service provider " +
"constructor.")
public static final Setting<String> tx_manager_impl = setting("tx_manager_impl", STRING, "native",
illegalValueMessage( "Must be class name of TransactionManager implementation", matches( ANY )));
@Description("Whether to allow a store upgrade in case the current version of the database starts against an " +
"older store version. " +
"Setting this to true does not guarantee successful upgrade, just " +
"that it allows an attempt at it.")
public static final Setting<Boolean> allow_store_upgrade = setting("allow_store_upgrade", BOOLEAN, FALSE );
@Description("Determines whether any TransactionInterceptors loaded will intercept " +
"externally received transactions (e.g. in HA) before they reach the " +
"logical log and are applied to the store.")
public static final Setting<Boolean> intercept_deserialized_transactions = setting("intercept_deserialized_transactions", BOOLEAN, FALSE);
// Cypher settings
// TODO: These should live with cypher
@Description("Enable this to specify a parser other than the default one.")
public static final Setting<String> cypher_parser_version = setting(
"cypher_parser_version",
options( "1.9", "2.0" ), NO_DEFAULT );
@Description("Used to set the number of Cypher query execution plans that are cached.")
public static Setting<Integer> query_cache_size = setting( "query_cache_size", INTEGER, "100", min( 0 ) );
// Store files
@Description("The directory where the database files are located.")
public static final Setting<File> store_dir = setting("store_dir", PATH, NO_DEFAULT );
@Description("The base name for the Neo4j Store files, either an absolute path or relative to the store_dir " +
"setting. This should generally not be changed.")
public static final Setting<File> neo_store = setting("neo_store", PATH, "neostore", basePath(store_dir) );
@Description("The base name for the logical log files, either an absolute path or relative to the store_dir " +
"setting. This should generally not be changed.")
public static final Setting<File> logical_log = setting("logical_log", PATH, "nioneo_logical.log", basePath(store_dir));
// Remote logging
@Description("Whether to enable logging to a remote server or not.")
public static final Setting<Boolean> remote_logging_enabled = setting("remote_logging_enabled", BOOLEAN, FALSE );
@Description("Host for remote logging using LogBack SocketAppender.")
public static final Setting<String> remote_logging_host = setting("remote_logging_host", STRING, "127.0.0.1", illegalValueMessage( "Must be a valid hostname", matches( ANY ) ) );
@Description("Port for remote logging using LogBack SocketAppender.")
public static final Setting<Integer> remote_logging_port = setting("remote_logging_port", INTEGER, "4560", port );
// TODO: Turn this into ByteSizeSetting, and make sure this applies to all logging providers
@Description("Threshold in bytes for when database logs (text logs, for debugging, that is) are rotated.")
public static final Setting<Integer> threshold_for_logging_rotation = setting("logging.threshold_for_rotation", INTEGER, "" + (100 * 1024 * 1024), min(1) );
// Indexing
@Description("Controls the auto indexing feature for nodes. Setting to false shuts it down, " +
"while true enables it by default for properties "
+ "listed in the node_keys_indexable setting.")
public static final Setting<Boolean> node_auto_indexing = setting("node_auto_indexing", BOOLEAN, FALSE);
@Description("A list of property names (comma separated) that will be indexed by default. This applies to Nodes " +
"only.")
public static final Setting<String> node_keys_indexable = setting("node_keys_indexable", STRING, NO_DEFAULT, illegalValueMessage( "Must be a comma-separated list of keys to be indexed", matches( ANY ) ) );
@Description("Controls the auto indexing feature for relationships. Setting to false shuts it down, " +
"while true enables it by default for properties "
+ "listed in the relationship_keys_indexable setting.")
public static final Setting<Boolean> relationship_auto_indexing = setting("relationship_auto_indexing",BOOLEAN, FALSE );
@Description(" A list of property names (comma separated) that will be indexed by default. This applies to " +
"Relationships only.")
public static final Setting<String> relationship_keys_indexable = setting("relationship_keys_indexable", STRING, NO_DEFAULT, illegalValueMessage( "Must be a comma-separated list of keys to be indexed", matches( ANY ) ) );
// Lucene settings
@Description("Integer value that sets the maximum number of open lucene index searchers.")
public static Setting<Integer> lucene_searcher_cache_size = setting("lucene_searcher_cache_size",INTEGER, Integer.toString( Integer.MAX_VALUE ), min( 1 ));
// NeoStore settings
@Description("Determines whether any TransactionInterceptors loaded will intercept prepared transactions before " +
"they reach the logical log.")
public static final Setting<Boolean> intercept_committing_transactions = setting("intercept_committing_transactions", BOOLEAN, FALSE );
@Description("Make Neo4j keep the logical transaction logs for being able to backup the database." +
"Can be used for specifying the threshold to prune logical logs after. For example \"10 days\" will " +
"prune logical logs that only contains transactions older than 10 days from the current time, " +
"or \"100k txs\" will keep the 100k latest transactions and prune any older transactions.")
public static final Setting<String> keep_logical_logs = setting("keep_logical_logs", STRING, "7 days", illegalValueMessage( "Must be 'true'/'false' or of format '<number><optional unit> <type>' for example '100M size' for " +
"limiting logical log space on disk to 100Mb," +
" or '200k txs' for limiting the number of transactions to keep to 200 000.", matches(ANY)));
@Description( "Specifies at which file size the logical log will auto-rotate. " +
"0 means that no rotation will automatically occur based on file size. " +
"Default is 25M" )
public static final Setting<Long> logical_log_rotation_threshold = setting( "logical_log_rotation_threshold", BYTES, "25M" );
@Description("Use a quick approach for rebuilding the ID generators. This give quicker recovery time, " +
"but will limit the ability to reuse the space of deleted entities.")
public static final Setting<Boolean> rebuild_idgenerators_fast = setting("rebuild_idgenerators_fast", BOOLEAN, TRUE );
// NeoStore memory settings
@Description("Tell Neo4j to use memory mapped buffers for accessing the native storage layer.")
public static final Setting<Boolean> use_memory_mapped_buffers = setting( "use_memory_mapped_buffers", BOOLEAN, Boolean.toString(!Settings.osIsWindows()));
@Description("Target size for pages of mapped memory.")
public static final Setting<Long> mapped_memory_page_size = setting("mapped_memory_page_size", BYTES, "1M" );
@Description("The size to allocate for a memory mapping pool to be shared between all stores.")
public static final Setting<Long> all_stores_total_mapped_memory_size = setting("all_stores_total_mapped_memory_size", BYTES, "500M" );
@Description("Tell Neo4j to regularly log memory mapping statistics.")
public static final Setting<Boolean> log_mapped_memory_stats = setting("log_mapped_memory_stats", BOOLEAN, FALSE );
@Description("The file where Neo4j will record memory mapping statistics.")
public static final Setting<File> log_mapped_memory_stats_filename = setting("log_mapped_memory_stats_filename", PATH, "mapped_memory_stats.log", basePath(store_dir) );
@Description("The number of records to be loaded between regular logging of memory mapping statistics.")
public static final Setting<Integer> log_mapped_memory_stats_interval = setting("log_mapped_memory_stats_interval", INTEGER, "1000000");
@Description("The size to allocate for memory mapping the node store.")
public static final Setting<Long> nodestore_mapped_memory_size = setting("neostore.nodestore.db.mapped_memory", BYTES, "20M" );
@Description("The size to allocate for memory mapping the property value store.")
public static final Setting<Long> nodestore_propertystore_mapped_memory_size = setting("neostore.propertystore.db.mapped_memory", BYTES, "90M" );
@Description("The size to allocate for memory mapping the store for property key indexes.")
public static final Setting<Long> nodestore_propertystore_index_mapped_memory_size = setting("neostore.propertystore.db.index.mapped_memory", BYTES, "1M" );
@Description("The size to allocate for memory mapping the store for property key strings.")
public static final Setting<Long> nodestore_propertystore_index_keys_mapped_memory_size = setting("neostore.propertystore.db.index.keys.mapped_memory", BYTES, "1M" );
@Description("The size to allocate for memory mapping the string property store.")
public static final Setting<Long> strings_mapped_memory_size = setting("neostore.propertystore.db.strings.mapped_memory", BYTES, "130M" );
@Description("The size to allocate for memory mapping the array property store.")
public static final Setting<Long> arrays_mapped_memory_size = setting("neostore.propertystore.db.arrays.mapped_memory", BYTES, "130M" );
@Description("The size to allocate for memory mapping the relationship store.")
public static final Setting<Long> relationshipstore_mapped_memory_size = setting("neostore.relationshipstore.db.mapped_memory", BYTES, "100M" );
@Description("How many relationships to read at a time during iteration")
public static final Setting<Integer> relationship_grab_size = setting("relationship_grab_size", INTEGER, "100", min( 1 ));
@Description("Specifies the block size for storing strings. This parameter is only honored when the store is " +
"created, otherwise it is ignored. " +
"Note that each character in a string occupies two bytes, meaning that a block size of 120 (the default " +
"size) will hold a 60 character " +
"long string before overflowing into a second block. Also note that each block carries an overhead of 8 " +
"bytes. " +
"This means that if the block size is 120, the size of the stored records will be 128 bytes.")
public static final Setting<Integer> string_block_size = setting("string_block_size", INTEGER, "120",min(1));
@Description("Specifies the block size for storing arrays. This parameter is only honored when the store is " +
"created, otherwise it is ignored. " +
"The default block size is 120 bytes, and the overhead of each block is the same as for string blocks, " +
"i.e., 8 bytes.")
public static final Setting<Integer> array_block_size = setting("array_block_size", INTEGER, "120",min(1));
@Description("Specifies the block size for storing labels exceeding in-lined space in node record. " +
"This parameter is only honored when the store is created, otherwise it is ignored. " +
"The default block size is 60 bytes, and the overhead of each block is the same as for string blocks, " +
"i.e., 8 bytes.")
public static final Setting<Integer> label_block_size = setting("label_block_size", INTEGER, "60",min(1));
@Description("Mark this database as a backup slave.")
public static final Setting<Boolean> backup_slave = setting("backup_slave", BOOLEAN, FALSE );
@Description("An identifier that uniquely identifies this graph database instance within this JVM. " +
"Defaults to an auto-generated number depending on how many instance are started in this JVM.")
public static final Setting<String> forced_kernel_id = setting("forced_kernel_id", STRING, NO_DEFAULT, illegalValueMessage( "invalid kernel identifier", matches( "[a-zA-Z0-9]*" ) ));
public static final Setting<Boolean> execution_guard_enabled = setting("execution_guard_enabled", BOOLEAN, FALSE );
@Description("Amount of time in ms the GC monitor thread will wait before taking another measurement.")
public static final Setting<Long> gc_monitor_interval = MonitorGc.Configuration.gc_monitor_wait_time;
@Description("The amount of time in ms the monitor thread has to be blocked before logging a message it was " +
"blocked.")
public static final Setting<Long> gc_monitor_block_threshold = MonitorGc.Configuration.gc_monitor_threshold;
private static String[] availableCaches()
{
List<String> available = new ArrayList<>();
for ( CacheProvider cacheProvider : Service.load( CacheProvider.class ) )
{
available.add( cacheProvider.getName() );
}
// --- higher prio ---->
for ( String prioritized : new String[] { "soft", "hpc" } )
{
if ( available.remove( prioritized ) )
{
available.add( 0, prioritized );
}
}
return available.toArray( new String[available.size()] );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseSettings.java
|
3,476
|
public class GraphDatabaseFactoryState
{
private List<Class<?>> settingsClasses;
private List<KernelExtensionFactory<?>> kernelExtensions;
private List<CacheProvider> cacheProviders;
private List<TransactionInterceptorProvider> txInterceptorProviders;
private Logging logging;
public GraphDatabaseFactoryState() {
settingsClasses = new ArrayList<>();
settingsClasses.add( GraphDatabaseSettings.class );
kernelExtensions = new ArrayList<>();
for ( KernelExtensionFactory factory : Service.load( KernelExtensionFactory.class ) )
{
kernelExtensions.add( factory );
}
cacheProviders = Iterables.toList( Service.load( CacheProvider.class ) );
txInterceptorProviders = Iterables.toList( Service.load( TransactionInterceptorProvider.class ) );
}
public GraphDatabaseFactoryState( GraphDatabaseFactoryState previous )
{
settingsClasses = new ArrayList<>( previous.settingsClasses );
kernelExtensions = new ArrayList<>( previous.kernelExtensions );
cacheProviders = new ArrayList<>( previous.cacheProviders );
txInterceptorProviders = new ArrayList<>( previous.txInterceptorProviders );
logging = previous.logging;
}
public Iterable<KernelExtensionFactory<?>> getKernelExtension()
{
return kernelExtensions;
}
public void setKernelExtensions( Iterable<KernelExtensionFactory<?>> newKernelExtensions )
{
kernelExtensions.clear();
addKernelExtensions( newKernelExtensions );
}
public void addKernelExtensions( Iterable<KernelExtensionFactory<?>> newKernelExtensions )
{
for ( KernelExtensionFactory<?> newKernelExtension : newKernelExtensions )
{
kernelExtensions.add( newKernelExtension );
}
}
public List<CacheProvider> getCacheProviders()
{
return cacheProviders;
}
public void setCacheProviders( Iterable<CacheProvider> newCacheProviders )
{
cacheProviders.clear();
for ( CacheProvider newCacheProvider : newCacheProviders )
{
cacheProviders.add( newCacheProvider );
}
}
public List<TransactionInterceptorProvider> getTransactionInterceptorProviders()
{
return txInterceptorProviders;
}
public void setTransactionInterceptorProviders( Iterable<TransactionInterceptorProvider>
transactionInterceptorProviders )
{
txInterceptorProviders.clear();
for ( TransactionInterceptorProvider newTxInterceptorProvider : transactionInterceptorProviders )
{
txInterceptorProviders.add( newTxInterceptorProvider );
}
}
public void setLogging( Logging logging )
{
this.logging = logging;
}
public Dependencies databaseDependencies()
{
return new GraphDatabaseDependencies(
logging,
settingsClasses,
kernelExtensions,
cacheProviders,
txInterceptorProviders );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseFactoryState.java
|
3,477
|
{
@SuppressWarnings("deprecation")
@Override
public GraphDatabaseService newDatabase( Map<String, String> config )
{
config.put( "ephemeral", "false" );
Dependencies dependencies = state.databaseDependencies();
if ( TRUE.equalsIgnoreCase( config.get( read_only.name() ) ) )
{
return new EmbeddedReadOnlyGraphDatabase( path, config, dependencies );
}
else
{
return new EmbeddedGraphDatabase( path, config, dependencies );
}
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseFactory.java
|
3,478
|
{
public boolean isReturnableNode( final TraversalPosition currentPosition )
{
return currentPosition.notStartNode();
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_ReturnableEvaluator.java
|
3,479
|
{
public boolean isReturnableNode( final TraversalPosition currentPosition )
{
return true;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_ReturnableEvaluator.java
|
3,480
|
{
@Override
public void close()
{ // Nothing to close
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_Resource.java
|
3,481
|
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null, "foo" );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,482
|
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null, "foo", 42 );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,483
|
{
@Override
public void call( RelationshipIndex self )
{
self.add( null, "foo", 42 );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,484
|
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo" );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,485
|
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo", "bar" );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,486
|
{
@Override
public void call( RelationshipIndex self )
{
self.get( "foo", "bar" );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,487
|
{
@Override
public void call( RelationshipIndex self )
{
self.query( 42, null, null );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,488
|
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo", 42, null, null );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,489
|
{
@Override
public void call( RelationshipIndex self )
{
self.putIfAbsent( null, "foo", 42 );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,490
|
{
@Override
public void call( RelationshipIndex self )
{
self.delete();
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,491
|
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,492
|
{
@Override
public void call( RelationshipIndex self )
{
self.get( "foo", 42, null, null );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,493
|
public class RelationshipIndexFacadeMethods
{
private static final FacadeMethod<RelationshipIndex> GET_WITH_FILTER = new FacadeMethod<RelationshipIndex>(
"IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull )" )
{
@Override
public void call( RelationshipIndex self )
{
self.get( "foo", 42, null, null );
}
};
private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY_WITH_FILTER = new
FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> query( String key, " +
"Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull )" )
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo", 42, null, null );
}
};
private static final FacadeMethod<RelationshipIndex> QUERY_WITH_FILTER = new FacadeMethod<RelationshipIndex>(
"IndexHits<Relationship> query( Object queryOrQueryObjectOrNull, Node startNodeOrNull, " +
"Node endNodeOrNull )" )
{
@Override
public void call( RelationshipIndex self )
{
self.query( 42, null, null );
}
};
private static final FacadeMethod<RelationshipIndex> GET = new FacadeMethod<RelationshipIndex>( "IndexHits<T>" +
" get( String key, Object value )" )
{
@Override
public void call( RelationshipIndex self )
{
self.get( "foo", "bar" );
}
};
private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY = new FacadeMethod<RelationshipIndex>(
"IndexHits<T> query( String key, Object queryOrQueryObject )" )
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo", "bar" );
}
};
private static final FacadeMethod<RelationshipIndex> QUERY = new FacadeMethod<RelationshipIndex>(
"IndexHits<T> query( Object queryOrQueryObject )" )
{
@Override
public void call( RelationshipIndex self )
{
self.query( "foo" );
}
};
private static final FacadeMethod<RelationshipIndex> ADD = new FacadeMethod<RelationshipIndex>( "void add( T " +
"entity, String key, Object value )" )
{
@Override
public void call( RelationshipIndex self )
{
self.add( null, "foo", 42 );
}
};
private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY_AND_VALUE = new
FacadeMethod<RelationshipIndex>( "void remove( T entity, String key, Object value )" )
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null, "foo", 42 );
}
};
private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY = new FacadeMethod<RelationshipIndex>(
"void remove( T entity, String key )" )
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null, "foo" );
}
};
private static final FacadeMethod<RelationshipIndex> REMOVE = new FacadeMethod<RelationshipIndex>( "void " +
"remove( T entity )" )
{
@Override
public void call( RelationshipIndex self )
{
self.remove( null );
}
};
private static final FacadeMethod<RelationshipIndex> DELETE = new FacadeMethod<RelationshipIndex>( "void delete()" )
{
@Override
public void call( RelationshipIndex self )
{
self.delete();
}
};
private static final FacadeMethod<RelationshipIndex> PUT_IF_ABSENT = new FacadeMethod<RelationshipIndex>( "T " +
"putIfAbsent( T entity, String key, Object value )" )
{
@Override
public void call( RelationshipIndex self )
{
self.putIfAbsent( null, "foo", 42 );
}
};
static final Iterable<FacadeMethod<RelationshipIndex>> ALL_RELATIONSHIP_INDEX_FACADE_METHODS =
unmodifiableCollection(
asList(
GET_WITH_FILTER,
QUERY_BY_KEY_WITH_FILTER,
QUERY_WITH_FILTER,
GET,
QUERY_BY_KEY,
QUERY,
ADD,
REMOVE_BY_KEY_AND_VALUE,
REMOVE_BY_KEY,
REMOVE,
DELETE,
PUT_IF_ABSENT
) );
}
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_RelationshipIndexFacadeMethods.java
|
3,494
|
{
@Override
public void call( Relationship relationship )
{
relationship.getEndNode();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,495
|
{
@Override
public void call( Relationship relationship )
{
relationship.getStartNode();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,496
|
{
@Override
public void call( Relationship relationship )
{
relationship.delete();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
|
3,497
|
public class RunOutOfDiskSpaceIT
{
@Test
public void shouldPropagateIOExceptions() throws Exception
{
// Given
TransactionFailureException exceptionThrown = null;
LimitedFileSystemGraphDatabase db = new LimitedFileSystemGraphDatabase();
db.runOutOfDiskSpaceNao();
// When
Transaction tx = db.beginTx();
db.createNode();
tx.success();
try
{
tx.finish();
fail( "Expected tx finish to throw TransactionFailureException when filesystem is full." );
}
catch ( TransactionFailureException e )
{
exceptionThrown = e;
}
// Then
assertThat( exceptionThrown.getCause(), isA( Throwable.class ) );
assertThat( exceptionThrown.getCause().getCause(), isA( Throwable.class ) );
assertThat( exceptionThrown.getCause().getCause().getCause(), is( instanceOf( IOException.class ) ) );
}
@Test
public void shouldStopDatabaseWhenOutOfDiskSpace() throws Exception
{
// Given
TransactionFailureException errorCaught = null;
LimitedFileSystemGraphDatabase db = new LimitedFileSystemGraphDatabase();
db.runOutOfDiskSpaceNao();
Transaction tx = db.beginTx();
db.createNode();
tx.success();
try
{
tx.finish();
fail( "Expected tx finish to throw TransactionFailureException when filesystem is full." );
}
catch ( TransactionFailureException e )
{
// Expected
}
// When
try
{
db.beginTx();
fail( "Expected tx begin to throw TransactionFailureException when tx manager breaks." );
}
catch ( TransactionFailureException e )
{
errorCaught = e;
}
// Then
assertThat( errorCaught.getCause(), is( instanceOf( SystemException.class ) ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_RunOutOfDiskSpaceIT.java
|
3,498
|
public class SchemaAcceptanceTest
{
public @Rule ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule();
private GraphDatabaseService db;
private Label label = Labels.MY_LABEL;
private String propertyKey = "my_property_key";
private enum Labels implements Label
{
MY_LABEL,
MY_OTHER_LABEL
}
@Test
public void addingAnIndexingRuleShouldSucceed() throws Exception
{
// WHEN
IndexDefinition index = createIndex( db, label , propertyKey );
// THEN
assertThat( getIndexes( db, label ), containsOnly( index ) );
}
@Test
public void addingAnIndexingRuleInNestedTxShouldSucceed() throws Exception
{
IndexDefinition index;
// WHEN
Transaction tx = db.beginTx();
IndexDefinition indexDef;
try
{
Transaction tx1 = db.beginTx();
try
{
indexDef = db.schema().indexFor( label ).on( propertyKey ).create();
tx1.success();
}
finally
{
tx1.finish();
}
index = indexDef;
tx.success();
}
finally
{
tx.finish();
}
waitForIndex( db, indexDef );
// THEN
assertThat( getIndexes( db, label ), containsOnly( index ) );
}
@Test
public void shouldThrowConstraintViolationIfAskedToIndexSamePropertyAndLabelTwiceInSameTx() throws Exception
{
// WHEN
Transaction tx = db.beginTx();
try
{
Schema schema = db.schema();
schema.indexFor( label ).on( propertyKey ).create();
try
{
schema.indexFor( label ).on( propertyKey ).create();
fail( "Should not have validated" );
}
catch ( ConstraintViolationException e )
{
assertEquals( "There already exists an index for label 'MY_LABEL' on property 'my_property_key'.",
e.getMessage() );
}
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldThrowConstraintViolationIfAskedToIndexPropertyThatIsAlreadyIndexed() throws Exception
{
// GIVEN
Transaction tx = db.beginTx();
Schema schema = db.schema();
schema.indexFor( label ).on( propertyKey ).create();
tx.success();
tx.finish();
// WHEN
ConstraintViolationException caught = null;
tx = db.beginTx();
try
{
schema.indexFor( label ).on( propertyKey ).create();
tx.success();
}
catch(ConstraintViolationException e)
{
caught = e;
}
finally
{
tx.finish();
}
// THEN
assertThat(caught, not(nullValue()));
}
@Test
public void shouldThrowConstraintViolationIfAskedToCreateCompoundIndex() throws Exception
{
// WHEN
Transaction tx = db.beginTx();
try
{
Schema schema = db.schema();
schema.indexFor( label )
.on( "my_property_key" )
.on( "other_property" ).create();
tx.success();
fail( "Should not be able to create index on multiple propertyKey keys" );
}
catch ( UnsupportedOperationException e )
{
assertThat( e.getMessage(), containsString( "Compound indexes" ) );
}
finally
{
tx.finish();
}
}
@Test
public void shouldThrowConstraintViolationIfAskedToCreateCompoundConstraint() throws Exception
{
// WHEN
Transaction tx = db.beginTx();
try
{
Schema schema = db.schema();
schema.constraintFor( label )
.assertPropertyIsUnique( "my_property_key" )
.assertPropertyIsUnique( "other_property" ).create();
tx.success();
fail( "Should not be able to create constraint on multiple propertyKey keys" );
}
catch ( UnsupportedOperationException e )
{
assertThat( e.getMessage(), containsString( "can only create one unique constraint" ) );
}
finally
{
tx.finish();
}
}
@Test
public void droppingExistingIndexRuleShouldSucceed() throws Exception
{
// GIVEN
IndexDefinition index = createIndex( db, label , propertyKey );
// WHEN
dropIndex( index );
// THEN
assertThat( getIndexes( db, label ), isEmpty() );
}
@Test
public void droppingAnUnexistingIndexShouldGiveHelpfulExceptionInSameTransaction() throws Exception
{
// GIVEN
IndexDefinition index = createIndex( db, label , propertyKey );
// WHEN
Transaction tx = db.beginTx();
try
{
index.drop();
try
{
index.drop();
fail( "Should not be able to drop index twice" );
}
catch ( ConstraintViolationException e )
{
assertThat( e.getMessage(), containsString( "Unable to drop index" ) );
}
tx.success();
}
finally
{
tx.finish();
}
// THEN
assertThat( "Index should have been deleted", getIndexes( db, label ), not( contains( index ) ) );
}
@Test
public void droppingAnUnexistingIndexShouldGiveHelpfulExceptionInSeparateTransactions() throws Exception
{
// GIVEN
IndexDefinition index = createIndex( db, label , propertyKey );
dropIndex( index );
// WHEN
try
{
dropIndex( index );
fail( "Should not be able to drop index twice" );
}
catch ( ConstraintViolationException e )
{
assertThat( e.getMessage(), containsString( "Unable to drop index" ) );
}
// THEN
assertThat( "Index should have been deleted", getIndexes( db, label ), not( contains( index ) ) );
}
@Test
public void awaitingIndexComingOnlineWorks()
{
// GIVEN
// WHEN
IndexDefinition index = createIndex( db, label, propertyKey );
// PASS
Transaction tx = db.beginTx();
try
{
db.schema().awaitIndexOnline( index, 1L, TimeUnit.MINUTES );
// THEN
assertEquals( Schema.IndexState.ONLINE, db.schema().getIndexState( index ) );
}
finally
{
tx.finish();
}
}
@Test
public void awaitingAllIndexesComingOnlineWorks()
{
// GIVEN
// WHEN
IndexDefinition index = createIndex( db, label , propertyKey );
createIndex( db, label , "other_property" );
// PASS
waitForIndex( db, index );
Transaction tx = db.beginTx();
try
{
db.schema().awaitIndexesOnline( 1L, TimeUnit.MINUTES );
// THEN
assertEquals( Schema.IndexState.ONLINE, db.schema().getIndexState( index ) );
}
finally
{
tx.finish();
}
}
@Test
public void shouldRecreateDroppedIndex() throws Exception
{
// GIVEN
Node node = createNode( db, propertyKey, "Neo", label );
// create an index
IndexDefinition index = createIndex( db, label , propertyKey );
waitForIndex( db, index );
// delete the index right away
dropIndex( index );
// WHEN recreating that index
createIndex( db, label, propertyKey );
waitForIndex( db, index );
// THEN it should exist and be usable
assertThat( getIndexes( db, label ), contains( index ) );
assertThat( findNodesByLabelAndProperty( label, propertyKey, "Neo", db ), containsOnly( node ) );
}
@Test
public void shouldCreateUniquenessConstraint() throws Exception
{
// WHEN
ConstraintDefinition constraint = createConstraint( label, propertyKey );
// THEN
try ( Transaction tx = db.beginTx() )
{
assertEquals( ConstraintType.UNIQUENESS, constraint.getConstraintType() );
assertEquals( label.name(), constraint.getLabel().name() );
assertEquals( asSet( propertyKey ), asSet( constraint.getPropertyKeys() ) );
tx.success();
}
}
@Test
public void shouldListAddedConstraintsByLabel() throws Exception
{
// GIVEN
ConstraintDefinition createdConstraint = createConstraint( label, propertyKey );
// WHEN THEN
assertThat( getConstraints( db, label ), containsOnly( createdConstraint ) );
}
@Test
public void shouldListAddedConstraints() throws Exception
{
// GIVEN
ConstraintDefinition createdConstraint = createConstraint( label, propertyKey );
// WHEN THEN
assertThat( getConstraints( db ), containsOnly( createdConstraint ) );
}
@Test
public void shouldDropUniquenessConstraint() throws Exception
{
// GIVEN
ConstraintDefinition constraint = createConstraint( label, propertyKey );
// WHEN
dropConstraint( db, constraint );
// THEN
assertThat( getConstraints( db, label ), isEmpty() );
}
@Test
public void addingConstraintWhenIndexAlreadyExistsGivesNiceError() throws Exception
{
// GIVEN
createIndex( db, label , propertyKey );
// WHEN
try
{
createConstraint( label, propertyKey );
fail( "Expected exception to be thrown" );
}
catch ( ConstraintViolationException e )
{
assertEquals( format( "There already exists an index for label 'MY_LABEL' on property 'my_property_key'. " +
"A constraint cannot be created until the index has been dropped." ), e.getMessage() );
}
}
@Test
public void addingUniquenessConstraintWhenDuplicateDataExistsGivesNiceError() throws Exception
{
// GIVEN
Transaction transaction = db.beginTx();
try {
db.createNode( label ).setProperty( propertyKey, "value1" );
db.createNode( label ).setProperty( propertyKey, "value1" );
transaction.success();
}
finally
{
transaction.finish();
}
// WHEN
try
{
createConstraint( label, propertyKey );
fail( "Expected exception to be thrown" );
}
catch ( ConstraintViolationException e )
{
assertEquals(
format( "Unable to create CONSTRAINT ON ( my_label:MY_LABEL ) ASSERT my_label.my_property_key " +
"IS UNIQUE:%nMultiple nodes with label `MY_LABEL` have property `my_property_key` = " +
"'value1':%n" +
" node(0)%n" +
" node(1)" ), e.getMessage() );
}
}
@Test
public void addingConstraintWhenAlreadyConstrainedGivesNiceError() throws Exception
{
// GIVEN
createConstraint( label, propertyKey );
// WHEN
try
{
createConstraint( label, propertyKey );
fail( "Expected exception to be thrown" );
}
catch ( ConstraintViolationException e )
{
assertEquals( "Label 'MY_LABEL' and property 'my_property_key' have a unique constraint defined on them.",
e.getMessage() );
}
}
@Test
public void addingIndexWhenAlreadyConstrained() throws Exception
{
// GIVEN
createConstraint( label, propertyKey );
// WHEN
try
{
createIndex( db, label , propertyKey );
fail( "Expected exception to be thrown" );
}
catch ( ConstraintViolationException e )
{
assertEquals(
"Label 'MY_LABEL' and property 'my_property_key' have a unique constraint defined on them, so an index is " +
"already created that matches this.", e.getMessage() );
}
}
@Test
public void addingIndexWhenAlreadyIndexed() throws Exception
{
// GIVEN
createIndex( db, label, propertyKey );
// WHEN
try
{
createIndex( db, label, propertyKey );
fail( "Expected exception to be thrown" );
}
catch ( ConstraintViolationException e )
{
assertEquals( "There already exists an index for label 'MY_LABEL' on property 'my_property_key'.",
e.getMessage() );
}
}
@Before
public void init()
{
db = dbRule.getGraphDatabaseService();
}
private void dropConstraint( GraphDatabaseService db, ConstraintDefinition constraint )
{
Transaction tx = db.beginTx();
try
{
constraint.drop();
tx.success();
}
finally
{
tx.finish();
}
}
private ConstraintDefinition createConstraint( Label label, String prop )
{
Transaction tx = db.beginTx();
try
{
ConstraintDefinition constraint = db.schema().constraintFor( label ).assertPropertyIsUnique( prop ).create();
tx.success();
return constraint;
}
finally
{
tx.finish();
}
}
private void dropIndex( IndexDefinition index )
{
Transaction tx = db.beginTx();
try
{
index.drop();
tx.success();
}
finally
{
tx.finish();
}
}
private Node createNode( GraphDatabaseService db, String key, Object value, Label label )
{
Transaction tx = db.beginTx();
try
{
Node node = db.createNode( label );
node.setProperty( key, value );
tx.success();
return node;
}
finally
{
tx.finish();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaAcceptanceTest.java
|
3,499
|
public class SchemaFacadeMethods
{
private static final Label LABEL = DynamicLabel.label( "Label" );
private static final IndexDefinition INDEX_DEFINITION = mock( IndexDefinition.class );
private static final FacadeMethod<Schema> INDEX_FOR = new FacadeMethod<Schema>( "IndexCreator indexFor( Label label )" )
{
@Override
public void call( Schema self )
{
self.indexFor( LABEL );
}
};
private static final FacadeMethod<Schema> GET_INDEXES_BY_LABEL =
new FacadeMethod<Schema>( "Iterable<IndexDefinition> getIndexes( Label label )" )
{
@Override
public void call( Schema self )
{
self.getIndexes( LABEL );
}
};
private static final FacadeMethod<Schema> GET_INDEXES =
new FacadeMethod<Schema>( "Iterable<IndexDefinition> getIndexes()" )
{
@Override
public void call( Schema self )
{
self.getIndexes();
}
};
private static final FacadeMethod<Schema> GET_INDEX_STATE =
new FacadeMethod<Schema>( "IndexState getIndexState( IndexDefinition index )" )
{
@Override
public void call( Schema self )
{
self.getIndexState( INDEX_DEFINITION );
}
};
private static final FacadeMethod<Schema> GET_INDEX_FAILURE =
new FacadeMethod<Schema>( "String getIndexFailure( IndexDefinition index )" )
{
@Override
public void call( Schema self )
{
self.getIndexFailure( INDEX_DEFINITION );
}
};
private static final FacadeMethod<Schema> CONSTRAINT_FOR =
new FacadeMethod<Schema>( "ConstraintCreator constraintFor( Label label )" )
{
@Override
public void call( Schema self )
{
self.constraintFor( LABEL );
}
};
private static final FacadeMethod<Schema> GET_CONSTRAINTS_BY_LABEL =
new FacadeMethod<Schema>( "Iterable<ConstraintDefinition> getConstraints( Label label )" )
{
@Override
public void call( Schema self )
{
self.getConstraints( LABEL );
}
};
private static final FacadeMethod<Schema> GET_CONSTRAINTS =
new FacadeMethod<Schema>( "Iterable<ConstraintDefinition> getConstraints()" )
{
@Override
public void call( Schema self )
{
self.getConstraints();
}
};
private static final FacadeMethod<Schema> AWAIT_INDEX_ONLINE =
new FacadeMethod<Schema>( "void awaitIndexOnline( IndexDefinition index, long duration, TimeUnit unit )" )
{
@Override
public void call( Schema self )
{
self.awaitIndexOnline( INDEX_DEFINITION, 1l, TimeUnit.SECONDS );
}
};
private static final FacadeMethod<Schema> AWAIT_INDEXES_ONLINE =
new FacadeMethod<Schema>( "void awaitIndexesOnline( long duration, TimeUnit unit )" )
{
@Override
public void call( Schema self )
{
self.awaitIndexesOnline( 1l, TimeUnit.SECONDS );
}
};
static final Iterable<FacadeMethod<Schema>> ALL_SCHEMA_FACADE_METHODS = unmodifiableCollection( asList(
INDEX_FOR,
GET_INDEXES_BY_LABEL,
GET_INDEXES,
GET_INDEX_STATE,
GET_INDEX_FAILURE,
CONSTRAINT_FOR,
GET_CONSTRAINTS_BY_LABEL,
GET_CONSTRAINTS,
AWAIT_INDEX_ONLINE,
AWAIT_INDEXES_ONLINE
) );
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.