Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
900
public class TestProperties extends AbstractNeo4jTestCase { @Test public void addAndRemovePropertiesWithinOneTransaction() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "name", "oscar" ); node.setProperty( "favourite_numbers", new Long[] { 1l, 2l, 3l } ); node.setProperty( "favourite_colors", new String[] { "blue", "red" } ); node.removeProperty( "favourite_colors" ); newTransaction(); assertNotNull( node.getProperty( "favourite_numbers", null ) ); } @Test public void addAndRemovePropertiesWithinOneTransaction2() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "foo", "bar" ); newTransaction(); node.setProperty( "foo2", "bar" ); node.removeProperty( "foo" ); newTransaction(); try { node.getProperty( "foo" ); fail( "property should not exist" ); } catch ( NotFoundException e ) { // good } } @Test public void removeAndAddSameProperty() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "foo", "bar" ); newTransaction(); node.removeProperty( "foo" ); node.setProperty( "foo", "bar" ); newTransaction(); assertEquals( "bar", node.getProperty( "foo" ) ); node.setProperty( "foo", "bar" ); node.removeProperty( "foo" ); newTransaction(); assertNull( node.getProperty( "foo", null ) ); } @Test public void removeSomeAndSetSome() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "remove me", "trash" ); newTransaction(); node.removeProperty( "remove me" ); node.setProperty( "foo", "bar" ); node.setProperty( "baz", 17 ); newTransaction(); assertEquals( "bar", node.getProperty( "foo" ) ); assertEquals( 17, node.getProperty( "baz" ) ); assertNull( node.getProperty( "remove me", null ) ); } @Test public void removeOneOfThree() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "1", 1 ); node.setProperty( "2", 2 ); node.setProperty( "3", 3 ); newTransaction(); node.removeProperty( "2" ); newTransaction(); assertNull( node.getProperty( "2", null ) ); } @Test public void testLongPropertyValues() throws Exception { Node n = getGraphDb().createNode(); setPropertyAndAssertIt( n, -134217728L ); setPropertyAndAssertIt( n, -134217729L ); } @Test public void testIntPropertyValues() throws Exception { Node n = getGraphDb().createNode(); setPropertyAndAssertIt( n, -134217728 ); setPropertyAndAssertIt( n, -134217729 ); } @Test public void booleanRange() throws Exception { Node node = getGraphDb().createNode(); setPropertyAndAssertIt( node, false ); setPropertyAndAssertIt( node, true ); } @Test public void byteRange() throws Exception { Node node = getGraphDb().createNode(); for ( byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; i++ ) { setPropertyAndAssertIt( node, i ); } } @Test public void charRange() throws Exception { Node node = getGraphDb().createNode(); for ( char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++ ) { setPropertyAndAssertIt( node, i ); } } @Test public void shortRange() throws Exception { Node node = getGraphDb().createNode(); for ( short i = Short.MIN_VALUE; i < Short.MAX_VALUE; i++ ) { setPropertyAndAssertIt( node, i ); } } @Test public void intRange() throws Exception { int step = 30001; Node node = getGraphDb().createNode(); for ( int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE-step; i += step ) { setPropertyAndAssertIt( node, i ); } } @Test public void longRange() throws Exception { long step = 120000000000001L; Node node = getGraphDb().createNode(); for ( long i = Long.MIN_VALUE; i < Long.MAX_VALUE-step; i += step ) { setPropertyAndAssertIt( node, i ); } } @Test public void floatRange() throws Exception { float step = 1234567890123456789012345678901234.1234F; Node node = getGraphDb().createNode(); for ( float i = Float.MIN_VALUE; i < Float.MAX_VALUE-step; i += step ) { setPropertyAndAssertIt( node, i ); } } @Test public void doubleRange() throws Exception { double step = 12.345; Node node = getGraphDb().createNode(); for ( double i = Double.MIN_VALUE; i < Double.MAX_VALUE; i += step, step *= 1.004D ) { setPropertyAndAssertIt( node, i ); } } private void setPropertyAndAssertIt( Node node, Object value ) { node.setProperty( "key", value ); assertEquals( value, node.getProperty( "key" ) ); } @Test public void loadManyProperties() throws Exception { Node node = getGraphDb().createNode(); for ( int i = 0; i < 1000; i++ ) { node.setProperty( "property " + i, "value" ); } newTransaction(); clearCache(); assertEquals( "value", node.getProperty( "property 0" ) ); } @Test public void name() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "name", "yo" ); node.getProperty( "name" ); commit(); Transaction tx = getGraphDb().beginTx(); try { node.getProperty( "name" ); tx.success(); } finally { //noinspection deprecation tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestProperties.java
901
public class TestOperationsOnDeletedRelationships { // Should it really do this? Wouldn't it be better if we could recover from a a relationship suddenly // missing in the chain? Perhaps that is really hard to do though. @Test public void shouldThrowNotFoundOnGetAllRelationshipsWhenRelationshipConcurrentlyDeleted() throws Exception { // Given NodeImpl nodeImpl = new NodeImpl( 1337l, false ); NodeManager nodeManager = mock( NodeManager.class ); Throwable exceptionCaught = null; // Given something tries to load relationships, throw InvalidRecordException when( nodeManager.getMoreRelationships( any( NodeImpl.class ) ) ).thenThrow( new InvalidRecordException( "LURING!" ) ); // When try { nodeImpl.getAllRelationships( nodeManager, RelIdArray.DirectionWrapper.BOTH ); } catch ( Throwable e ) { exceptionCaught = e; } // Then assertThat( exceptionCaught, not( nullValue() ) ); assertThat( exceptionCaught, is( instanceOf( NotFoundException.class ) ) ); } @Test public void shouldThrowNotFoundWhenIteratingOverDeletedRelationship() throws Exception { // Given NodeImpl fromNode = new NodeImpl( 1337l, false ); NodeManager nodeManager = mock( NodeManager.class ); Throwable exceptionCaught = null; // This makes fromNode think there are more relationships to be loaded fromNode.setRelChainPosition( 1337l ); // This makes nodeManager pretend that relationships have been deleted when( nodeManager.getMoreRelationships( any( NodeImpl.class ) ) ).thenThrow( new InvalidRecordException( "LURING!" ) ); // When try { fromNode.getMoreRelationships( nodeManager ); } catch ( Throwable e ) { exceptionCaught = e; } // Then assertThat( exceptionCaught, not( nullValue() ) ); assertThat( exceptionCaught, is( instanceOf( NotFoundException.class ) ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestOperationsOnDeletedRelationships.java
902
{ @Override public void run() { try( Transaction tx = getGraphDb().beginTx() ) { tx.acquireWriteLock( entity ); gotTheLock.set( true ); tx.success(); } catch ( Exception e ) { e.printStackTrace(); throw launderedException( e ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNode.java
903
public class TestNode extends AbstractNeo4jTestCase { @Test public void testNodeCreateAndDelete() { Node node = getGraphDb().createNode(); long nodeId = node.getId(); getGraphDb().getNodeById( nodeId ); node.delete(); Transaction tx = getTransaction(); tx.success(); //noinspection deprecation tx.finish(); setTransaction( getGraphDb().beginTx() ); try { getGraphDb().getNodeById( nodeId ); fail( "Node[" + nodeId + "] should be deleted." ); } catch ( NotFoundException e ) { } } @Test public void testDeletedNode() { // do some evil stuff Node node = getGraphDb().createNode(); node.delete(); Logger log = Logger .getLogger( "org.neo4j.kernel.impl.core.NeoConstraintsListener" ); Level level = log.getLevel(); log.setLevel( Level.OFF ); try { node.setProperty( "key1", new Integer( 1 ) ); fail( "Adding stuff to deleted node should throw exception" ); } catch ( Exception e ) { // good } log.setLevel( level ); } @Test public void testNodeAddProperty() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); try { node1.setProperty( null, null ); fail( "Null argument should result in exception." ); } catch ( IllegalArgumentException e ) { } String key1 = "key1"; String key2 = "key2"; String key3 = "key3"; Integer int1 = new Integer( 1 ); Integer int2 = new Integer( 2 ); String string1 = new String( "1" ); String string2 = new String( "2" ); // add property node1.setProperty( key1, int1 ); node2.setProperty( key1, string1 ); node1.setProperty( key2, string2 ); node2.setProperty( key2, int2 ); assertTrue( node1.hasProperty( key1 ) ); assertTrue( node2.hasProperty( key1 ) ); assertTrue( node1.hasProperty( key2 ) ); assertTrue( node2.hasProperty( key2 ) ); assertTrue( !node1.hasProperty( key3 ) ); assertTrue( !node2.hasProperty( key3 ) ); assertEquals( int1, node1.getProperty( key1 ) ); assertEquals( string1, node2.getProperty( key1 ) ); assertEquals( string2, node1.getProperty( key2 ) ); assertEquals( int2, node2.getProperty( key2 ) ); getTransaction().failure(); } @Test public void testNodeRemoveProperty() { String key1 = "key1"; String key2 = "key2"; Integer int1 = new Integer( 1 ); Integer int2 = new Integer( 2 ); String string1 = new String( "1" ); String string2 = new String( "2" ); Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); try { if ( node1.removeProperty( key1 ) != null ) { fail( "Remove of non existing property should return null" ); } } catch ( NotFoundException e ) { } try { node1.removeProperty( null ); fail( "Remove null property should throw exception." ); } catch ( IllegalArgumentException e ) { } node1.setProperty( key1, int1 ); node2.setProperty( key1, string1 ); node1.setProperty( key2, string2 ); node2.setProperty( key2, int2 ); try { node1.removeProperty( null ); fail( "Null argument should result in exception." ); } catch ( IllegalArgumentException e ) { } // test remove property assertEquals( int1, node1.removeProperty( key1 ) ); assertEquals( string1, node2.removeProperty( key1 ) ); // test remove of non existing property try { if ( node2.removeProperty( key1 ) != null ) { fail( "Remove of non existing property return null." ); } } catch ( NotFoundException e ) { // must mark as rollback only } getTransaction().failure(); } @Test public void testNodeChangeProperty() { String key1 = "key1"; String key2 = "key2"; String key3 = "key3"; Integer int1 = new Integer( 1 ); Integer int2 = new Integer( 2 ); String string1 = new String( "1" ); String string2 = new String( "2" ); Boolean bool1 = new Boolean( true ); Boolean bool2 = new Boolean( false ); Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); node1.setProperty( key1, int1 ); node2.setProperty( key1, string1 ); node1.setProperty( key2, string2 ); node2.setProperty( key2, int2 ); try { node1.setProperty( null, null ); fail( "Null argument should result in exception." ); } catch ( IllegalArgumentException e ) { } catch ( NotFoundException e ) { fail( "wrong exception" ); } // test change property node1.setProperty( key1, int2 ); node2.setProperty( key1, string2 ); assertEquals( string2, node2.getProperty( key1 ) ); node1.setProperty( key3, bool1 ); node1.setProperty( key3, bool2 ); assertEquals( string2, node2.getProperty( key1 ) ); node1.delete(); node2.delete(); } @Test public void testNodeChangeProperty2() { String key1 = "key1"; Integer int1 = new Integer( 1 ); Integer int2 = new Integer( 2 ); String string1 = new String( "1" ); String string2 = new String( "2" ); Boolean bool1 = new Boolean( true ); Boolean bool2 = new Boolean( false ); Node node1 = getGraphDb().createNode(); node1.setProperty( key1, int1 ); node1.setProperty( key1, int2 ); assertEquals( int2, node1.getProperty( key1 ) ); node1.removeProperty( key1 ); node1.setProperty( key1, string1 ); node1.setProperty( key1, string2 ); assertEquals( string2, node1.getProperty( key1 ) ); node1.removeProperty( key1 ); node1.setProperty( key1, bool1 ); node1.setProperty( key1, bool2 ); assertEquals( bool2, node1.getProperty( key1 ) ); node1.removeProperty( key1 ); node1.delete(); } @Test public void testNodeGetProperties() { String key1 = "key1"; String key2 = "key2"; String key3 = "key3"; Integer int1 = new Integer( 1 ); Integer int2 = new Integer( 2 ); String string = new String( "3" ); Node node1 = getGraphDb().createNode(); try { node1.getProperty( key1 ); fail( "get non existing property din't throw exception" ); } catch ( NotFoundException e ) { } try { node1.getProperty( null ); fail( "get of null key din't throw exception" ); } catch ( IllegalArgumentException e ) { } assertTrue( !node1.hasProperty( key1 ) ); assertTrue( !node1.hasProperty( null ) ); node1.setProperty( key1, int1 ); node1.setProperty( key2, int2 ); node1.setProperty( key3, string ); Iterator<String> keys = node1.getPropertyKeys().iterator(); keys.next(); keys.next(); keys.next(); assertTrue( node1.hasProperty( key1 ) ); assertTrue( node1.hasProperty( key2 ) ); assertTrue( node1.hasProperty( key3 ) ); try { node1.removeProperty( key3 ); } catch ( NotFoundException e ) { fail( "Remove of property failed." ); } assertTrue( !node1.hasProperty( key3 ) ); assertTrue( !node1.hasProperty( null ) ); node1.delete(); } @Test public void testAddPropertyThenDelete() { Node node = getGraphDb().createNode(); node.setProperty( "test", "test" ); Transaction tx = getTransaction(); tx.success(); //noinspection deprecation tx.finish(); tx = getGraphDb().beginTx(); node.setProperty( "test2", "test2" ); node.delete(); tx.success(); //noinspection deprecation tx.finish(); setTransaction( getGraphDb().beginTx() ); } @Test public void testChangeProperty() { Node node = getGraphDb().createNode(); node.setProperty( "test", "test1" ); newTransaction(); node.setProperty( "test", "test2" ); node.removeProperty( "test" ); node.setProperty( "test", "test3" ); assertEquals( "test3", node.getProperty( "test" ) ); node.removeProperty( "test" ); node.setProperty( "test", "test4" ); newTransaction(); assertEquals( "test4", node.getProperty( "test" ) ); } @Test public void testChangeProperty2() { Node node = getGraphDb().createNode(); node.setProperty( "test", "test1" ); newTransaction(); node.removeProperty( "test" ); node.setProperty( "test", "test3" ); assertEquals( "test3", node.getProperty( "test" ) ); newTransaction(); assertEquals( "test3", node.getProperty( "test" ) ); node.removeProperty( "test" ); node.setProperty( "test", "test4" ); newTransaction(); assertEquals( "test4", node.getProperty( "test" ) ); } @Test public void testNodeLockingProblem() throws InterruptedException { testLockProblem( getGraphDb().createNode() ); } @Test public void testRelationshipLockingProblem() throws InterruptedException { Node node = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); testLockProblem( node.createRelationshipTo( node2, DynamicRelationshipType.withName( "lock-rel" ) ) ); } private void testLockProblem( final PropertyContainer entity ) throws InterruptedException { entity.setProperty( "key", "value" ); final AtomicBoolean gotTheLock = new AtomicBoolean(); Thread thread = new Thread() { @Override public void run() { try( Transaction tx = getGraphDb().beginTx() ) { tx.acquireWriteLock( entity ); gotTheLock.set( true ); tx.success(); } catch ( Exception e ) { e.printStackTrace(); throw launderedException( e ); } } }; thread.start(); long endTime = System.currentTimeMillis() + 5000; WAIT: while ( thread.getState() != State.TERMINATED ) { if ( thread.getState() == Thread.State.WAITING ) { for ( StackTraceElement el : thread.getStackTrace() ) { // if we are in WAITING state in acquireWriteLock we know that we are waiting for the lock if ( el.getClassName().equals( "org.neo4j.kernel.impl.transaction.RWLock" ) ) if ( el.getMethodName().equals( "acquireWriteLock" ) ) break WAIT; } } Thread.sleep( 1 ); if ( System.currentTimeMillis() > endTime ) break; } boolean gotLock = gotTheLock.get(); newTransaction(); assertFalse( gotLock ); thread.join(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNode.java
904
public class TestNeo4jConstrains extends AbstractNeo4jTestCase { private final String key = "testproperty"; @Test public void testDeleteReferenceNodeOrLastNodeIsOk() { Transaction tx = getTransaction(); for ( int i = 0; i < 10; i++ ) { getGraphDb().createNode(); } // long numNodesPre = getNodeManager().getNumberOfIdsInUse( Node.class // ); // empty the DB instance for ( Node node : GlobalGraphOperations.at( getGraphDb() ).getAllNodes() ) { for ( Relationship rel : node.getRelationships() ) { rel.delete(); } node.delete(); } tx.success(); tx.finish(); tx = getGraphDb().beginTx(); // the DB should be empty // long numNodesPost = getNodeManager().getNumberOfIdsInUse( Node.class // ); // System.out.println(String.format( "pre: %d, post: %d", numNodesPre, // numNodesPost )); assertFalse( GlobalGraphOperations.at( getGraphDb() ).getAllNodes().iterator().hasNext() ); // TODO: this should be valid, fails right now! // assertEquals( 0, numNodesPost ); tx.success(); tx.finish(); } @Test public void testDeleteNodeWithRel1() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); node1.createRelationshipTo( node2, MyRelTypes.TEST ); node1.delete(); try { Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Should not validate" ); } catch ( Exception e ) { // good } setTransaction( getGraphDb().beginTx() ); } @Test public void testDeleteNodeWithRel2() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); node1.createRelationshipTo( node2, MyRelTypes.TEST ); node2.delete(); node1.delete(); try { Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Should not validate" ); } catch ( Exception e ) { // good } setTransaction( getGraphDb().beginTx() ); } @Test public void testDeleteNodeWithRel3() { // make sure we can delete in wrong order Node node0 = getGraphDb().createNode(); Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel0 = node0.createRelationshipTo( node1, MyRelTypes.TEST ); Relationship rel1 = node0.createRelationshipTo( node2, MyRelTypes.TEST ); node1.delete(); rel0.delete(); Transaction tx = getTransaction(); tx.success(); tx.finish(); setTransaction( getGraphDb().beginTx() ); node2.delete(); rel1.delete(); node0.delete(); } @Test public void testCreateRelOnDeletedNode() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Transaction tx = getTransaction(); tx.success(); tx.finish(); tx = getGraphDb().beginTx(); node1.delete(); clearCache(); try { node1.createRelationshipTo( node2, MyRelTypes.TEST ); fail( "Create of rel on deleted node should fail fast" ); } catch ( Exception e ) { // ok } try { tx.failure(); tx.finish(); // fail( "Transaction should be marked rollback" ); } catch ( Exception e ) { // good } setTransaction( getGraphDb().beginTx() ); node2.delete(); node1.delete(); } @Test public void testAddPropertyDeletedNode() { Node node = getGraphDb().createNode(); node.delete(); try { node.setProperty( key, 1 ); fail( "Add property on deleted node should not validate" ); } catch ( Exception e ) { // good } } @Test public void testRemovePropertyDeletedNode() { Node node = getGraphDb().createNode(); node.setProperty( key, 1 ); node.delete(); try { node.removeProperty( key ); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Change property on deleted node should not validate" ); } catch ( Exception e ) { // ok } } @Test public void testChangePropertyDeletedNode() { Node node = getGraphDb().createNode(); node.setProperty( key, 1 ); node.delete(); try { node.setProperty( key, 2 ); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Change property on deleted node should not validate" ); } catch ( Exception e ) { // ok } } @Test public void testAddPropertyDeletedRelationship() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.delete(); try { rel.setProperty( key, 1 ); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Add property on deleted rel should not validate" ); } catch ( Exception e ) { // good } node1.delete(); node2.delete(); } @Test public void testRemovePropertyDeletedRelationship() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.setProperty( key, 1 ); rel.delete(); try { rel.removeProperty( key ); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Remove property on deleted rel should not validate" ); } catch ( Exception e ) { // ok } node1.delete(); node2.delete(); } @Test public void testChangePropertyDeletedRelationship() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.setProperty( key, 1 ); rel.delete(); try { rel.setProperty( key, 2 ); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Change property on deleted rel should not validate" ); } catch ( Exception e ) { // ok } node1.delete(); node2.delete(); } @Test public void testMultipleDeleteNode() { Node node1 = getGraphDb().createNode(); node1.delete(); try { node1.delete(); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Should not validate" ); } catch ( Exception e ) { // ok } } @Test public void testMultipleDeleteRelationship() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.delete(); node1.delete(); node2.delete(); try { rel.delete(); Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Should not validate" ); } catch ( Exception e ) { // ok } } @Test public void testIllegalPropertyType() { Node node1 = getGraphDb().createNode(); try { node1.setProperty( key, new Object() ); fail( "Shouldn't validate" ); } catch ( Exception e ) { // good } { Transaction tx = getTransaction(); tx.failure(); tx.finish(); } setTransaction( getGraphDb().beginTx() ); try { getGraphDb().getNodeById( node1.getId() ); fail( "Node should not exist, previous tx didn't rollback" ); } catch ( NotFoundException e ) { // good } node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); try { rel.setProperty( key, new Object() ); fail( "Shouldn't validate" ); } catch ( Exception e ) { // good } try { Transaction tx = getTransaction(); tx.success(); tx.finish(); fail( "Shouldn't validate" ); } catch ( Exception e ) { } // good setTransaction( getGraphDb().beginTx() ); try { getGraphDb().getNodeById( node1.getId() ); fail( "Node should not exist, previous tx didn't rollback" ); } catch ( NotFoundException e ) { // good } try { getGraphDb().getNodeById( node2.getId() ); fail( "Node should not exist, previous tx didn't rollback" ); } catch ( NotFoundException e ) { // good } } @Test public void testNodeRelDeleteSemantics() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel1 = node1.createRelationshipTo( node2, MyRelTypes.TEST ); Relationship rel2 = node1.createRelationshipTo( node2, MyRelTypes.TEST ); node1.setProperty( "key1", "value1" ); rel1.setProperty( "key1", "value1" ); newTransaction(); node1.delete(); try { node1.getProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { node1.setProperty( "key1", "value2" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { node1.removeProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } node2.delete(); try { node2.delete(); fail( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } clearCache(); assertEquals( node1, getGraphDb().getNodeById( node1.getId() ) ); assertEquals( node2, getGraphDb().getNodeById( node2.getId() ) ); try { node1.getProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { node1.setProperty( "key1", "value2" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { node1.removeProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } assertEquals( "value1", rel1.getProperty( "key1" ) ); rel1.delete(); try { rel1.delete(); fail( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { rel1.getProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { rel1.setProperty( "key1", "value2" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { rel1.removeProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } clearCache(); assertEquals( rel1, getGraphDb().getRelationshipById( rel1.getId() ) ); try { rel1.getProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { rel1.setProperty( "key1", "value2" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { rel1.removeProperty( "key1" ); fail ( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } try { node2.createRelationshipTo( node1, MyRelTypes.TEST ); fail( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } clearCache(); try { node2.createRelationshipTo( node1, MyRelTypes.TEST ); fail( "Should throw exception" ); } catch ( IllegalStateException e ) { // good } assertEquals( rel2, node1.getSingleRelationship( MyRelTypes.TEST, Direction.OUTGOING ) ); clearCache(); assertEquals( rel2, node2.getSingleRelationship( MyRelTypes.TEST, Direction.INCOMING ) ); clearCache(); assertEquals( node1, rel1.getStartNode() ); clearCache(); assertEquals( node2, rel2.getEndNode() ); Node[] nodes = rel1.getNodes(); assertEquals( node1, nodes[0] ); assertEquals( node2, nodes[1] ); clearCache(); assertEquals( node2, rel1.getOtherNode( node1 ) ); rel2.delete(); // will be marked for rollback so commit will throw exception rollback(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNeo4jConstrains.java
905
public class TestNeo4jCacheAndPersistence extends AbstractNeo4jTestCase { private long node1Id = -1; private long node2Id = -1; private final String key1 = "key1"; private final String key2 = "key2"; private final String arrayKey = "arrayKey"; private final Integer int1 = new Integer( 1 ); private final Integer int2 = new Integer( 2 ); private final String string1 = new String( "1" ); private final String string2 = new String( "2" ); private final int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7 }; @Before public void createTestingGraph() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); node1Id = node1.getId(); node2Id = node2.getId(); node1.setProperty( key1, int1 ); node1.setProperty( key2, string1 ); node2.setProperty( key1, int2 ); node2.setProperty( key2, string2 ); rel.setProperty( key1, int1 ); rel.setProperty( key2, string1 ); node1.setProperty( arrayKey, array ); node2.setProperty( arrayKey, array ); rel.setProperty( arrayKey, array ); // assertTrue( node1.getProperty( key1 ).equals( 1 ) ); Transaction tx = getTransaction(); tx.success(); tx.finish(); clearCache(); tx = getGraphDb().beginTx(); // node1.getPropertyKeys().iterator().next(); assertTrue( node1.getProperty( key1 ).equals( 1 ) ); setTransaction( tx ); } @After public void deleteTestingGraph() { Node node1 = getGraphDb().getNodeById( node1Id ); Node node2 = getGraphDb().getNodeById( node2Id ); node1.getSingleRelationship( MyRelTypes.TEST, Direction.BOTH ).delete(); node1.delete(); node2.delete(); } @Test public void testAddProperty() { String key3 = "key3"; Node node1 = getGraphDb().getNodeById( node1Id ); Node node2 = getGraphDb().getNodeById( node2Id ); Relationship rel = node1.getSingleRelationship( MyRelTypes.TEST, Direction.BOTH ); // add new property node2.setProperty( key3, int1 ); rel.setProperty( key3, int2 ); assertTrue( node1.hasProperty( key1 ) ); assertTrue( node2.hasProperty( key1 ) ); assertTrue( node1.hasProperty( key2 ) ); assertTrue( node2.hasProperty( key2 ) ); assertTrue( node1.hasProperty( arrayKey ) ); assertTrue( node2.hasProperty( arrayKey ) ); assertTrue( rel.hasProperty( arrayKey ) ); assertTrue( !node1.hasProperty( key3 ) ); assertTrue( node2.hasProperty( key3 ) ); assertEquals( int1, node1.getProperty( key1 ) ); assertEquals( int2, node2.getProperty( key1 ) ); assertEquals( string1, node1.getProperty( key2 ) ); assertEquals( string2, node2.getProperty( key2 ) ); assertEquals( int1, rel.getProperty( key1 ) ); assertEquals( string1, rel.getProperty( key2 ) ); assertEquals( int2, rel.getProperty( key3 ) ); } @Test public void testNodeRemoveProperty() { Node node1 = getGraphDb().getNodeById( node1Id ); Node node2 = getGraphDb().getNodeById( node2Id ); Relationship rel = node1.getSingleRelationship( MyRelTypes.TEST, Direction.BOTH ); // test remove property assertEquals( 1, node1.removeProperty( key1 ) ); assertEquals( 2, node2.removeProperty( key1 ) ); assertEquals( 1, rel.removeProperty( key1 ) ); assertEquals( string1, node1.removeProperty( key2 ) ); assertEquals( string2, node2.removeProperty( key2 ) ); assertEquals( string1, rel.removeProperty( key2 ) ); assertTrue( node1.removeProperty( arrayKey ) != null ); assertTrue( node2.removeProperty( arrayKey ) != null ); assertTrue( rel.removeProperty( arrayKey ) != null ); } @Test public void testNodeChangeProperty() { Node node1 = getGraphDb().getNodeById( node1Id ); Node node2 = getGraphDb().getNodeById( node2Id ); Relationship rel = node1.getSingleRelationship( MyRelTypes.TEST, Direction.BOTH ); // test change property node1.setProperty( key1, int2 ); node2.setProperty( key1, int1 ); rel.setProperty( key1, int2 ); int[] newIntArray = new int[] { 3, 2, 1 }; node1.setProperty( arrayKey, newIntArray ); node2.setProperty( arrayKey, newIntArray ); rel.setProperty( arrayKey, newIntArray ); } @Test public void testNodeGetProperties() { Node node1 = getGraphDb().getNodeById( node1Id ); assertTrue( !node1.hasProperty( null ) ); Iterator<String> keys = node1.getPropertyKeys().iterator(); keys.next(); keys.next(); assertTrue( node1.hasProperty( key1 ) ); assertTrue( node1.hasProperty( key2 ) ); } private Relationship[] getRelationshipArray( Iterable<Relationship> relsIterable ) { ArrayList<Relationship> relList = new ArrayList<Relationship>(); for ( Relationship rel : relsIterable ) { relList.add( rel ); } return relList.toArray( new Relationship[relList.size()] ); } @Test public void testDirectedRelationship1() { Node node1 = getGraphDb().getNodeById( node1Id ); Relationship rel = node1.getSingleRelationship( MyRelTypes.TEST, Direction.BOTH ); Node nodes[] = rel.getNodes(); assertEquals( 2, nodes.length ); Node node2 = getGraphDb().getNodeById( node2Id ); assertTrue( nodes[0].equals( node1 ) && nodes[1].equals( node2 ) ); assertEquals( node1, rel.getStartNode() ); assertEquals( node2, rel.getEndNode() ); Relationship relArray[] = getRelationshipArray( node1.getRelationships( MyRelTypes.TEST, Direction.OUTGOING ) ); assertEquals( 1, relArray.length ); assertEquals( rel, relArray[0] ); relArray = getRelationshipArray( node2.getRelationships( MyRelTypes.TEST, Direction.INCOMING ) ); assertEquals( 1, relArray.length ); assertEquals( rel, relArray[0] ); } @Test public void testRelCountInSameTx() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); assertEquals( 1, getRelationshipArray( node1.getRelationships() ).length ); assertEquals( 1, getRelationshipArray( node2.getRelationships() ).length ); rel.delete(); assertEquals( 0, getRelationshipArray( node1.getRelationships() ).length ); assertEquals( 0, getRelationshipArray( node2.getRelationships() ).length ); node1.delete(); node2.delete(); } @Test public void testGetDirectedRelationship() { Node node1 = getGraphDb().getNodeById( node1Id ); Relationship rel = node1.getSingleRelationship( MyRelTypes.TEST, Direction.OUTGOING ); assertEquals( int1, rel.getProperty( key1 ) ); } @Test public void testSameTxWithArray() { getTransaction().success(); getTransaction().finish(); newTransaction(); Node nodeA = getGraphDb().createNode(); Node nodeB = getGraphDb().createNode(); Relationship relA = nodeA.createRelationshipTo( nodeB, MyRelTypes.TEST ); nodeA.setProperty( arrayKey, array ); relA.setProperty( arrayKey, array ); clearCache(); assertTrue( nodeA.getProperty( arrayKey ) != null ); assertTrue( relA.getProperty( arrayKey ) != null ); relA.delete(); nodeA.delete(); nodeB.delete(); } @Test public void testAddCacheCleared() { Node nodeA = getGraphDb().createNode(); nodeA.setProperty( "1", 1 ); Node nodeB = getGraphDb().createNode(); Relationship rel = nodeA.createRelationshipTo( nodeB, MyRelTypes.TEST ); rel.setProperty( "1", 1 ); getTransaction().success(); getTransaction().finish(); newTransaction(); clearCache(); nodeA.createRelationshipTo( nodeB, MyRelTypes.TEST ); int count = 0; for ( Relationship relToB : nodeA.getRelationships( MyRelTypes.TEST ) ) { count++; } assertEquals( 2, count ); nodeA.setProperty( "2", 2 ); assertEquals( 1, nodeA.getProperty( "1" ) ); rel.setProperty( "2", 2 ); assertEquals( 1, rel.getProperty( "1" ) ); clearCache(); // trigger empty load getGraphDb().getNodeById( nodeA.getId() ); getGraphDb().getRelationshipById( rel.getId() ); // apply COW maps getTransaction().success(); getTransaction().finish(); newTransaction(); count = 0; for ( Relationship relToB : nodeA.getRelationships( MyRelTypes.TEST ) ) { count++; } assertEquals( 2, count ); assertEquals( 1, nodeA.getProperty( "1" ) ); assertEquals( 1, rel.getProperty( "1" ) ); assertEquals( 2, nodeA.getProperty( "2" ) ); assertEquals( 2, rel.getProperty( "2" ) ); } @Test public void testTxCacheLoadIsolation() throws Exception { Node node = getGraphDb().createNode(); node.setProperty( "someproptest", "testing" ); Node node1 = getGraphDb().createNode(); node1.setProperty( "someotherproptest", 2 ); commit(); TransactionManager txManager = getGraphDbAPI().getDependencyResolver().resolveDependency( TransactionManager.class ); txManager.begin(); node.setProperty( "someotherproptest", "testing2" ); Relationship rel = node.createRelationshipTo( node1, MyRelTypes.TEST ); javax.transaction.Transaction txA = txManager.suspend(); txManager.begin(); assertEquals( "testing", node.getProperty( "someproptest" ) ); assertTrue( !node.hasProperty( "someotherproptest" ) ); assertTrue( !node.hasRelationship() ); clearCache(); assertEquals( "testing", node.getProperty( "someproptest" ) ); assertTrue( !node.hasProperty( "someotherproptest" ) ); javax.transaction.Transaction txB = txManager.suspend(); txManager.resume( txA ); assertEquals( "testing", node.getProperty( "someproptest" ) ); assertTrue( node.hasProperty( "someotherproptest" ) ); assertTrue( node.hasRelationship() ); clearCache(); assertEquals( "testing", node.getProperty( "someproptest" ) ); assertTrue( node.hasProperty( "someotherproptest" ) ); assertTrue( node.hasRelationship() ); txManager.suspend(); txManager.resume( txB ); assertEquals( "testing", node.getProperty( "someproptest" ) ); assertTrue( !node.hasProperty( "someotherproptest" ) ); assertTrue( !node.hasRelationship() ); txManager.rollback(); txManager.resume( txA ); node.delete(); node1.delete(); rel.delete(); txManager.commit(); newTransaction(); } @Test public void testNodeMultiRemoveProperty() { Node node = getGraphDb().createNode(); node.setProperty( "key0", "0" ); node.setProperty( "key1", "1" ); node.setProperty( "key2", "2" ); node.setProperty( "key3", "3" ); node.setProperty( "key4", "4" ); newTransaction(); node.removeProperty( "key3" ); node.removeProperty( "key2" ); node.removeProperty( "key3" ); newTransaction(); clearCache(); assertEquals( "0", node.getProperty( "key0" ) ); assertEquals( "1", node.getProperty( "key1" ) ); assertEquals( "4", node.getProperty( "key4" ) ); assertTrue( !node.hasProperty( "key2" ) ); assertTrue( !node.hasProperty( "key3" ) ); node.delete(); } @Test public void testRelMultiRemoveProperty() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.setProperty( "key0", "0" ); rel.setProperty( "key1", "1" ); rel.setProperty( "key2", "2" ); rel.setProperty( "key3", "3" ); rel.setProperty( "key4", "4" ); newTransaction(); rel.removeProperty( "key3" ); rel.removeProperty( "key2" ); rel.removeProperty( "key3" ); newTransaction(); clearCache(); assertEquals( "0", rel.getProperty( "key0" ) ); assertEquals( "1", rel.getProperty( "key1" ) ); assertEquals( "4", rel.getProperty( "key4" ) ); assertTrue( !rel.hasProperty( "key2" ) ); assertTrue( !rel.hasProperty( "key3" ) ); rel.delete(); node1.delete(); node2.delete(); } @Test public void testRelationshipCachingIterator() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rels[] = new Relationship[100]; for ( int i = 0; i < rels.length; i++ ) { if ( i < 50 ) { rels[i] = node1.createRelationshipTo( node2, MyRelTypes.TEST ); } else { rels[i] = node2.createRelationshipTo( node1, MyRelTypes.TEST ); } } newTransaction(); clearCache(); Iterable<Relationship> relIterable = node1.getRelationships(); Set<Relationship> relSet = new HashSet<Relationship>(); for ( Relationship rel : rels ) { rel.delete(); relSet.add( rel ); } newTransaction(); assertEquals( relSet, new HashSet<Relationship>( IteratorUtil.asCollection( relIterable ) ) ); node1.delete(); node2.delete(); } @Test public void testLowGrabSize() { Map<String,String> config = new HashMap<String,String>(); config.put( "relationship_grab_size", "1" ); String storePath = getStorePath( "neo2" ); deleteFileOrDirectory( storePath ); GraphDatabaseService graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( config ).newGraphDatabase(); Transaction tx = graphDb.beginTx(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.createRelationshipTo( node2, MyRelTypes.TEST ); node2.createRelationshipTo( node1, MyRelTypes.TEST2 ); node1.createRelationshipTo( node2, MyRelTypes.TEST_TRAVERSAL ); tx.success(); tx.finish(); tx = graphDb.beginTx(); Set<Relationship> rels = new HashSet<Relationship>(); RelationshipType types[] = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST2, MyRelTypes.TEST_TRAVERSAL }; clearCache(); for ( Relationship rel : node1.getRelationships( types ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 3, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node1.getRelationships() ) { assertTrue( rels.add( rel ) ); } assertEquals( 3, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node2.getRelationships( types ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 3, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node2.getRelationships() ) { assertTrue( rels.add( rel ) ); } assertEquals( 3, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node1.getRelationships( Direction.OUTGOING ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 2, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node1.getRelationships( Direction.INCOMING ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 1, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node2.getRelationships( Direction.OUTGOING ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 1, rels.size() ); rels.clear(); clearCache(); for ( Relationship rel : node2.getRelationships( Direction.INCOMING ) ) { assertTrue( rels.add( rel ) ); } assertEquals( 2, rels.size() ); tx.success(); tx.finish(); graphDb.shutdown(); } @Test public void testAnotherLowGrabSize() { testLowGrabSize( false ); } @Test public void testAnotherLowGrabSizeWithLoops() { testLowGrabSize( true ); } private void testLowGrabSize( boolean includeLoops ) { Map<String, String> config = new HashMap<String, String>(); config.put( "relationship_grab_size", "2" ); String storePath = getStorePath( "neo2" ); deleteFileOrDirectory( storePath ); GraphDatabaseService graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( config ).newGraphDatabase(); Transaction tx = graphDb.beginTx(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); // These are expected relationships for node2 Collection<Relationship> outgoingOriginal = new HashSet<Relationship>(); Collection<Relationship> incomingOriginal = new HashSet<Relationship>(); Collection<Relationship> loopsOriginal = new HashSet<Relationship>(); int total = 0; int totalOneDirection = 0; for ( int i = 0; i < 33; i++ ) { if ( includeLoops ) { loopsOriginal.add( node2.createRelationshipTo( node2, MyRelTypes.TEST ) ); total++; totalOneDirection++; } if ( i % 2 == 0 ) { incomingOriginal.add( node1.createRelationshipTo( node2, MyRelTypes.TEST ) ); outgoingOriginal.add( node2.createRelationshipTo( node3, MyRelTypes.TEST ) ); } else { outgoingOriginal.add( node2.createRelationshipTo( node1, MyRelTypes.TEST ) ); incomingOriginal.add( node3.createRelationshipTo( node2, MyRelTypes.TEST ) ); } total += 2; totalOneDirection++; } tx.success(); tx.finish(); tx = graphDb.beginTx(); Set<Relationship> rels = new HashSet<Relationship>(); clearCache(); Collection<Relationship> outgoing = new HashSet<Relationship>( outgoingOriginal ); Collection<Relationship> incoming = new HashSet<Relationship>( incomingOriginal ); Collection<Relationship> loops = new HashSet<Relationship>( loopsOriginal ); for ( Relationship rel : node2.getRelationships( MyRelTypes.TEST ) ) { assertTrue( rels.add( rel ) ); if ( rel.getStartNode().equals( node2 ) && rel.getEndNode().equals( node2 ) ) { assertTrue( loops.remove( rel ) ); } else if ( rel.getStartNode().equals( node2 ) ) { assertTrue( outgoing.remove( rel ) ); } else { assertTrue( incoming.remove( rel ) ); } } assertEquals( total, rels.size() ); assertEquals( 0, loops.size() ); assertEquals( 0, incoming.size() ); assertEquals( 0, outgoing.size() ); rels.clear(); clearCache(); outgoing = new HashSet<Relationship>( outgoingOriginal ); incoming = new HashSet<Relationship>( incomingOriginal ); loops = new HashSet<Relationship>( loopsOriginal ); for ( Relationship rel : node2.getRelationships( Direction.OUTGOING ) ) { assertTrue( rels.add( rel ) ); if ( rel.getStartNode().equals( node2 ) && rel.getEndNode().equals( node2 ) ) { assertTrue( loops.remove( rel ) ); } else if ( rel.getStartNode().equals( node2 ) ) { assertTrue( outgoing.remove( rel ) ); } else { fail( "There should be no incomming relationships " + rel ); } } assertEquals( totalOneDirection, rels.size() ); assertEquals( 0, loops.size() ); assertEquals( 0, outgoing.size() ); rels.clear(); clearCache(); outgoing = new HashSet<Relationship>( outgoingOriginal ); incoming = new HashSet<Relationship>( incomingOriginal ); loops = new HashSet<Relationship>( loopsOriginal ); for ( Relationship rel : node2.getRelationships( Direction.INCOMING ) ) { assertTrue( rels.add( rel ) ); if ( rel.getStartNode().equals( node2 ) && rel.getEndNode().equals( node2 ) ) { assertTrue( loops.remove( rel ) ); } else if ( rel.getEndNode().equals( node2 ) ) { assertTrue( incoming.remove( rel ) ); } else { fail( "There should be no outgoing relationships " + rel ); } } assertEquals( totalOneDirection, rels.size() ); assertEquals( 0, loops.size() ); assertEquals( 0, incoming.size() ); rels.clear(); tx.success(); tx.finish(); graphDb.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNeo4jCacheAndPersistence.java
906
public class TestNeo4jApiExceptions { @Test public void testNotInTransactionException() { Node node1 = graph.createNode(); node1.setProperty( "test", 1 ); Node node2 = graph.createNode(); Node node3 = graph.createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); rel.setProperty( "test", 11 ); commit(); try { graph.createNode(); fail( "Create node with no transaction should throw exception" ); } catch ( NotInTransactionException e ) { // good } try { node1.createRelationshipTo( node2, MyRelTypes.TEST ); fail( "Create relationship with no transaction should " + "throw exception" ); } catch ( NotInTransactionException e ) { // good } try { node1.setProperty( "test", 2 ); fail( "Set property with no transaction should throw exception" ); } catch ( NotInTransactionException e ) { // good } try { rel.setProperty( "test", 22 ); fail( "Set property with no transaction should throw exception" ); } catch ( NotInTransactionException e ) { // good } try { node3.delete(); fail( "Delete node with no transaction should " + "throw exception" ); } catch ( NotInTransactionException e ) { // good } try { rel.delete(); fail( "Delete relationship with no transaction should " + "throw exception" ); } catch ( NotInTransactionException e ) { // good } newTransaction(); assertEquals( node1.getProperty( "test" ), 1 ); assertEquals( rel.getProperty( "test" ), 11 ); assertEquals( rel, node1.getSingleRelationship( MyRelTypes.TEST, Direction.OUTGOING ) ); node1.delete(); node2.delete(); rel.delete(); node3.delete(); // Finally rollback(); } @Test public void testNotFoundException() { Node node1 = graph.createNode(); Node node2 = graph.createNode(); Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST ); long nodeId = node1.getId(); long relId = rel.getId(); rel.delete(); node2.delete(); node1.delete(); newTransaction(); try { graph.getNodeById( nodeId ); fail( "Get node by id on deleted node should throw exception" ); } catch ( NotFoundException e ) { // good } try { graph.getRelationshipById( relId ); fail( "Get relationship by id on deleted node should " + "throw exception" ); } catch ( NotFoundException e ) { // good } // Finally rollback(); } @Test public void shouldGiveNiceErrorWhenShutdownKernelApi() { GraphDatabaseService graphDb = graph; Node node = graphDb.createNode(); commit(); graphDb.shutdown(); try { asList( node.getLabels().iterator() ); fail( "Did not get a nice exception" ); } catch ( DatabaseShutdownException e ) { // good } } @Test public void shouldGiveNiceErrorWhenShutdownLegacy() { GraphDatabaseService graphDb = graph; Node node = graphDb.createNode(); commit(); graphDb.shutdown(); try { node.getRelationships(); fail( "Did not get a nice exception" ); } catch ( DatabaseShutdownException e ) { // good } try { graphDb.createNode(); fail( "Create node did not produce expected error" ); } catch ( DatabaseShutdownException e ) { // good } } private Transaction tx; private GraphDatabaseService graph; private void newTransaction() { if ( tx != null ) { tx.success(); tx.close(); } tx = graph.beginTx(); } public void commit() { if ( tx != null ) { tx.success(); tx.close(); tx = null; } } public void rollback() { if ( tx != null ) { tx.close(); tx = null; } } @Before public void init() { graph = new TestGraphDatabaseFactory().newImpermanentDatabase(); newTransaction(); } @After public void cleanUp() { rollback(); graph.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNeo4jApiExceptions.java
907
public class TestNeo4j extends AbstractNeo4jTestCase { @Test public void testBasicNodeRelationships() { Node firstNode; Node secondNode; Relationship rel; // Create nodes and a relationship between them firstNode = getGraphDb().createNode(); assertNotNull( "Failure creating first node", firstNode ); secondNode = getGraphDb().createNode(); assertNotNull( "Failure creating second node", secondNode ); rel = firstNode.createRelationshipTo( secondNode, MyRelTypes.TEST ); assertNotNull( "Relationship is null", rel ); RelationshipType relType = rel.getType(); assertNotNull( "Relationship's type is is null", relType ); // Verify that the node reports that it has a relationship of // the type we created above assertTrue( firstNode.getRelationships( relType ).iterator().hasNext() ); assertTrue( secondNode.getRelationships( relType ).iterator().hasNext() ); Iterable<Relationship> allRels; // Verify that both nodes return the relationship we created above allRels = firstNode.getRelationships(); assertTrue( this.objectExistsInIterable( rel, allRels ) ); allRels = firstNode.getRelationships( relType ); assertTrue( this.objectExistsInIterable( rel, allRels ) ); allRels = secondNode.getRelationships(); assertTrue( this.objectExistsInIterable( rel, allRels ) ); allRels = secondNode.getRelationships( relType ); assertTrue( this.objectExistsInIterable( rel, allRels ) ); // Verify that the relationship reports that it is associated with // firstNode and secondNode Node[] relNodes = rel.getNodes(); assertEquals( "A relationship should always be connected to exactly " + "two nodes", relNodes.length, 2 ); assertTrue( "Relationship says that it isn't connected to firstNode", this.objectExistsInArray( firstNode, relNodes ) ); assertTrue( "Relationship says that it isn't connected to secondNode", this.objectExistsInArray( secondNode, relNodes ) ); assertTrue( "The other node should be secondNode but it isn't", rel .getOtherNode( firstNode ).equals( secondNode ) ); assertTrue( "The other node should be firstNode but it isn't", rel .getOtherNode( secondNode ).equals( firstNode ) ); rel.delete(); secondNode.delete(); firstNode.delete(); } private boolean objectExistsInIterable( Relationship rel, Iterable<Relationship> allRels ) { for ( Relationship iteratedRel : allRels ) { if ( rel.equals( iteratedRel ) ) { return true; } } return false; } private boolean objectExistsInArray( Object obj, Object[] objArray ) { for ( int i = 0; i < objArray.length; i++ ) { if ( objArray[i].equals( obj ) ) { return true; } } return false; } // private static enum RelTypes implements RelationshipType // { // ONE_MORE_RELATIONSHIP; // } // TODO: fix this testcase @Test public void testIdUsageInfo() { NodeManager nm = getGraphDbAPI().getDependencyResolver().resolveDependency( NodeManager.class ); long nodeCount = nm.getNumberOfIdsInUse( Node.class ); long relCount = nm.getNumberOfIdsInUse( Relationship.class ); if ( nodeCount > nm.getHighestPossibleIdInUse( Node.class ) ) { // fail( "Node count greater than highest id " + nodeCount ); } if ( relCount > nm.getHighestPossibleIdInUse( Relationship.class ) ) { // fail( "Rel count greater than highest id " + relCount ); } // assertTrue( nodeCount <= nm.getHighestPossibleIdInUse( Node.class ) // ); // assertTrue( relCount <= nm.getHighestPossibleIdInUse( // Relationship.class ) ); Node n1 = nm.createNode(); Node n2 = nm.createNode(); Relationship r1 = n1.createRelationshipTo( n2, MyRelTypes.TEST ); // assertEquals( nodeCount + 2, nm.getNumberOfIdsInUse( Node.class ) ); // assertEquals( relCount + 1, nm.getNumberOfIdsInUse( // Relationship.class ) ); r1.delete(); n1.delete(); n2.delete(); // must commit for ids to be reused getTransaction().success(); getTransaction().finish(); // assertEquals( nodeCount, nm.getNumberOfIdsInUse( Node.class ) ); // assertEquals( relCount, nm.getNumberOfIdsInUse( Relationship.class ) // ); setTransaction( getGraphDb().beginTx() ); } @Test public void testRandomPropertyName() { Node node1 = getGraphDb().createNode(); String key = "random_" + new Random( System.currentTimeMillis() ).nextLong(); node1.setProperty( key, "value" ); assertEquals( "value", node1.getProperty( key ) ); node1.delete(); } @Test public void testNodeChangePropertyArray() throws Exception { getTransaction().finish(); Node node; try ( Transaction tx = getGraphDb().beginTx() ) { node = getGraphDb().createNode(); tx.success(); } try ( Transaction tx = getGraphDb().beginTx() ) { node.setProperty( "test", new String[] { "value1" } ); tx.success(); } try (Transaction ignored = getGraphDb().beginTx() ) { node.setProperty( "test", new String[] { "value1", "value2" } ); // no success, we wanna test rollback on this operation } try (Transaction tx = getGraphDb().beginTx() ) { String[] value = (String[]) node.getProperty( "test" ); assertEquals( 1, value.length ); assertEquals( "value1", value[0] ); tx.success(); } setTransaction( getGraphDb().beginTx() ); } @Test @Ignore // This test wasn't executed before, because of some JUnit bug. // And it fails with NPE. public void testMultipleNeos() { String storePath = getStorePath( "test-neo2" ); deleteFileOrDirectory( storePath ); GraphDatabaseService graphDb2 = new GraphDatabaseFactory().newEmbeddedDatabase( storePath ); Transaction tx2 = graphDb2.beginTx(); getGraphDb().createNode(); graphDb2.createNode(); tx2.success(); tx2.finish(); graphDb2.shutdown(); } @Test public void testGetAllNodes() { long highId = getNodeManager().getHighestPossibleIdInUse( Node.class ); if ( highId >= 0 && highId < 10000 ) { int count = IteratorUtil.count( GlobalGraphOperations.at( getGraphDb() ).getAllNodes() ); boolean found = false; Node newNode = getGraphDb().createNode(); newTransaction(); int oldCount = count; count = 0; for ( Node node : GlobalGraphOperations.at( getGraphDb() ).getAllNodes() ) { count++; if ( node.equals( newNode ) ) { found = true; } } assertTrue( found ); assertEquals( count, oldCount + 1 ); // Tests a bug in the "all nodes" iterator Iterator<Node> allNodesIterator = GlobalGraphOperations.at( getGraphDb() ).getAllNodes().iterator(); assertNotNull( allNodesIterator.next() ); newNode.delete(); newTransaction(); found = false; count = 0; for ( Node node : GlobalGraphOperations.at( getGraphDb() ).getAllNodes() ) { count++; if ( node.equals( newNode ) ) { found = true; } } assertTrue( !found ); assertEquals( count, oldCount ); } // else we skip test, takes too long } @Test public void testMultipleShutdown() { commit(); getGraphDb().shutdown(); getGraphDb().shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestNeo4j.java
908
{ protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( cache_type, "weak" ); builder.setConfig( relationship_grab_size, "" + (relCount/2) ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentRelationshipChainLoadingIssue.java
909
public class TestConcurrentRelationshipChainLoadingIssue { private final int relCount = 2; public final @Rule ImpermanentDatabaseRule graphDb = new ImpermanentDatabaseRule() { protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( cache_type, "weak" ); builder.setConfig( relationship_grab_size, "" + (relCount/2) ); } }; @Test public void tryToTriggerRelationshipLoadingStoppingMidWay() throws Throwable { GraphDatabaseAPI db = graphDb.getGraphDatabaseAPI(); Node node = createNodeWithRelationships( db ); checkStateToHelpDiagnoseFlakeyTest( db, node ); long end = currentTimeMillis()+SECONDS.toMillis( 5 ); int iterations = 0; while ( currentTimeMillis() < end ) tryOnce( db, node, iterations++ ); } private void checkStateToHelpDiagnoseFlakeyTest( GraphDatabaseAPI db, Node node ) { loadNode( db, node ); db.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); loadNode( db, node ); } private void loadNode( GraphDatabaseAPI db, Node node ) { try (Transaction ignored = db.beginTx()) { count( node.getRelationships() ); } } private void awaitStartSignalAndRandomTimeLonger( final CountDownLatch startSignal ) { try { startSignal.await(); idleLoop( (int) (System.currentTimeMillis()%100000) ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } private void tryOnce( final GraphDatabaseAPI db, final Node node, int iterations ) throws Throwable { db.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); ExecutorService executor = newCachedThreadPool(); final CountDownLatch startSignal = new CountDownLatch( 1 ); int threads = getRuntime().availableProcessors(); final List<Throwable> errors = Collections.synchronizedList( new ArrayList<Throwable>() ); for ( int i = 0; i < threads; i++ ) { executor.submit( new Runnable() { @Override public void run() { awaitStartSignalAndRandomTimeLonger( startSignal ); Transaction transaction = db.beginTx(); try { assertEquals( relCount, count( node.getRelationships() ) ); } catch ( Throwable e ) { errors.add( e ); } finally { transaction.finish(); } } } ); } startSignal.countDown(); executor.shutdown(); executor.awaitTermination( 10, SECONDS ); if ( !errors.isEmpty() ) throw new MultipleCauseException( format("Exception(s) after %s iterations with %s threads", iterations, threads), errors ); } private static int idleLoop( int l ) { // Use atomic integer to disable the JVM from rewriting this loop to simple addition. AtomicInteger i = new AtomicInteger( 0 ); for ( int j = 0; j < l; j++ ) i.incrementAndGet(); return i.get(); } private Node createNodeWithRelationships( GraphDatabaseAPI db ) { Transaction tx = db.beginTx(); Node node; try { node = db.createNode(); for ( int i = 0; i < relCount / 2; i++ ) node.createRelationshipTo( node, MyRelTypes.TEST ); for ( int i = 0; i < relCount / 2; i++ ) node.createRelationshipTo( node, MyRelTypes.TEST2 ); tx.success(); return node; } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentRelationshipChainLoadingIssue.java
910
{ @Override public void run() { deleteRelationshipInSameThread( db, toDelete); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentModificationOfRelationshipChains.java
911
{ @Override protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( GraphDatabaseSettings.relationship_grab_size, ""+RelationshipGrabSize ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentModificationOfRelationshipChains.java
912
public class PropertyKeyTokenHolder extends TokenHolder<Token> { public PropertyKeyTokenHolder( AbstractTransactionManager transactionManager, PersistenceManager persistenceManager, EntityIdGenerator idGenerator, TokenCreator tokenCreator ) { super( transactionManager, persistenceManager, idGenerator, tokenCreator ); } @Override protected Token newToken( String name, int id ) { return new Token( name, id ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_PropertyKeyTokenHolder.java
913
class PropertyEventData { private final String key; private final Object value; public PropertyEventData( String key, Object value ) { this.key = key; this.value = value; } public String getKey() { return key; } public Object getValue() { return value; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_PropertyEventData.java
914
class PropertyEntryImpl<T extends PropertyContainer> implements PropertyEntry<T> { private final T entity; private final String key; private final Object value; private final Object valueBeforeTransaction; private PropertyEntryImpl( T entity, String key, Object value, Object valueBeforeTransaction ) { this.entity = entity; this.key = key; this.value = value; this.valueBeforeTransaction = valueBeforeTransaction; } static <T extends PropertyContainer> PropertyEntry<T> assigned( T entity, String key, Object value, Object valueBeforeTransaction ) { if ( value == null ) { throw new IllegalArgumentException( "Null value" ); } return new PropertyEntryImpl<T>( entity, key, value, valueBeforeTransaction ); } static <T extends PropertyContainer> PropertyEntry<T> removed( T entity, String key, Object valueBeforeTransaction ) { return new PropertyEntryImpl<T>( entity, key, null, valueBeforeTransaction ); } public T entity() { return this.entity; } public String key() { return this.key; } public Object previouslyCommitedValue() { return this.valueBeforeTransaction; } public Object value() { if ( this.value == null ) { throw new IllegalStateException( "PropertyEntry[" + entity + ", " + key + "] has no value, it represents a removed property" ); } return this.value; } @Override public String toString() { return "PropertyEntry[entity:" + entity + ", key:" + key + ", value:" + value + ", valueBeforeTx:" + valueBeforeTransaction + "]"; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_PropertyEntryImpl.java
915
public abstract class Primitive implements SizeOfObject { // Used for marking that properties have been loaded but there just wasn't any. // Saves an extra trip down to the store layer. protected static final DefinedProperty[] NO_PROPERTIES = new DefinedProperty[0]; Primitive( boolean newPrimitive ) { if ( newPrimitive ) { setEmptyProperties(); } } public abstract long getId(); public Iterator<DefinedProperty> getProperties( CacheLoader<Iterator<DefinedProperty>> loader, CacheUpdateListener updateListener ) { return ensurePropertiesLoaded( loader, updateListener ); } public Property getProperty( CacheLoader<Iterator<DefinedProperty>> loader, CacheUpdateListener updateListener, int key ) { ensurePropertiesLoaded( loader, updateListener ); return getCachedProperty( key ); } public PrimitiveLongIterator getPropertyKeys( CacheLoader<Iterator<DefinedProperty>> cacheLoader, CacheUpdateListener updateListener ) { ensurePropertiesLoaded( cacheLoader, updateListener ); return getCachedPropertyKeys(); } private Iterator<DefinedProperty> ensurePropertiesLoaded( CacheLoader<Iterator<DefinedProperty>> loader, CacheUpdateListener updateListener ) { if ( !hasLoadedProperties() ) { synchronized ( this ) { if ( !hasLoadedProperties() ) { try { Iterator<DefinedProperty> loadedProperties = loader.load( getId() ); setProperties( loadedProperties ); updateListener.newSize( this, sizeOfObjectInBytesIncludingOverhead() ); } catch ( InvalidRecordException | EntityNotFoundException e ) { throw new NotFoundException( this + " not found. This can be because someone " + "else deleted this entity while we were trying to read properties from it, or because of " + "concurrent modification of other properties on this entity. The problem should be temporary.", e ); } } } } return getCachedProperties(); } protected abstract Iterator<DefinedProperty> getCachedProperties(); protected abstract Property getCachedProperty( int key ); protected abstract PrimitiveLongIterator getCachedPropertyKeys(); protected abstract boolean hasLoadedProperties(); protected abstract void setEmptyProperties(); protected abstract void setProperties( Iterator<DefinedProperty> properties ); protected abstract DefinedProperty getPropertyForIndex( int keyId ); protected abstract void commitPropertyMaps( ArrayMap<Integer, DefinedProperty> cowPropertyAddMap, ArrayMap<Integer, DefinedProperty> cowPropertyRemoveMap, long firstProp ); @Override public int hashCode() { long id = getId(); return (int) (( id >>> 32 ) ^ id ); } // Force subclasses to implement equals @Override public abstract boolean equals(Object other); private void ensurePropertiesLoaded( NodeManager nodeManager ) { // double checked locking if ( !hasLoadedProperties() ) { synchronized ( this ) { if ( !hasLoadedProperties() ) { try { setProperties( loadProperties( nodeManager ) ); } catch ( InvalidRecordException e ) { throw new NotFoundException( asProxy( nodeManager ) + " not found. This can be because someone " + "else deleted this entity while we were trying to read properties from it, or because of " + "concurrent modification of other properties on this entity. The problem should be temporary.", e ); } } } } } protected abstract Iterator<DefinedProperty> loadProperties( NodeManager nodeManager ); protected Object getCommittedPropertyValue( NodeManager nodeManager, String key ) { ensurePropertiesLoaded( nodeManager ); Token index = nodeManager.getPropertyKeyTokenOrNull( key ); if ( index != null ) { DefinedProperty property = getPropertyForIndex( index.id() ); if ( property != null ) { return property.value(); } } return null; } public abstract CowEntityElement getEntityElement( PrimitiveElement element, boolean create ); abstract PropertyContainer asProxy( NodeManager nm ); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_Primitive.java
916
public class NodeProxyTest { public final @Rule DatabaseRule dbRule = new ImpermanentDatabaseRule(); private final String PROPERTY_KEY = "PROPERTY_KEY"; private GraphDatabaseService db; @Before public void init() { db = dbRule.getGraphDatabaseService(); } @Test public void shouldThrowHumaneExceptionsWhenPropertyDoesNotExistOnNode() throws Exception { // Given a database with PROPERTY_KEY in it createNodeWith( PROPERTY_KEY ); // When trying to get property from node without it try ( Transaction ignored = db.beginTx() ) { Node node = db.createNode(); node.getProperty( PROPERTY_KEY ); fail( "Expected exception to have been thrown" ); } // Then catch ( NotFoundException exception ) { assertThat( exception.getMessage(), containsString( PROPERTY_KEY ) ); } } @Test public void shouldThrowHumaneExceptionsWhenPropertyDoesNotExist() throws Exception { // Given a database without PROPERTY_KEY in it // When try ( Transaction ignored = db.beginTx() ) { Node node = db.createNode(); node.getProperty( PROPERTY_KEY ); } // Then catch ( NotFoundException exception ) { assertThat( exception.getMessage(), containsString( PROPERTY_KEY ) ); } } private void createNodeWith( String key ) { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode(); node.setProperty( key, 1 ); tx.success(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeProxyTest.java
917
public class NodeProxy implements Node { public interface NodeLookup { NodeImpl lookup( long nodeId ); GraphDatabaseService getGraphDatabase(); NodeManager getNodeManager(); NodeImpl lookup( long nodeId, LockType lock ); } private final NodeLookup nodeLookup; private final ThreadToStatementContextBridge statementContextProvider; private final long nodeId; NodeProxy( long nodeId, NodeLookup nodeLookup, ThreadToStatementContextBridge statementContextProvider ) { this.nodeId = nodeId; this.nodeLookup = nodeLookup; this.statementContextProvider = statementContextProvider; } @Override public long getId() { return nodeId; } @Override public GraphDatabaseService getGraphDatabase() { return nodeLookup.getGraphDatabase(); } @Override public void delete() { try ( Statement statement = statementContextProvider.instance() ) { statement.dataWriteOperations().nodeDelete( getId() ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public Iterable<Relationship> getRelationships() { assertInTransaction(); return nodeLookup.lookup( nodeId ).getRelationships( nodeLookup.getNodeManager() ); } @Override public boolean hasRelationship() { assertInTransaction(); return nodeLookup.lookup( nodeId ).hasRelationship( nodeLookup.getNodeManager() ); } @Override public Iterable<Relationship> getRelationships( Direction dir ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).getRelationships( nodeLookup.getNodeManager(), dir ); } @Override public boolean hasRelationship( Direction dir ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).hasRelationship( nodeLookup.getNodeManager(), dir ); } @Override public Iterable<Relationship> getRelationships( RelationshipType... types ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).getRelationships( nodeLookup.getNodeManager(), types ); } @Override public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).getRelationships( nodeLookup.getNodeManager(), direction, types ); } @Override public boolean hasRelationship( RelationshipType... types ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).hasRelationship( nodeLookup.getNodeManager(), types ); } @Override public boolean hasRelationship( Direction direction, RelationshipType... types ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).hasRelationship( nodeLookup.getNodeManager(), direction, types ); } @Override public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).getRelationships( nodeLookup.getNodeManager(), type, dir ); } @Override public boolean hasRelationship( RelationshipType type, Direction dir ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).hasRelationship( nodeLookup.getNodeManager(), type, dir ); } @Override public Relationship getSingleRelationship( RelationshipType type, Direction dir ) { assertInTransaction(); return nodeLookup.lookup( nodeId ).getSingleRelationship( nodeLookup.getNodeManager(), type, dir ); } private void assertInTransaction() { statementContextProvider.assertInTransaction(); } @Override public void setProperty( String key, Object value ) { boolean requireRollback = true; // TODO: this seems like the wrong level to do this on... try ( Statement statement = statementContextProvider.instance() ) { int propertyKeyId = statement.tokenWriteOperations().propertyKeyGetOrCreateForName( key ); try { statement.dataWriteOperations().nodeSetProperty( nodeId, Property.property( propertyKeyId, value ) ); } catch ( ConstraintValidationKernelException e ) { requireRollback = false; throw new ConstraintViolationException( e.getUserMessage( new StatementTokenNameLookup( statement.readOperations() ) ), e ); } requireRollback = false; } catch ( EntityNotFoundException e ) { throw new NotFoundException( e ); } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } finally { if ( requireRollback ) { nodeLookup.getNodeManager().setRollbackOnly(); } } } @Override public Object removeProperty( String key ) throws NotFoundException { try ( Statement statement = statementContextProvider.instance() ) { int propertyKeyId = statement.tokenWriteOperations().propertyKeyGetOrCreateForName( key ); return statement.dataWriteOperations().nodeRemoveProperty( nodeId, propertyKeyId ).value( null ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( e ); } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public Object getProperty( String key, Object defaultValue ) { if ( null == key ) { throw new IllegalArgumentException( "(null) property key is not allowed" ); } try ( Statement statement = statementContextProvider.instance() ) { int propertyKeyId = statement.readOperations().propertyKeyGetForName( key ); return statement.readOperations().nodeGetProperty( nodeId, propertyKeyId ).value( defaultValue ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( e ); } } @Override public Iterable<String> getPropertyKeys() { try ( Statement statement = statementContextProvider.instance() ) { List<String> keys = new ArrayList<>(); Iterator<DefinedProperty> properties = statement.readOperations().nodeGetAllProperties( getId() ); while ( properties.hasNext() ) { keys.add( statement.readOperations().propertyKeyGetName( properties.next().propertyKeyId() ) ); } return keys; } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Node not found", e ); } catch ( PropertyKeyIdNotFoundKernelException e ) { throw new ThisShouldNotHappenError( "Jake", "Property key retrieved through kernel API should exist.", e ); } } @Override public Object getProperty( String key ) throws NotFoundException { if ( null == key ) { throw new IllegalArgumentException( "(null) property key is not allowed" ); } try ( Statement statement = statementContextProvider.instance() ) { try { int propertyKeyId = statement.readOperations().propertyKeyGetForName( key ); if ( propertyKeyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY ) { throw new NotFoundException( format( "No such property, '%s'.", key ) ); } return statement.readOperations().nodeGetProperty( nodeId, propertyKeyId ).value(); } catch ( EntityNotFoundException | PropertyNotFoundException e ) { throw new NotFoundException( e.getUserMessage( new StatementTokenNameLookup( statement.readOperations() ) ), e ); } } } @Override public boolean hasProperty( String key ) { if ( null == key ) { return false; } try ( Statement statement = statementContextProvider.instance() ) { int propertyKeyId = statement.readOperations().propertyKeyGetForName( key ); return statement.readOperations().nodeGetProperty( nodeId, propertyKeyId ).isDefined(); } catch ( EntityNotFoundException e ) { throw new NotFoundException( e ); } } public int compareTo( Object node ) { Node n = (Node) node; long ourId = this.getId(), theirId = n.getId(); if ( ourId < theirId ) { return -1; } else if ( ourId > theirId ) { return 1; } else { return 0; } } @Override public boolean equals( Object o ) { return o instanceof Node && this.getId() == ((Node) o).getId(); } @Override public int hashCode() { return (int) ((nodeId >>> 32) ^ nodeId); } @Override public String toString() { return "Node[" + this.getId() + "]"; } @Override public Relationship createRelationshipTo( Node otherNode, RelationshipType type ) { if ( otherNode == null ) { throw new IllegalArgumentException( "Other node is null." ); } // TODO: This is the checks we would like to do, but we have tests that expect to mix nodes... //if ( !(otherNode instanceof NodeProxy) || (((NodeProxy) otherNode).nodeLookup != nodeLookup) ) //{ // throw new IllegalArgumentException( "Nodes do not belong to same graph database." ); //} try ( Statement statement = statementContextProvider.instance() ) { long relationshipTypeId = statement.tokenWriteOperations().relationshipTypeGetOrCreateForName( type.name() ); return nodeLookup.getNodeManager().newRelationshipProxyById( statement.dataWriteOperations().relationshipCreate( relationshipTypeId, nodeId, otherNode.getId() ) ); } catch ( IllegalTokenNameException | RelationshipTypeIdNotFoundKernelException e ) { throw new IllegalArgumentException( e ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction ) { assertInTransaction(); return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipType, direction ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection ) { assertInTransaction(); return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, firstRelationshipType, firstDirection, secondRelationshipType, secondDirection ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { assertInTransaction(); return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipTypesAndDirections ); } @Override public void addLabel( Label label ) { try ( Statement statement = statementContextProvider.instance() ) { try { statement.dataWriteOperations().nodeAddLabel( getId(), statement.tokenWriteOperations().labelGetOrCreateForName( label.name() ) ); } catch ( ConstraintValidationKernelException e ) { throw new ConstraintViolationException( e.getUserMessage( new StatementTokenNameLookup( statement.readOperations() ) ), e ); } } catch ( IllegalTokenNameException e ) { throw new ConstraintViolationException( format( "Invalid label name '%s'.", label.name() ), e ); } catch ( TooManyLabelsException e ) { throw new ConstraintViolationException( "Unable to add label.", e ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( "No node with id " + getId() + " found.", e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public void removeLabel( Label label ) { try ( Statement statement = statementContextProvider.instance() ) { int labelId = statement.readOperations().labelGetForName( label.name() ); if ( labelId != KeyReadOperations.NO_SUCH_LABEL ) { statement.dataWriteOperations().nodeRemoveLabel( getId(), labelId ); } } catch ( EntityNotFoundException e ) { throw new NotFoundException( "No node with id " + getId() + " found.", e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public boolean hasLabel( Label label ) { try ( Statement statement = statementContextProvider.instance() ) { int labelId = statement.readOperations().labelGetForName( label.name() ); return statement.readOperations().nodeHasLabel( getId(), labelId ); } catch ( EntityNotFoundException e ) { return false; } } @Override public Iterable<Label> getLabels() { try ( Statement statement = statementContextProvider.instance() ) { PrimitiveIntIterator labels = statement.readOperations().nodeGetLabels( getId() ); List<Label> keys = new ArrayList<>(); while ( labels.hasNext() ) { int labelId = labels.next(); keys.add( label( statement.readOperations().labelGetName( labelId ) ) ); } return keys; } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Node not found", e ); } catch ( LabelNotFoundKernelException e ) { throw new ThisShouldNotHappenError( "Stefan", "Label retrieved through kernel API should exist." ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeProxy.java
918
private class RelationshipLoggingTracker implements PropertyTracker<Relationship> { @Override public void propertyAdded( Relationship primitive, String propertyName, Object propertyValue ) { } public String removed = ""; @Override public void propertyRemoved( Relationship primitive, String propertyName, Object propertyValue ) { removed = removed + primitive.getId() + ":" + propertyName; } @Override public void propertyChanged( Relationship primitive, String propertyName, Object oldValue, Object newValue ) { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeManagerTest.java
919
private class NodeLoggingTracker implements PropertyTracker<Node> { @Override public void propertyAdded( Node primitive, String propertyName, Object propertyValue ) { } public String removed = ""; @Override public void propertyRemoved( Node primitive, String propertyName, Object propertyValue ) { removed = removed + primitive.getId() + ":" + propertyName; } @Override public void propertyChanged( Node primitive, String propertyName, Object oldValue, Object newValue ) { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeManagerTest.java
920
{ @Override public void run() { Transaction newTx = db.beginTx(); assertThat( newTx, not( instanceOf( PlaceboTransaction.class ) ) ); db.createNode(); newTx.success(); newTx.finish(); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeManagerTest.java
921
public class NodeManagerTest { private GraphDatabaseAPI db; @Before public void init() { db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase(); } @After public void stop() { db.shutdown(); } @Test public void shouldRemoveAllPropertiesWhenDeletingNode() throws Exception { // GIVEN Node node = createNodeWith( "wut", "foo" ); NodeManager nodeManager = getNodeManager(); NodeLoggingTracker tracker = new NodeLoggingTracker(); nodeManager.addNodePropertyTracker( tracker ); // WHEN delete( node ); //THEN assertThat( tracker.removed, is( "0:wut" ) ); } @Test public void shouldNotRemovePropertyTwice() throws Exception { // GIVEN node with one property Node node = createNodeWith( "wut", "foo" ); NodeManager nodeManager = getNodeManager(); NodeLoggingTracker tracker = new NodeLoggingTracker(); nodeManager.addNodePropertyTracker( tracker ); // WHEN in the same tx, remove prop and then delete node Transaction tx = db.beginTx(); node.removeProperty( "wut" ); node.delete(); tx.success(); tx.finish(); //THEN prop is removed only once assertThat( tracker.removed, is( "0:wut" ) ); } @Test public void shouldRemoveRelationshipProperties() throws Exception { // GIVEN relationship with one property Relationship relationship = createRelationshipWith( "wut", "foo" ); NodeManager nodeManager = getNodeManager(); RelationshipLoggingTracker tracker = new RelationshipLoggingTracker(); nodeManager.addRelationshipPropertyTracker( tracker ); // WHEN delete( relationship ); //THEN prop is removed from tracker assertThat( tracker.removed, is( "0:wut" ) ); } @Test public void getAllNodesShouldConsiderTxState() throws Exception { // GIVEN // Three nodes Transaction tx = db.beginTx(); Node firstCommittedNode = db.createNode(); Node secondCommittedNode = db.createNode(); Node thirdCommittedNode = db.createNode(); tx.success(); tx.finish(); // Second one deleted, just to create a hole tx = db.beginTx(); secondCommittedNode.delete(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); Node firstAdditionalNode = db.createNode(); Node secondAdditionalNode = db.createNode(); thirdCommittedNode.delete(); List<Node> allNodes = addToCollection( getNodeManager().getAllNodes(), new ArrayList<Node>() ); Set<Node> allNodesSet = new HashSet<>( allNodes ); tx.finish(); // THEN assertEquals( allNodes.size(), allNodesSet.size() ); assertEquals( asSet( firstCommittedNode, firstAdditionalNode, secondAdditionalNode ), allNodesSet ); } @Test public void getAllRelationshipsShouldConsiderTxState() throws Exception { // GIVEN // Three relationships Transaction tx = db.beginTx(); Relationship firstCommittedRelationship = createRelationshipAssumingTxWith( "committed", 1 ); Relationship secondCommittedRelationship = createRelationshipAssumingTxWith( "committed", 2 ); Relationship thirdCommittedRelationship = createRelationshipAssumingTxWith( "committed", 3 ); tx.success(); tx.finish(); tx = db.beginTx(); secondCommittedRelationship.delete(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); Relationship firstAdditionalRelationship = createRelationshipAssumingTxWith( "additional", 1 ); Relationship secondAdditionalRelationship = createRelationshipAssumingTxWith( "additional", 2 ); thirdCommittedRelationship.delete(); List<Relationship> allRelationships = addToCollection( getNodeManager().getAllRelationships(), new ArrayList<Relationship>() ); Set<Relationship> allRelationshipsSet = new HashSet<>( allRelationships ); tx.finish(); // THEN assertEquals( allRelationships.size(), allRelationshipsSet.size() ); assertEquals( asSet( firstCommittedRelationship, firstAdditionalRelationship, secondAdditionalRelationship ), allRelationshipsSet ); } @Test public void getAllNodesIteratorShouldPickUpHigherIdsThanHighIdWhenStarted() throws Exception { // GIVEN { Transaction tx = db.beginTx(); db.createNode(); db.createNode(); tx.success(); tx.finish(); } // WHEN iterator is started Transaction transaction = db.beginTx(); Iterator<Node> allNodes = GlobalGraphOperations.at( db ).getAllNodes().iterator(); allNodes.next(); // and WHEN another node is then added Thread thread = new Thread( new Runnable() { @Override public void run() { Transaction newTx = db.beginTx(); assertThat( newTx, not( instanceOf( PlaceboTransaction.class ) ) ); db.createNode(); newTx.success(); newTx.finish(); } } ); thread.start(); thread.join(); // THEN the new node is picked up by the iterator assertThat( addToCollection( allNodes, new ArrayList<Node>() ).size(), is( 2 ) ); transaction.finish(); } @Test public void getAllRelationshipsIteratorShouldPickUpHigherIdsThanHighIdWhenStarted() throws Exception { // GIVEN Transaction tx = db.beginTx(); Relationship relationship1 = createRelationshipAssumingTxWith( "key", 1 ); Relationship relationship2 = createRelationshipAssumingTxWith( "key", 2 ); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); Iterator<Relationship> allRelationships = GlobalGraphOperations.at( db ).getAllRelationships().iterator(); Relationship relationship3 = createRelationshipAssumingTxWith( "key", 3 ); // THEN assertEquals( asList( relationship1, relationship2, relationship3 ), addToCollection( allRelationships, new ArrayList<Relationship>() ) ); tx.success(); tx.finish(); } private void delete( Relationship relationship ) { Transaction tx = db.beginTx(); relationship.delete(); tx.success(); tx.finish(); } private Node createNodeWith( String key, Object value ) { Transaction tx = db.beginTx(); Node node = db.createNode(); node.setProperty( key, value ); tx.success(); tx.finish(); return node; } private Relationship createRelationshipWith( String key, Object value ) { Transaction tx = db.beginTx(); Relationship relationship = createRelationshipAssumingTxWith( key, value ); tx.success(); tx.finish(); return relationship; } private Relationship createRelationshipAssumingTxWith( String key, Object value ) { Node a = db.createNode(); Node b = db.createNode(); Relationship relationship = a.createRelationshipTo( b, DynamicRelationshipType.withName( "FOO" ) ); relationship.setProperty( key, value ); return relationship; } private void delete( Node node ) { Transaction tx = db.beginTx(); node.delete(); tx.success(); tx.finish(); } private class NodeLoggingTracker implements PropertyTracker<Node> { @Override public void propertyAdded( Node primitive, String propertyName, Object propertyValue ) { } public String removed = ""; @Override public void propertyRemoved( Node primitive, String propertyName, Object propertyValue ) { removed = removed + primitive.getId() + ":" + propertyName; } @Override public void propertyChanged( Node primitive, String propertyName, Object oldValue, Object newValue ) { } } private class RelationshipLoggingTracker implements PropertyTracker<Relationship> { @Override public void propertyAdded( Relationship primitive, String propertyName, Object propertyValue ) { } public String removed = ""; @Override public void propertyRemoved( Relationship primitive, String propertyName, Object propertyValue ) { removed = removed + primitive.getId() + ":" + propertyName; } @Override public void propertyChanged( Relationship primitive, String propertyName, Object oldValue, Object newValue ) { } } private NodeManager getNodeManager() { return db.getDependencyResolver().resolveDependency( NodeManager.class ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_NodeManagerTest.java
922
{ @Override public boolean accept( Relationship relationship ) { return !txState.relationshipIsDeleted( relationship.getId() ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
923
{ @Override public boolean accept( Relationship relationship ) { return !createdRelationships.contains( relationship.getId() ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
924
{ private long highId = getHighestPossibleIdInUse( Relationship.class ); private long currentId; @Override protected Relationship fetchNextOrNull() { while ( true ) { // This outer loop is for checking if highId has changed since we started. while ( currentId <= highId ) { try { Relationship relationship = getRelationshipByIdOrNull( currentId ); if ( relationship != null ) { return relationship; } } finally { currentId++; } } long newHighId = getHighestPossibleIdInUse( Node.class ); if ( newHighId > highId ) { highId = newHighId; } else { break; } } return null; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
925
{ @Override protected Node underlyingObjectToObject( Long id ) { return getNodeById( id ); } } ) );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
926
{ @Override public boolean accept( Node node ) { return !txState.nodeIsDeleted( node.getId() ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
927
{ @Override public boolean accept( Node node ) { return !createdNodes.contains( node.getId() ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
928
{ private long highId = getHighestPossibleIdInUse( Node.class ); private long currentId; @Override protected Node fetchNextOrNull() { while ( true ) { // This outer loop is for checking if highId has changed since we started. while ( currentId <= highId ) { try { Node node = getNodeByIdOrNull( currentId ); if ( node != null ) { return node; } } finally { currentId++; } } long newHighId = getHighestPossibleIdInUse( Node.class ); if ( newHighId > highId ) { highId = newHighId; } else { break; } } return null; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
929
{ @Override public RelationshipImpl loadById( long id ) { RelationshipRecord data = persistenceManager.loadLightRelationship( id ); if ( data == null ) { return null; } int typeId = data.getType(); final long startNodeId = data.getFirstNode(); final long endNodeId = data.getSecondNode(); return new RelationshipImpl( id, startNodeId, endNodeId, typeId, false ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
930
{ @Override protected Relationship underlyingObjectToObject( Long id ) { return getRelationshipById( id ); } } ) );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_NodeManager.java
931
@Ignore( "Requires a lot of disk space" ) public class ProveFiveBillionIT { private static final String PATH = "target/var/5b"; private static final RelationshipType TYPE = DynamicRelationshipType.withName( "CHAIN" ); @Test public void proveIt() throws Exception { deleteFileOrDirectory( new File( PATH ) ); BatchInserter inserter = BatchInserters.inserter( PATH/*, stringMap( "neostore.nodestore.db.mapped_memory", "300M", "neostore.relationshipstore.db.mapped_memory", "800M", "neostore.propertystore.db.mapped_memory", "100M", "neostore.propertystore.db.strings.mapped_memory", "100M" ) */); // Create one giant chain of nodes n1->n2->n3 where each node will have // an int property and each rel a long string property. This will yield // 5b nodes/relationships, 10b property records and 5b dynamic records. // Start off by creating the first 4 billion (or so) entities with the // batch inserter just to speed things up a little long first = inserter.createNode(map()); int max = (int) pow( 2, 32 )-1000; Map<String, Object> nodeProperties = map( "number", 123 ); Map<String, Object> relationshipProperties = map( "string", "A long string, which is longer than shortstring boundaries" ); long i = 0; for ( ; i < max; i++ ) { long second = inserter.createNode( nodeProperties ); inserter.createRelationship( first, second, TYPE, relationshipProperties ); if ( i > 0 && i % 1000000 == 0 ) System.out.println( (i/1000000) + "M" ); first = second; } inserter.shutdown(); System.out.println( "Switch to embedded" ); // Then create the rest with embedded graph db. GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( PATH ); Node firstNode = db.getNodeById( first ); Transaction tx = db.beginTx(); for ( ; i < 5000000000L; i++ ) { Node secondNode = db.createNode(); firstNode.createRelationshipTo( secondNode, TYPE ); firstNode = secondNode; if ( i % 100000 == 0 ) { tx.success(); tx.finish(); System.out.println( (i/1000000) + "M" ); tx = db.beginTx(); } } // Here we have a huge db. Loop through it and count chain length. /* long count = 0; Node node = db.getReferenceNode(); while ( true ) { Relationship relationship = node.getSingleRelationship( TYPE, Direction.OUTGOING ); if ( relationship == null ) { break; } } System.out.println( count ); assertTrue( count > 4900000000L );*/ db.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_ProveFiveBillionIT.java
932
public class ReadOnlyDbException extends RuntimeException { public ReadOnlyDbException() { super( "This is a read only embedded Neo4j instance" ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_ReadOnlyDbException.java
933
public class ReadOnlyNodeManager extends NodeManager { public ReadOnlyNodeManager( StringLogger logger, GraphDatabaseService graphDb, AbstractTransactionManager transactionManager, PersistenceManager persistenceManager, EntityIdGenerator idGenerator, RelationshipTypeTokenHolder relationshipTypeTokenHolder, CacheProvider cacheType, PropertyKeyTokenHolder propertyKeyTokenHolder, LabelTokenHolder labelTokenHolder, NodeProxy.NodeLookup nodeLookup, RelationshipProxy.RelationshipLookups relationshipLookups, Cache<NodeImpl> nodeCache, Cache<RelationshipImpl> relCache, XaDataSourceManager xaDsm, ThreadToStatementContextBridge statementCtxProvider ) { super( logger, graphDb, transactionManager, persistenceManager, idGenerator, relationshipTypeTokenHolder, cacheType, propertyKeyTokenHolder, labelTokenHolder, nodeLookup, relationshipLookups, nodeCache, relCache, xaDsm, statementCtxProvider ); } @Override public Node createNode() { throw new ReadOnlyDbException(); } @Override public Relationship createRelationship( Node startNodeProxy, NodeImpl startNode, Node endNode, long typeId ) { throw new ReadOnlyDbException(); } @Override public ArrayMap<Integer, DefinedProperty> deleteNode( NodeImpl node, TransactionState tx ) { throw new ReadOnlyDbException(); } @Override public ArrayMap<Integer, DefinedProperty> deleteRelationship( RelationshipImpl rel, TransactionState tx ) { throw new ReadOnlyDbException(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_ReadOnlyNodeManager.java
934
public class RelationshipTypeTokenHolder extends TokenHolder<RelationshipTypeToken> { public RelationshipTypeTokenHolder( AbstractTransactionManager transactionManager, PersistenceManager persistenceManager, EntityIdGenerator idGenerator, TokenCreator tokenCreator ) { super( transactionManager, persistenceManager, idGenerator, tokenCreator ); } @Override protected RelationshipTypeToken newToken( String name, int id ) { return new RelationshipTypeToken( name, id ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipTypeTokenHolder.java
935
public class TestConcurrentModificationOfRelationshipChains { private static final int RelationshipGrabSize = 2; @Rule public ImpermanentDatabaseRule graphDb = new ImpermanentDatabaseRule() { @Override protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( GraphDatabaseSettings.relationship_grab_size, ""+RelationshipGrabSize ); } }; @Test public void relationshipChainPositionCachePoisoningFromSameThreadReReadNode() { GraphDatabaseAPI db = graphDb.getGraphDatabaseAPI(); Triplet<Iterable<Relationship>, Long, Relationship> relsCreated = setup( db ); Relationship firstFromSecondBatch = relsCreated.third(); deleteRelationshipInSameThread( db, firstFromSecondBatch ); Transaction transaction = db.beginTx(); for ( Relationship rel : db.getNodeById( relsCreated.second() ).getRelationships() ) { rel.getId(); } transaction.finish(); } @Test public void relationshipChainPositionCachePoisoningFromDifferentThreadReReadNode() throws InterruptedException { GraphDatabaseAPI db = graphDb.getGraphDatabaseAPI(); Triplet<Iterable<Relationship>, Long, Relationship> relsCreated = setup( db ); Relationship firstFromSecondBatch = relsCreated.third(); deleteRelationshipInDifferentThread( db, firstFromSecondBatch ); Transaction transaction = db.beginTx(); for ( Relationship rel : db.getNodeById( relsCreated.second() ).getRelationships() ) { rel.getId(); } transaction.finish(); } @Test public void relationshipChainPositionCachePoisoningFromSameThread() { GraphDatabaseAPI db = graphDb.getGraphDatabaseAPI(); Triplet<Iterable<Relationship>, Long, Relationship> relsCreated = setup( db ); Iterator<Relationship> rels = relsCreated.first().iterator(); Relationship firstFromSecondBatch = relsCreated.third(); deleteRelationshipInSameThread( db, firstFromSecondBatch ); while ( rels.hasNext() ) { rels.next(); } } @Test public void relationshipChainPositionCachePoisoningFromDifferentThreads() throws InterruptedException { GraphDatabaseAPI db = graphDb.getGraphDatabaseAPI(); Triplet<Iterable<Relationship>, Long, Relationship> relsCreated = setup( db ); Iterator<Relationship> rels = relsCreated.first().iterator(); Relationship firstFromSecondBatch = relsCreated.third(); deleteRelationshipInDifferentThread( db, firstFromSecondBatch ); while ( rels.hasNext() ) { rels.next(); } } private void deleteRelationshipInSameThread( GraphDatabaseAPI db, Relationship toDelete ) { Transaction tx = db.beginTx(); toDelete.delete(); tx.success(); tx.finish(); } private void deleteRelationshipInDifferentThread( final GraphDatabaseAPI db, final Relationship toDelete ) throws InterruptedException { Runnable deleter = new Runnable() { @Override public void run() { deleteRelationshipInSameThread( db, toDelete); } }; Thread t = new Thread( deleter ); t.start(); t.join(); } private Triplet<Iterable<Relationship>, Long, Relationship> setup( GraphDatabaseAPI db ) { Transaction tx = db.beginTx(); Node node1 = db.createNode(); Node node2 = db.createNode(); RelationshipType relType = DynamicRelationshipType.withName( "POISON" ); Relationship firstFromSecondBatch = node1.createRelationshipTo( node2, relType ); for ( int i = 0; i < RelationshipGrabSize; i++ ) { node1.createRelationshipTo( node2, relType ); } tx.success(); tx.finish(); db.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); Transaction transaction = db.beginTx(); Iterable<Relationship> relationships = node1.getRelationships(); transaction.finish(); return Triplet.of( relationships, node1.getId(), firstFromSecondBatch ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentModificationOfRelationshipChains.java
936
public class TestConcurrentIteratorModification { @Rule public EmbeddedDatabaseRule dbRule = new EmbeddedDatabaseRule(); @Test public void shouldNotThrowConcurrentModificationExceptionWhenUpdatingWhileIterating() { // given GraphDatabaseService graph = dbRule.getGraphDatabaseService(); GlobalGraphOperations glops = GlobalGraphOperations.at( graph ); Label label = DynamicLabel.label( "Bird" ); Node node1, node2, node3; try ( Transaction tx = graph.beginTx() ) { node1 = graph.createNode( label ); node2 = graph.createNode( label ); tx.success(); } // when Set<Node> result = new HashSet<>(); try ( Transaction tx = graph.beginTx() ) { node3 = graph.createNode( label ); ResourceIterator<Node> iterator = glops.getAllNodesWithLabel( label ).iterator(); node3.removeLabel( label ); graph.createNode( label ); while ( iterator.hasNext() ) { result.add( iterator.next() ); } tx.success(); } // then does not throw and retains view from iterator creation time assertEquals(asSet(node1, node2, node3), result); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestConcurrentIteratorModification.java
937
public class TestChangingOfLogFormat { @Test public void inabilityToStartFromOldFormatFromNonCleanShutdown() throws Exception { File storeDir = new File( "target/var/oldlog" ); GraphDatabaseService db = factory.newImpermanentDatabase( storeDir.getPath() ); File logBaseFileName = ((GraphDatabaseAPI)db).getDependencyResolver().resolveDependency( XaDataSourceManager .class ).getNeoStoreDataSource().getXaContainer().getLogicalLog().getBaseFileName(); Transaction tx = db.beginTx(); db.createNode(); tx.success(); tx.finish(); Pair<Pair<File, File>, Pair<File, File>> copy = copyLogicalLog( fs.get(), logBaseFileName ); decrementLogFormat( copy.other().other() ); db.shutdown(); renameCopiedLogicalLog( fs.get(), copy ); try { db = factory.newImpermanentDatabase( storeDir.getPath() ); fail( "Shouldn't be able to do recovery (and upgrade log format version) on non-clean shutdown" ); } catch ( Exception e ) { // Good } } private void decrementLogFormat( File file ) throws IOException { // Gotten from LogIoUtils class StoreChannel channel = fs.get().open( file, "rw" ); ByteBuffer buffer = ByteBuffer.wrap( new byte[8] ); channel.read( buffer ); buffer.flip(); long version = buffer.getLong(); long logFormatVersion = (version >>> 56); version = version & 0x00FFFFFFFFFFFFFFL; long oldVersion = version | ( (logFormatVersion-1) << 56 ); channel.position( 0 ); buffer.clear(); buffer.putLong( oldVersion ); buffer.flip(); channel.write( buffer ); channel.close(); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private TestGraphDatabaseFactory factory; @Before public void before() throws Exception { factory = new TestGraphDatabaseFactory().setFileSystem( fs.get() ); } @After public void after() throws Exception { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestChangingOfLogFormat.java
938
private class Measurement { private long time; private int count; public void add( long time ) { this.time += time; this.count++; } public double average() { return (double)time/count; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestBinarySearchPerformance.java
939
{ @Override public void run() { for ( int i = 0; i < times; i++ ) { doBinarySearch( array, 0 ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestBinarySearchPerformance.java
940
{ @Override public void run() { for ( int i = 0; i < times; i++ ) { doScan( array, i%array.length ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestBinarySearchPerformance.java
941
public class TestBinarySearchPerformance { @Ignore( "Not a unit test, enable to try out performance difference" ) @Test public void measurePerformance() throws Exception { for ( int i = 1; i < 100; i++ ) { System.out.println( "===" + i + "===" ); test( i ); } } private void test( int size ) { final DefinedProperty[] array = datas( size ); final int times = 10000000; measure( "scan", new Runnable() { @Override public void run() { for ( int i = 0; i < times; i++ ) { doScan( array, i%array.length ); } } } ); measure( "bs", new Runnable() { @Override public void run() { for ( int i = 0; i < times; i++ ) { doBinarySearch( array, 0 ); } } } ); } private DefinedProperty[] datas( int size ) { DefinedProperty[] result = new DefinedProperty[size]; for ( int i = 0; i < size; i++ ) { result[i] = Property.byteProperty( i, (byte) 0 ); } return result; } private DefinedProperty doScan( DefinedProperty[] array, long keyId ) { for ( DefinedProperty pd : array ) { if ( pd.propertyKeyId() == keyId ) { return pd; } } return null; } private DefinedProperty doBinarySearch( DefinedProperty[] array, int keyId ) { return array[Arrays.binarySearch( array, keyId, ArrayBasedPrimitive.PROPERTY_DATA_COMPARATOR_FOR_BINARY_SEARCH )]; } private void measure( String name, Runnable runnable ) { // Warmup runnable.run(); // Run System.out.print( name + "... " ); Measurement m = new Measurement(); for ( int i = 0; i < 3; i++ ) { long t = System.currentTimeMillis(); runnable.run(); m.add( (System.currentTimeMillis()-t) ); } System.out.println( name + ":" + m.average() + " (lower=better)" ); } private class Measurement { private long time; private int count; public void add( long time ) { this.time += time; this.count++; } public double average() { return (double)time/count; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_TestBinarySearchPerformance.java
942
public class SchemaLock { @Override public int hashCode() { return 40591; // a centered triangular prime } @Override public boolean equals( Object obj ) { return obj instanceof SchemaLock; } @Override public String toString() { return getClass().getSimpleName(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_SchemaLock.java
943
class RelationshipTypeToken extends Token implements RelationshipType { public RelationshipTypeToken( String name, int id ) { super( name, id ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipTypeToken.java
944
public class RelationshipImpl extends ArrayBasedPrimitive { /* * The id long is used to store the relationship id (which is at most 35 bits). * But also the high order bits for the start node (s) and end node (e) as well * as the relationship type. This allows for a more compressed memory * representation. * * 2 bytes type start/end high 5 bytes of id * [tttt,tttt][tttt,tttt][ssss,eeee][iiii,iiii][iiii,iiii][iiii,iiii][iiii,iiii][iiii,iiii] */ private final long idAndMore; private final int startNodeId; private final int endNodeId; RelationshipImpl( long id, long startNodeId, long endNodeId, int typeId, boolean newRel ) { super( newRel ); this.startNodeId = (int) startNodeId; this.endNodeId = (int) endNodeId; this.idAndMore = (((long)typeId) << 48) | ((startNodeId&0xF00000000L)<<12) | ((endNodeId&0xF00000000L)<<8) | id; } @Override public boolean equals( Object obj ) { return this == obj || ( obj instanceof RelationshipImpl && ( (RelationshipImpl) obj ).getId() == getId() ); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (idAndMore ^ (idAndMore >>> 32)); return result; } @Override public int sizeOfObjectInBytesIncludingOverhead() { return super.sizeOfObjectInBytesIncludingOverhead() + 8/*idAndMore*/ + 8/*startNodeId and endNodeId*/; } @Override protected Iterator<DefinedProperty> loadProperties( NodeManager nodeManager ) { return nodeManager.loadProperties( this, false ); } @Override public long getId() { return idAndMore&0xFFFFFFFFFFL; } long getStartNodeId() { return (startNodeId&0xFFFFFFFFL) | ((idAndMore&0xF00000000000L)>>12); } long getEndNodeId() { return (endNodeId&0xFFFFFFFFL) | ((idAndMore&0xF0000000000L)>>8); } int getTypeId() { return (int)((idAndMore&0xFFFF000000000000L)>>>48); } @Override public String toString() { return "RelationshipImpl #" + this.getId() + " of type " + getTypeId() + " between Node[" + getStartNodeId() + "] and Node[" + getEndNodeId() + "]"; } @Override public CowEntityElement getEntityElement( PrimitiveElement element, boolean create ) { return element.relationshipElement( getId(), create ); } @Override PropertyContainer asProxy( NodeManager nm ) { return nm.newRelationshipProxyById( getId() ); } @Override protected Property noProperty( int key ) { return Property.noRelationshipProperty( getId(), key ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipImpl.java
945
public class RelationshipProxy implements Relationship { public interface RelationshipLookups { Node newNodeProxy( long nodeId ); RelationshipImpl lookupRelationship(long relationshipId); GraphDatabaseService getGraphDatabaseService(); NodeManager getNodeManager(); } private final long relId; private final RelationshipLookups relationshipLookups; private final ThreadToStatementContextBridge statementContextProvider; RelationshipProxy( long relId, RelationshipLookups relationshipLookups, ThreadToStatementContextBridge statementContextProvider ) { this.relId = relId; this.relationshipLookups = relationshipLookups; this.statementContextProvider = statementContextProvider; } @Override public long getId() { return relId; } @Override public GraphDatabaseService getGraphDatabase() { return relationshipLookups.getGraphDatabaseService(); } @Override public void delete() { try ( Statement statement = statementContextProvider.instance() ) { statement.dataWriteOperations().relationshipDelete( getId() ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public Node[] getNodes() { assertInTransaction(); RelationshipImpl relationship = relationshipLookups.lookupRelationship( relId ); return new Node[]{ relationshipLookups.newNodeProxy( relationship.getStartNodeId() ), relationshipLookups.newNodeProxy( relationship.getEndNodeId() )}; } @Override public Node getOtherNode( Node node ) { assertInTransaction(); RelationshipImpl relationship = relationshipLookups.lookupRelationship( relId ); if ( relationship.getStartNodeId() == node.getId() ) { return relationshipLookups.newNodeProxy( relationship.getEndNodeId() ); } if ( relationship.getEndNodeId() == node.getId() ) { return relationshipLookups.newNodeProxy( relationship.getStartNodeId() ); } throw new NotFoundException( "Node[" + node.getId() + "] not connected to this relationship[" + getId() + "]" ); } @Override public Node getStartNode() { assertInTransaction(); return relationshipLookups.newNodeProxy( relationshipLookups.lookupRelationship( relId ).getStartNodeId() ); } @Override public Node getEndNode() { assertInTransaction(); return relationshipLookups.newNodeProxy( relationshipLookups.lookupRelationship( relId ).getEndNodeId() ); } @Override public RelationshipType getType() { assertInTransaction(); try { return relationshipLookups.getNodeManager().getRelationshipTypeById( relationshipLookups.lookupRelationship( relId ) .getTypeId() ); } catch ( TokenNotFoundException e ) { throw new NotFoundException( e ); } } @Override public Iterable<String> getPropertyKeys() { try ( Statement statement = statementContextProvider.instance() ) { List<String> keys = new ArrayList<>(); Iterator<DefinedProperty> properties = statement.readOperations().relationshipGetAllProperties( getId() ); while ( properties.hasNext() ) { keys.add( statement.readOperations().propertyKeyGetName( properties.next().propertyKeyId() ) ); } return keys; } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Relationship not found", e ); } catch ( PropertyKeyIdNotFoundKernelException e ) { throw new ThisShouldNotHappenError( "Jake", "Property key retrieved through kernel API should exist." ); } } @Override public Object getProperty( String key ) { if ( null == key ) { throw new IllegalArgumentException( "(null) property key is not allowed" ); } try ( Statement statement = statementContextProvider.instance() ) { try { int propertyId = statement.readOperations().propertyKeyGetForName( key ); if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY ) { throw new NotFoundException( String.format( "No such property, '%s'.", key ) ); } return statement.readOperations().relationshipGetProperty( relId, propertyId ).value(); } catch ( EntityNotFoundException | PropertyNotFoundException e ) { throw new NotFoundException( e.getUserMessage( new StatementTokenNameLookup( statement.readOperations() ) ), e ); } } } @Override public Object getProperty( String key, Object defaultValue ) { if ( null == key ) { throw new IllegalArgumentException( "(null) property key is not allowed" ); } try ( Statement statement = statementContextProvider.instance() ) { int propertyId = statement.readOperations().propertyKeyGetForName( key ); return statement.readOperations().relationshipGetProperty( relId, propertyId ).value( defaultValue ); } catch ( EntityNotFoundException e ) { throw new IllegalStateException( e ); } } @Override public boolean hasProperty( String key ) { if ( null == key ) { return false; } try ( Statement statement = statementContextProvider.instance() ) { int propertyId = statement.readOperations().propertyKeyGetForName( key ); return propertyId != KeyReadOperations.NO_SUCH_PROPERTY_KEY && statement.readOperations().relationshipGetProperty( relId, propertyId ).isDefined(); } catch ( EntityNotFoundException e ) { throw new IllegalStateException( e ); } } @Override public void setProperty( String key, Object value ) { boolean success = false; try ( Statement statement = statementContextProvider.instance() ) { int propertyKeyId = statement.tokenWriteOperations().propertyKeyGetOrCreateForName( key ); statement.dataWriteOperations().relationshipSetProperty( relId, Property.property( propertyKeyId, value ) ); success = true; } catch ( EntityNotFoundException e ) { throw new IllegalStateException( e ); } catch ( IllegalTokenNameException e ) { // TODO: Maybe throw more context-specific error than just IllegalArgument throw new IllegalArgumentException( e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } finally { if ( !success ) { relationshipLookups.getNodeManager().setRollbackOnly(); } } } @Override public Object removeProperty( String key ) { try ( Statement statement = statementContextProvider.instance() ) { int propertyId = statement.tokenWriteOperations().propertyKeyGetOrCreateForName( key ); return statement.dataWriteOperations().relationshipRemoveProperty( relId, propertyId ).value( null ); } catch ( EntityNotFoundException e ) { throw new IllegalStateException( e ); } catch ( IllegalTokenNameException e ) { // TODO: Maybe throw more context-specific error than just IllegalArgument throw new IllegalArgumentException( e ); } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( ReadOnlyDatabaseKernelException e ) { throw new ReadOnlyDbException(); } } @Override public boolean isType( RelationshipType type ) { assertInTransaction(); try { return relationshipLookups.getNodeManager().getRelationshipTypeById( relationshipLookups.lookupRelationship( relId ).getTypeId() ).name().equals( type.name() ); } catch ( TokenNotFoundException e ) { throw new NotFoundException( e ); } } public int compareTo( Object rel ) { Relationship r = (Relationship) rel; long ourId = this.getId(), theirId = r.getId(); if ( ourId < theirId ) { return -1; } else if ( ourId > theirId ) { return 1; } else { return 0; } } @Override public boolean equals( Object o ) { return o instanceof Relationship && this.getId() == ((Relationship) o).getId(); } @Override public int hashCode() { return (int) (( relId >>> 32 ) ^ relId ); } @Override public String toString() { return "Relationship[" + this.getId() + "]"; } private void assertInTransaction() { statementContextProvider.assertInTransaction(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipProxy.java
946
public class RelationshipLoaderTest { @Test public void shouldPopulateCacheIfLoadedRelIsNotInCache() throws Exception { // Given long fromDiskRelId = 12l; PersistenceManager persistenceManager = mock( PersistenceManager.class ); Cache relCache = mock( Cache.class ); NodeImpl node = new NodeImpl( 1337l ); node.setRelChainPosition( 0l ); Map<RelIdArray.DirectionWrapper, Iterable<RelationshipRecord>> relsFromDisk = new HashMap<>(); relsFromDisk.put( RelIdArray.DirectionWrapper.OUTGOING, asList( new RelationshipRecord( fromDiskRelId ) )); relsFromDisk.put( RelIdArray.DirectionWrapper.INCOMING, Collections.<RelationshipRecord>emptyList() ); when( persistenceManager.getMoreRelationships( 1337l, 0l ) ).thenReturn(Pair.of( relsFromDisk, -1l)); RelationshipLoader loader = new RelationshipLoader( persistenceManager, relCache ); // When Triplet<ArrayMap<Integer,RelIdArray>,List<RelationshipImpl>,Long> result = loader.getMoreRelationships( node ); // Then List<RelationshipImpl> relsThatWereNotInCache = result.second(); assertThat(relsThatWereNotInCache.size(), equalTo(1)); assertThat(relsThatWereNotInCache.get(0).getId(), equalTo(fromDiskRelId)); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_RelationshipLoaderTest.java
947
public class RelationshipLoader { private final PersistenceManager persistenceManager; private final Cache<RelationshipImpl> relationshipCache; public RelationshipLoader(PersistenceManager persistenceManager, Cache<RelationshipImpl> relationshipCache ) { this.persistenceManager = persistenceManager; this.relationshipCache = relationshipCache; } public Triplet<ArrayMap<Integer, RelIdArray>, List<RelationshipImpl>, Long> getMoreRelationships( NodeImpl node ) { long nodeId = node.getId(); long position = node.getRelChainPosition(); Pair<Map<RelIdArray.DirectionWrapper, Iterable<RelationshipRecord>>, Long> rels = persistenceManager.getMoreRelationships( nodeId, position ); ArrayMap<Integer, RelIdArray> newRelationshipMap = new ArrayMap<>(); List<RelationshipImpl> relsList = new ArrayList<>( 150 ); Iterable<RelationshipRecord> loops = rels.first().get( RelIdArray.DirectionWrapper.BOTH ); boolean hasLoops = loops != null; if ( hasLoops ) { populateLoadedRelationships( loops, relsList, RelIdArray.DirectionWrapper.BOTH, true, newRelationshipMap ); } populateLoadedRelationships( rels.first().get( RelIdArray.DirectionWrapper.OUTGOING ), relsList, RelIdArray.DirectionWrapper.OUTGOING, hasLoops, newRelationshipMap ); populateLoadedRelationships( rels.first().get( RelIdArray.DirectionWrapper.INCOMING ), relsList, RelIdArray.DirectionWrapper.INCOMING, hasLoops, newRelationshipMap ); return Triplet.of( newRelationshipMap, relsList, rels.other() ); } /** * @param loadedRelationshipsOutputParameter * This is the return value for this method. It's written like this * because several calls to this method are used to gradually build up * the map of RelIdArrays that are ultimately involved in the operation. */ private void populateLoadedRelationships( Iterable<RelationshipRecord> loadedRelationshipRecords, List<RelationshipImpl> relsList, RelIdArray.DirectionWrapper dir, boolean hasLoops, ArrayMap<Integer, RelIdArray> loadedRelationshipsOutputParameter ) { for ( RelationshipRecord rel : loadedRelationshipRecords ) { long relId = rel.getId(); RelationshipImpl relImpl = getOrCreateRelationshipFromCache( relsList, rel, relId ); getOrCreateRelationships( hasLoops, relImpl.getTypeId(), loadedRelationshipsOutputParameter ) .add( relId, dir ); } } private RelIdArray getOrCreateRelationships( boolean hasLoops, int typeId, ArrayMap<Integer, RelIdArray> loadedRelationships ) { RelIdArray relIdArray = loadedRelationships.get( typeId ); if ( relIdArray != null ) { return relIdArray; } RelIdArray loadedRelIdArray = hasLoops ? new RelIdArrayWithLoops( typeId ) : new RelIdArray( typeId ); loadedRelationships.put( typeId, loadedRelIdArray ); return loadedRelIdArray; } private RelationshipImpl getOrCreateRelationshipFromCache( List<RelationshipImpl> newlyCreatedRelationships, RelationshipRecord rel, long relId ) { RelationshipImpl relImpl = relationshipCache.get( relId ); if (relImpl != null) return relImpl; RelationshipImpl loadedRelImpl = new RelationshipImpl( relId, rel.getFirstNode(), rel.getSecondNode(), rel.getType(), false ); newlyCreatedRelationships.add( loadedRelImpl ); return loadedRelImpl; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipLoader.java
948
private static class ControlledRelIdIterator implements RelIdIterator { private final List<Long> ids; private int index; private final Queue<Boolean> controlledHasNextResults = new LinkedList<>(); ControlledRelIdIterator( Long... ids ) { this.ids = new ArrayList<>( Arrays.asList( ids ) ); } void add( long... ids ) { for ( long id : ids ) { this.ids.add( id ); } } void queueHasNextAnswers( boolean... answers ) { for ( boolean answer : answers ) { controlledHasNextResults.add( answer ); } } @Override public int getType() { return 0; } @Override public boolean hasNext() { Boolean controlledAnswer = controlledHasNextResults.poll(); if ( controlledAnswer != null ) { return controlledAnswer.booleanValue(); } return index < ids.size(); } @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return ids.get( index++ ); } @Override public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction ) { throw new UnsupportedOperationException(); } @Override public void doAnotherRound() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_RelationshipIteratorIssuesTest.java
949
{ @Override public RelationshipProxy answer( InvocationOnMock invocation ) throws Throwable { RelationshipProxy relationship = mock( RelationshipProxy.class ); when( relationship.getId() ).thenReturn( (Long) invocation.getArguments()[0] ); return relationship; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_RelationshipIteratorIssuesTest.java
950
public class RelationshipIteratorIssuesTest { @Test public void arrayIndexOutOfBoundsInRelTypeArrayWhenCreatingRelationshipsConcurrently() throws Exception { // GIVEN // -- a node manager capable of serving light-weight RelationshipProxy capable of answering getId() NodeManager nodeManager = mock( NodeManager.class ); when( nodeManager.newRelationshipProxyById( anyLong() ) ).thenAnswer( relationshipProxyWithId() ); // -- a node that says it cannot load any more relationships NodeImpl node = mock( NodeImpl.class ); when( node.getMoreRelationships( nodeManager ) ).thenReturn( LoadStatus.NOTHING ); // -- a type iterator that at this point contains one relationship (0) ControlledRelIdIterator typeIterator = new ControlledRelIdIterator( 0L ); RelationshipIterator iterator = new RelationshipIterator( new RelIdIterator[] { typeIterator }, node, OUTGOING, nodeManager, false, false ); // -- go forth one step in the iterator iterator.next(); // WHEN // -- one relationship has been returned, and we're in the middle of the next call to next() // typeIterator will get one more relationship in it. To mimic this we control the outcome of // RelIdIterator#hasNext() so that we get to the correct branch in the RelationshipIterator code typeIterator.queueHasNextAnswers( false, false, true ); long otherRelationship = 1, thirdRelationship = 2; typeIterator.add( otherRelationship, thirdRelationship ); // -- go one more step, getting us into the state where the type index in RelationshipIterator // was incremented by mistake. Although this particular call to next() succeeds iterator.next(); // -- call next() again, where the first thing happening is to get the RelIdIterator with the // now invalid type index, causing ArrayIndexOutOfBoundsException Relationship returnedThirdRelationship = iterator.next(); // THEN assertEquals( thirdRelationship, returnedThirdRelationship.getId() ); } private Answer<RelationshipProxy> relationshipProxyWithId() { return new Answer<RelationshipProxy>() { @Override public RelationshipProxy answer( InvocationOnMock invocation ) throws Throwable { RelationshipProxy relationship = mock( RelationshipProxy.class ); when( relationship.getId() ).thenReturn( (Long) invocation.getArguments()[0] ); return relationship; } }; } private static class ControlledRelIdIterator implements RelIdIterator { private final List<Long> ids; private int index; private final Queue<Boolean> controlledHasNextResults = new LinkedList<>(); ControlledRelIdIterator( Long... ids ) { this.ids = new ArrayList<>( Arrays.asList( ids ) ); } void add( long... ids ) { for ( long id : ids ) { this.ids.add( id ); } } void queueHasNextAnswers( boolean... answers ) { for ( boolean answer : answers ) { controlledHasNextResults.add( answer ); } } @Override public int getType() { return 0; } @Override public boolean hasNext() { Boolean controlledAnswer = controlledHasNextResults.poll(); if ( controlledAnswer != null ) { return controlledAnswer.booleanValue(); } return index < ids.size(); } @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return ids.get( index++ ); } @Override public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction ) { throw new UnsupportedOperationException(); } @Override public void doAnotherRound() { throw new UnsupportedOperationException(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_RelationshipIteratorIssuesTest.java
951
class RelationshipIterator extends PrefetchingIterator<Relationship> implements Iterable<Relationship> { private RelIdIterator[] rels; private int currentTypeIndex; private final NodeImpl fromNode; private final DirectionWrapper direction; private final NodeManager nodeManager; private boolean lastTimeILookedThereWasMoreToLoad; private final boolean allTypes; RelationshipIterator( RelIdIterator[] rels, NodeImpl fromNode, DirectionWrapper direction, NodeManager nodeManager, boolean hasMoreToLoad, boolean allTypes ) { initializeRels( rels ); this.lastTimeILookedThereWasMoreToLoad = hasMoreToLoad; this.fromNode = fromNode; this.direction = direction; this.nodeManager = nodeManager; this.allTypes = allTypes; } private void initializeRels( RelIdIterator[] rels ) { this.rels = rels; this.currentTypeIndex = 0; } @Override public Iterator<Relationship> iterator() { return this; } @Override protected Relationship fetchNextOrNull() { RelIdIterator currentTypeIterator = rels[currentTypeIndex]; do { if ( currentTypeIterator.hasNext() ) { // There are more relationships loaded of this relationship type, let's return it long nextId = currentTypeIterator.next(); try { return nodeManager.newRelationshipProxyById( nextId ); } catch ( NotFoundException e ) { // OK, deleted. Skip it and move on } } LoadStatus status; while ( !currentTypeIterator.hasNext() ) { // There aren't any more relationships loaded of this relationship type if ( currentTypeIndex+1 < rels.length ) { // There are other relationship types to try to get relationships from, go to the next type currentTypeIterator = rels[++currentTypeIndex]; } else if ( (status = fromNode.getMoreRelationships( nodeManager )).loaded() // This is here to guard for that someone else might have loaded // stuff in this relationship chain (and exhausted it) while I // iterated over my batch of relationships. It will only happen // for nodes which have more than <grab size> relationships and // isn't fully loaded when starting iterating. || lastTimeILookedThereWasMoreToLoad ) { // There aren't any more relationship types to try to get relationships from, // but it's likely there are more relationships to load for this node, // so try to go and load more relationships lastTimeILookedThereWasMoreToLoad = status.hasMoreToLoad(); Map<Integer,RelIdIterator> newRels = new HashMap<>(); for ( RelIdIterator itr : rels ) { int type = itr.getType(); RelIdArray newSrc = fromNode.getRelationshipIds( type ); if ( newSrc != null ) { itr = itr.updateSource( newSrc, direction ); itr.doAnotherRound(); } newRels.put( type, itr ); } // If we wanted relationships of any type check if there are // any new relationship types loaded for this node and if so // initiate iterators for them if ( allTypes ) { ArrayMap<Integer, Collection<Long>> skipMap = nodeManager.getTransactionState(). getCowRelationshipRemoveMap( fromNode ); for ( RelIdArray ids : fromNode.getRelationshipIds() ) { int type = ids.getType(); RelIdIterator itr = newRels.get( type ); if ( itr == null ) { Collection<Long> remove = skipMap != null ? skipMap.get( type ) : null; itr = remove == null ? ids.iterator( direction ) : RelIdArray.from( ids, null, remove ).iterator( direction ); newRels.put( type, itr ); } else { itr = itr.updateSource( ids, direction ); newRels.put( type, itr ); } } } initializeRels( newRels.values().toArray( new RelIdIterator[newRels.size()] ) ); currentTypeIterator = rels[currentTypeIndex]; } else { // There aren't any more relationship types to try to get relationships from // and there are no more relationships to load for this node break; } } } while ( currentTypeIterator.hasNext() ); // Denotes the end of the iterator return null; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_core_RelationshipIterator.java
952
@RunWith( Parameterized.class ) public class RelationshipImplTest { @Parameters public static Collection<Object[]> data() { Collection<Object[]> data = new ArrayList<Object[]>(); for ( int i = 1; i <= 16; i++ ) { data.add( new Object[] { (1 << i) - 1 } ); } return data; } private final int typeId; public RelationshipImplTest( int typeId ) { this.typeId = typeId; } @Test public void typeIdCanUse16Bits() { RelationshipImpl rel = new RelationshipImpl( 10, 10, 10, typeId, true ); assertEquals( typeId, rel.getTypeId() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_core_RelationshipImplTest.java
953
public class MonitorGc implements Lifecycle { public static class Configuration { public static final Setting<Long> gc_monitor_wait_time = setting( "gc_monitor_wait_time", DURATION, "100ms" ); public static final Setting<Long> gc_monitor_threshold = setting("gc_monitor_threshold", DURATION, "200ms" ); } private final Config config; private final StringLogger logger; private volatile MeasureDoNothing monitorGc; public MonitorGc( Config config, StringLogger logger ) { this.config = config; this.logger = logger; } @Override public void init() throws Throwable { } @Override public void start() throws Throwable { monitorGc = new MeasureDoNothing( "GC-Monitor", logger, config.get( Configuration.gc_monitor_wait_time ), config.get( Configuration.gc_monitor_threshold ) ); monitorGc.start(); } @Override public void stop() throws Throwable { monitorGc.stopMeasuring(); monitorGc = null; } @Override public void shutdown() throws Throwable { } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_MonitorGc.java
954
public class MeasureDoNothing extends Thread { private volatile boolean measure = true; private volatile long timeBlocked = 0; private final long TIME_TO_WAIT; private final long TIME_BEFORE_BLOCK; private final StringLogger logger; public MeasureDoNothing( String threadName, StringLogger logger ) { super( threadName ); if ( logger == null ) { throw new IllegalArgumentException( "Null message log" ); } this.logger = logger; this.TIME_TO_WAIT = 100; this.TIME_BEFORE_BLOCK = 200; setDaemon( true ); } public MeasureDoNothing( String threadName, StringLogger logger, long timeToWait, long acceptableWaitTime ) { super( threadName ); if ( logger == null ) { throw new IllegalArgumentException( "Null message log" ); } if ( timeToWait >= acceptableWaitTime ) { throw new IllegalArgumentException( "timeToWait[" + timeToWait + "] should be less than acceptableWaitTime[" + acceptableWaitTime + "]" ); } this.logger = logger; this.TIME_TO_WAIT = timeToWait; this.TIME_BEFORE_BLOCK = acceptableWaitTime; setDaemon( true ); } @Override public synchronized void run() { logger.info( "GC Monitor started. " ); while ( measure ) { long start = System.currentTimeMillis(); try { this.wait( TIME_TO_WAIT ); } catch ( InterruptedException e ) { Thread.interrupted(); } long time = System.currentTimeMillis() - start; if ( time > TIME_BEFORE_BLOCK ) { long blockTime = time - TIME_TO_WAIT; timeBlocked += blockTime; logger.warn( "GC Monitor: Application threads blocked for an additional " + blockTime + "ms [total block time: " + (timeBlocked / 1000.0f) + "s]" ); } } logger.info( "GC Monitor stopped. " ); } public synchronized void stopMeasuring() { measure = false; this.interrupt(); } public long getTimeInBlock() { return timeBlocked; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_MeasureDoNothing.java
955
{ @Override protected boolean removeEldestEntry( Map.Entry<K,E> eldest ) { // synchronization miss with old value on maxSize here is ok if ( super.size() > maxSize ) { super.remove( eldest.getKey() ); elementCleaned( eldest.getValue() ); } return false; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_cache_LruCache.java
956
{ @Override protected void flushUpdates( Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { for ( NodePropertyUpdate update : updates ) { switch ( update.getUpdateMode() ) { case CHANGED: case REMOVED: UniqueInMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); } } for ( NodePropertyUpdate update : updates ) { switch ( update.getUpdateMode() ) { case ADDED: case CHANGED: add( update.getNodeId(), update.getValueAfter(), IndexUpdateMode.ONLINE == mode ); } } } @Override public void remove( Iterable<Long> nodeIds ) { for ( long nodeId : nodeIds ) { UniqueInMemoryIndex.this.remove( nodeId ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_UniqueInMemoryIndex.java
957
public class InMemoryIndexProviderTest extends IndexProviderCompatibilityTestSuite { @Override protected SchemaIndexProvider createIndexProvider() { return new InMemoryIndexProvider(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndexProviderTest.java
958
@Service.Implementation(KernelExtensionFactory.class) public class InMemoryIndexProviderFactory extends KernelExtensionFactory<InMemoryIndexProviderFactory.Dependencies> { public static final String KEY = "in-memory"; public static final SchemaIndexProvider.Descriptor PROVIDER_DESCRIPTOR = new SchemaIndexProvider.Descriptor( KEY, "1.0" ); private final InMemoryIndexProvider singleProvider; public interface Dependencies { } public InMemoryIndexProviderFactory() { super( KEY ); this.singleProvider = null; } public InMemoryIndexProviderFactory( InMemoryIndexProvider singleProvider ) { super( KEY ); if ( singleProvider == null ) { throw new IllegalArgumentException( "Null provider" ); } this.singleProvider = singleProvider; } @Override public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable { return hasSingleProvider() ? singleProvider : new InMemoryIndexProvider(); } private boolean hasSingleProvider() { return singleProvider != null; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndexProviderFactory.java
959
public class InMemoryIndexProvider extends SchemaIndexProvider { private final Map<Long, InMemoryIndex> indexes; public InMemoryIndexProvider() { this( 0 ); } public InMemoryIndexProvider( int prio ) { this( prio, new CopyOnWriteHashMap<Long, InMemoryIndex>() ); } private InMemoryIndexProvider( int prio, Map<Long, InMemoryIndex> indexes ) { super( InMemoryIndexProviderFactory.PROVIDER_DESCRIPTOR, prio ); this.indexes = indexes; } @Override public InternalIndexState getInitialState( long indexId ) { InMemoryIndex index = indexes.get( indexId ); return index != null ? index.getState() : InternalIndexState.POPULATING; } @Override public IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config ) { InMemoryIndex index = config.isUnique() ? new UniqueInMemoryIndex( descriptor.getPropertyKeyId() ) : new InMemoryIndex(); indexes.put( indexId, index ); return index.getPopulator(); } @Override public IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config ) { InMemoryIndex index = indexes.get( indexId ); if ( index == null || index.getState() != InternalIndexState.ONLINE ) { throw new IllegalStateException( "Index " + indexId + " not online yet" ); } if ( config.isUnique() && !(index instanceof UniqueInMemoryIndex) ) { throw new IllegalStateException( String.format( "The index [%s] was not created as a unique index.", indexId ) ); } return index.getOnlineAccessor(); } @Override public String getPopulationFailure( long indexId ) throws IllegalStateException { String failure = indexes.get( indexId ).failure; if ( failure == null ) { throw new IllegalStateException(); } return failure; } public InMemoryIndexProvider snapshot() { Map<Long, InMemoryIndex> copy = new CopyOnWriteHashMap<>(); for ( Map.Entry<Long, InMemoryIndex> entry : indexes.entrySet() ) { copy.put( entry.getKey(), entry.getValue().snapshot() ); } return new InMemoryIndexProvider( priority, copy ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndexProvider.java
960
private static class ArrayKey { private final String arrayValue; private ArrayKey( String arrayValue ) { this.arrayValue = arrayValue; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ArrayKey other = (ArrayKey) o; return other.arrayValue.equals( this.arrayValue ); } @Override public int hashCode() { return arrayValue != null ? arrayValue.hashCode() : 0; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndexImplementation.java
961
abstract class InMemoryIndexImplementation implements IndexReader, BoundedIterable<Long> { abstract void clear(); @Override public final PrimitiveLongIterator lookup( Object value ) { return doLookup( encode( value ) ); } final void add( long nodeId, Object propertyValue, boolean applyIdempotently ) { doAdd( encode( propertyValue ), nodeId, applyIdempotently ); } final void remove( long nodeId, Object propertyValue ) { doRemove( encode( propertyValue ), nodeId ); } abstract PrimitiveLongIterator doLookup( Object propertyValue ); abstract void doAdd( Object propertyValue, long nodeId, boolean applyIdempotently ); abstract void doRemove( Object propertyValue, long nodeId ); abstract void remove( long nodeId ); abstract void iterateAll( IndexEntryIterator iterator ) throws Exception; @Override public void close() { } private static Object encode( Object propertyValue ) { if ( propertyValue instanceof Number ) { return ((Number) propertyValue).doubleValue(); } if ( propertyValue instanceof Character ) { return propertyValue.toString(); } if ( propertyValue.getClass().isArray() ) { return new ArrayKey( ArrayEncoder.encode( propertyValue ) ); } return propertyValue; } private static class ArrayKey { private final String arrayValue; private ArrayKey( String arrayValue ) { this.arrayValue = arrayValue; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ArrayKey other = (ArrayKey) o; return other.arrayValue.equals( this.arrayValue ); } @Override public int hashCode() { return arrayValue != null ? arrayValue.hashCode() : 0; } } abstract InMemoryIndexImplementation snapshot(); protected interface IndexEntryIterator { void visitEntry( Object key, Set<Long> nodeId ) throws Exception; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndexImplementation.java
962
private class Populator implements IndexPopulator { @Override public void create() { indexData.clear(); } @Override public void add( long nodeId, Object propertyValue ) throws IndexEntryConflictException, IOException { InMemoryIndex.this.add( nodeId, propertyValue, false ); } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws Exception { InMemoryIndex.this.verifyDeferredConstraints( accessor ); } @Override public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException { return InMemoryIndex.this.newUpdater( IndexUpdateMode.ONLINE, true ); } @Override public void drop() throws IOException { indexData.clear(); } @Override public void close( boolean populationCompletedSuccessfully ) throws IOException { if ( populationCompletedSuccessfully ) { state = InternalIndexState.ONLINE; } } @Override public void markAsFailed( String failureString ) { failure = failureString; state = InternalIndexState.FAILED; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndex.java
963
private class OnlineAccessor implements IndexAccessor { @Override public void force() throws IOException { } @Override public void drop() throws IOException { indexData.clear(); } @Override public IndexUpdater newUpdater( final IndexUpdateMode mode ) { return InMemoryIndex.this.newUpdater( mode, false ); } @Override public void close() throws IOException { } @Override public IndexReader newReader() { return indexData; } @Override public BoundedIterable<Long> newAllEntriesReader() { return indexData; } @Override public ResourceIterator<File> snapshotFiles() { return emptyIterator(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndex.java
964
private class InMemoryIndexUpdater implements IndexUpdater { private final boolean applyIdempotently; private InMemoryIndexUpdater( boolean applyIdempotently ) { this.applyIdempotently = applyIdempotently; } @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { switch ( update.getUpdateMode() ) { case ADDED: InMemoryIndex.this.add( update.getNodeId(), update.getValueAfter(), applyIdempotently ); break; case CHANGED: InMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); add( update.getNodeId(), update.getValueAfter(), applyIdempotently ); break; case REMOVED: InMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); break; default: throw new UnsupportedOperationException(); } } @Override public void close() throws IOException, IndexEntryConflictException { } @Override public void remove( Iterable<Long> nodeIds ) { for ( Long nodeId : nodeIds ) { indexData.remove( nodeId ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndex.java
965
class InMemoryIndex { protected final InMemoryIndexImplementation indexData; private InternalIndexState state = InternalIndexState.POPULATING; String failure; InMemoryIndex() { this( new HashBasedIndex() ); } InMemoryIndex( InMemoryIndexImplementation indexData ) { this.indexData = indexData; } @Override public String toString() { if ( failure != null ) { return String.format( "%s[failure=\"%s\"]%s", getClass().getSimpleName(), failure, indexData ); } else { return String.format( "%s%s", getClass().getSimpleName(), indexData ); } } final IndexPopulator getPopulator() { return new Populator(); } final IndexAccessor getOnlineAccessor() { return new OnlineAccessor(); } protected final PrimitiveLongIterator lookup( Object propertyValue ) { return indexData.lookup( propertyValue ); } protected void add( long nodeId, Object propertyValue, boolean applyIdempotently ) throws IndexEntryConflictException, IOException { indexData.add( nodeId, propertyValue, applyIdempotently ); } protected void remove( long nodeId, Object propertyValue ) { indexData.remove( nodeId, propertyValue ); } protected void remove( long nodeId ) { indexData.remove( nodeId ); } InternalIndexState getState() { return state; } private class Populator implements IndexPopulator { @Override public void create() { indexData.clear(); } @Override public void add( long nodeId, Object propertyValue ) throws IndexEntryConflictException, IOException { InMemoryIndex.this.add( nodeId, propertyValue, false ); } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws Exception { InMemoryIndex.this.verifyDeferredConstraints( accessor ); } @Override public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException { return InMemoryIndex.this.newUpdater( IndexUpdateMode.ONLINE, true ); } @Override public void drop() throws IOException { indexData.clear(); } @Override public void close( boolean populationCompletedSuccessfully ) throws IOException { if ( populationCompletedSuccessfully ) { state = InternalIndexState.ONLINE; } } @Override public void markAsFailed( String failureString ) { failure = failureString; state = InternalIndexState.FAILED; } } public void verifyDeferredConstraints( PropertyAccessor accessor ) throws Exception { } private class OnlineAccessor implements IndexAccessor { @Override public void force() throws IOException { } @Override public void drop() throws IOException { indexData.clear(); } @Override public IndexUpdater newUpdater( final IndexUpdateMode mode ) { return InMemoryIndex.this.newUpdater( mode, false ); } @Override public void close() throws IOException { } @Override public IndexReader newReader() { return indexData; } @Override public BoundedIterable<Long> newAllEntriesReader() { return indexData; } @Override public ResourceIterator<File> snapshotFiles() { return emptyIterator(); } } protected IndexUpdater newUpdater( IndexUpdateMode mode, boolean populating ) { return new InMemoryIndexUpdater( populating ); } private class InMemoryIndexUpdater implements IndexUpdater { private final boolean applyIdempotently; private InMemoryIndexUpdater( boolean applyIdempotently ) { this.applyIdempotently = applyIdempotently; } @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { switch ( update.getUpdateMode() ) { case ADDED: InMemoryIndex.this.add( update.getNodeId(), update.getValueAfter(), applyIdempotently ); break; case CHANGED: InMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); add( update.getNodeId(), update.getValueAfter(), applyIdempotently ); break; case REMOVED: InMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); break; default: throw new UnsupportedOperationException(); } } @Override public void close() throws IOException, IndexEntryConflictException { } @Override public void remove( Iterable<Long> nodeIds ) { for ( Long nodeId : nodeIds ) { indexData.remove( nodeId ); } } } InMemoryIndex snapshot() { InMemoryIndex snapshot = new InMemoryIndex( indexData.snapshot() ); snapshot.failure = this.failure; snapshot.state = this.state; return snapshot; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_InMemoryIndex.java
966
class HashBasedIndex extends InMemoryIndexImplementation { private final Map<Object, Set<Long>> data = new HashMap<>(); @Override public String toString() { return data.toString(); } @Override void clear() { data.clear(); } @Override PrimitiveLongIterator doLookup( Object propertyValue ) { Set<Long> nodes = data.get( propertyValue ); return nodes == null ? emptyPrimitiveLongIterator() : toPrimitiveLongIterator( nodes.iterator() ); } @Override void doAdd( Object propertyValue, long nodeId, boolean applyIdempotently ) { Set<Long> nodes = data.get( propertyValue ); if ( nodes == null ) { data.put( propertyValue, nodes = new HashSet<>() ); } // In this implementation we don't care about idempotency. nodes.add( nodeId ); } @Override void doRemove( Object propertyValue, long nodeId ) { Set<Long> nodes = data.get( propertyValue ); if ( nodes != null ) { nodes.remove( nodeId ); } } @Override void remove( long nodeId ) { for ( Set<Long> nodes : data.values() ) { nodes.remove( nodeId ); } } @Override void iterateAll( IndexEntryIterator iterator ) throws Exception { for ( Map.Entry<Object, Set<Long>> entry : data.entrySet() ) { iterator.visitEntry( entry.getKey(), entry.getValue() ); } } @Override public long maxCount() { return ids().size(); } @Override public Iterator<Long> iterator() { return ids().iterator(); } private Collection<Long> ids() { Set<Long> allIds = new HashSet<>(); for ( Set<Long> someIds : data.values() ) { allIds.addAll( someIds ); } return allIds; } @Override InMemoryIndexImplementation snapshot() { HashBasedIndex snapshot = new HashBasedIndex(); for ( Map.Entry<Object, Set<Long>> entry : data.entrySet() ) { snapshot.data.put( entry.getKey(), new HashSet<>( entry.getValue() ) ); } return snapshot; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_HashBasedIndex.java
967
REMOVED { @Override public boolean forLabel( long[] before, long[] after, long label ) { return binarySearch( before, label ) >= 0; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_UpdateMode.java
968
CHANGED { @Override public boolean forLabel( long[] before, long[] after, long label ) { return ADDED.forLabel( before, after, label ) && REMOVED.forLabel( before, after, label ); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_UpdateMode.java
969
ADDED { @Override public boolean forLabel( long[] before, long[] after, long label ) { return binarySearch( after, label ) >= 0; } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_UpdateMode.java
970
public abstract class UniquePropertyIndexUpdater implements IndexUpdater { private final Map<Object, DiffSets<Long>> referenceCount = new HashMap<>(); private final ArrayList<NodePropertyUpdate> updates = new ArrayList<>(); @Override public void process( NodePropertyUpdate update ) { // build uniqueness verification state switch ( update.getUpdateMode() ) { case ADDED: propertyValueDiffSet( update.getValueAfter() ).add( update.getNodeId() ); break; case CHANGED: propertyValueDiffSet( update.getValueBefore() ).remove( update.getNodeId() ); propertyValueDiffSet( update.getValueAfter() ).add( update.getNodeId() ); break; case REMOVED: propertyValueDiffSet( update.getValueBefore() ).remove( update.getNodeId() ); break; default: throw new UnsupportedOperationException(); } // do not flush update before close updates.add( update ); } @Override public void close() throws IOException, IndexEntryConflictException { // flush updates flushUpdates( updates ); } protected abstract void flushUpdates( Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException; private DiffSets<Long> propertyValueDiffSet( Object value ) { DiffSets<Long> diffSets = referenceCount.get( value ); if ( diffSets == null ) { referenceCount.put( value, diffSets = new DiffSets<>() ); } return diffSets; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_UniquePropertyIndexUpdater.java
971
public class TestSchemaIndexProviderDescriptor { public final static SchemaIndexProvider.Descriptor PROVIDER_DESCRIPTOR = new SchemaIndexProvider.Descriptor( "quantum-dex", "25.0" ); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_TestSchemaIndexProviderDescriptor.java
972
{ @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { try { delegate.process( update ); } catch ( IndexEntryConflictException conflict ) { failures.add( conflict ); } } @Override public void close() throws IOException, IndexEntryConflictException { try { delegate.close(); } catch ( IndexEntryConflictException conflict ) { failures.add( conflict ); } } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_TentativeConstraintIndexProxy.java
973
public class TentativeConstraintIndexProxy extends AbstractDelegatingIndexProxy { private final FlippableIndexProxy flipper; private final OnlineIndexProxy target; private final Collection<IndexEntryConflictException> failures = new CopyOnWriteArrayList<>(); public TentativeConstraintIndexProxy( FlippableIndexProxy flipper, OnlineIndexProxy target ) { this.flipper = flipper; this.target = target; } @Override public IndexUpdater newUpdater( IndexUpdateMode mode ) { switch( mode ) { case ONLINE: return new DelegatingIndexUpdater( target.accessor.newUpdater( mode ) ) { @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { try { delegate.process( update ); } catch ( IndexEntryConflictException conflict ) { failures.add( conflict ); } } @Override public void close() throws IOException, IndexEntryConflictException { try { delegate.close(); } catch ( IndexEntryConflictException conflict ) { failures.add( conflict ); } } }; case RECOVERY: return super.newUpdater( mode ); default: throw new ThisShouldNotHappenError( "Stefan", "Unsupported IndexUpdateMode" ); } } @Override public InternalIndexState getState() { return failures.isEmpty() ? InternalIndexState.POPULATING : InternalIndexState.FAILED; } @Override public String toString() { return getClass().getSimpleName() + "[target:" + target + "]"; } @Override public IndexReader newReader() throws IndexNotFoundKernelException { throw new IndexNotFoundKernelException( getDescriptor() + " is still populating" ); } @Override protected IndexProxy getDelegate() { return target; } @Override public void validate() throws ConstraintVerificationFailedKernelException { Iterator<IndexEntryConflictException> iterator = failures.iterator(); if ( iterator.hasNext() ) { Set<ConstraintVerificationFailedKernelException.Evidence> evidence = new HashSet<>(); do { evidence.add( new ConstraintVerificationFailedKernelException.Evidence( iterator.next() ) ); } while ( iterator.hasNext() ); IndexDescriptor descriptor = getDescriptor(); throw new ConstraintVerificationFailedKernelException( new UniquenessConstraint( descriptor.getLabelId(), descriptor.getPropertyKeyId() ), evidence ); } } public void activate() { if ( failures.isEmpty() ) { flipper.flipTo( target ); } else { throw new IllegalStateException( "Trying to activate failed index, should have checked the failures earlier..." ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_TentativeConstraintIndexProxy.java
974
public final class SwallowingIndexUpdater implements IndexUpdater { public static final IndexUpdater INSTANCE = new org.neo4j.kernel.impl.api.index.SwallowingIndexUpdater(); public SwallowingIndexUpdater() { } @Override public void process( NodePropertyUpdate update ) { // intentionally swallow this update } @Override public void close() throws IOException, IndexEntryConflictException { // nothing to close } @Override public void remove( Iterable<Long> nodeIds ) { // intentionally swallow these removals } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_SwallowingIndexUpdater.java
975
private static class SingleInstanceSchemaIndexProviderFactory extends KernelExtensionFactory<SingleInstanceSchemaIndexProviderFactoryDependencies> { private final SchemaIndexProvider provider; private SingleInstanceSchemaIndexProviderFactory( String key, SchemaIndexProvider provider ) { super( key ); this.provider = provider; } @Override public Lifecycle newKernelExtension( SingleInstanceSchemaIndexProviderFactoryDependencies dependencies ) throws Throwable { return provider; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_SchemaIndexTestHelper.java
976
class UniqueInMemoryIndex extends InMemoryIndex { private final int propertyKeyId; public UniqueInMemoryIndex( int propertyKeyId ) { this.propertyKeyId = propertyKeyId; } @Override protected IndexUpdater newUpdater( final IndexUpdateMode mode, final boolean populating ) { return new UniquePropertyIndexUpdater() { @Override protected void flushUpdates( Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { for ( NodePropertyUpdate update : updates ) { switch ( update.getUpdateMode() ) { case CHANGED: case REMOVED: UniqueInMemoryIndex.this.remove( update.getNodeId(), update.getValueBefore() ); } } for ( NodePropertyUpdate update : updates ) { switch ( update.getUpdateMode() ) { case ADDED: case CHANGED: add( update.getNodeId(), update.getValueAfter(), IndexUpdateMode.ONLINE == mode ); } } } @Override public void remove( Iterable<Long> nodeIds ) { for ( long nodeId : nodeIds ) { UniqueInMemoryIndex.this.remove( nodeId ); } } }; } @Override public void verifyDeferredConstraints( final PropertyAccessor accessor ) throws Exception { indexData.iterateAll( new InMemoryIndexImplementation.IndexEntryIterator() { @Override public void visitEntry( Object key, Set<Long> nodeIds ) throws Exception { List<Entry> entries = new ArrayList<>(); for (long nodeId : nodeIds ) { Property property = accessor.getProperty( nodeId, propertyKeyId ); Object value = property.value(); for ( Entry current : entries ) { if (current.property.valueEquals( value )) { throw new PreexistingIndexEntryConflictException( value, current.nodeId, nodeId ); } } entries.add( new Entry( nodeId, property) ); } } } ); } private static class Entry { long nodeId; Property property; private Entry( long nodeId, Property property ) { this.nodeId = nodeId; this.property = property; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_UniqueInMemoryIndex.java
977
{ @Override public void visitEntry( Object key, Set<Long> nodeIds ) throws Exception { List<Entry> entries = new ArrayList<>(); for (long nodeId : nodeIds ) { Property property = accessor.getProperty( nodeId, propertyKeyId ); Object value = property.value(); for ( Entry current : entries ) { if (current.property.valueEquals( value )) { throw new PreexistingIndexEntryConflictException( value, current.nodeId, nodeId ); } } entries.add( new Entry( nodeId, property) ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_UniqueInMemoryIndex.java
978
{ @Override public Void apply( GraphDatabaseService db ) { db.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create(); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_UniquenessConstraintValidationConcurrencyIT.java
979
private static class Entry { long nodeId; Property property; private Entry( long nodeId, Property property ) { this.nodeId = nodeId; this.property = property; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_UniqueInMemoryIndex.java
980
{ @Override public Future<Boolean> apply( GraphDatabaseService db ) { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); try { return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) ); } finally { assertThat( otherThread, isWaiting() ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_UniquenessConstraintValidationConcurrencyIT.java
981
{ @Override public Future<Boolean> apply( GraphDatabaseService db ) { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); return otherThread.execute( createNode( db, "Label1", "key1", "value2" ) ); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_UniquenessConstraintValidationConcurrencyIT.java
982
public class UniquenessConstraintValidationConcurrencyIT { public final @Rule DatabaseRule database = new ImpermanentDatabaseRule(); public final @Rule OtherThreadRule<Void> otherThread = new OtherThreadRule<>(); @Test public void shouldAllowConcurrentCreationOfNonConflictingData() throws Exception { // given database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) ); // when Future<Boolean> created = database.executeAndCommit( new Function<GraphDatabaseService, Future<Boolean>>() { @Override public Future<Boolean> apply( GraphDatabaseService db ) { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); return otherThread.execute( createNode( db, "Label1", "key1", "value2" ) ); } } ); // then assertTrue( "Node creation should succeed", created.get() ); } @Test public void shouldPreventConcurrentCreationOfConflictingData() throws Exception { // given database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) ); // when Future<Boolean> created = database.executeAndCommit( new Function<GraphDatabaseService, Future<Boolean>>() { @Override public Future<Boolean> apply( GraphDatabaseService db ) { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); try { return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) ); } finally { assertThat( otherThread, isWaiting() ); } } } ); // then assertFalse( "node creation should fail", created.get() ); } @Test public void shouldAllowOtherTransactionToCompleteIfFirstTransactionRollsBack() throws Exception { // given database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) ); // when Future<Boolean> created = database.executeAndRollback( new Function<GraphDatabaseService, Future<Boolean>>() { @Override public Future<Boolean> apply( GraphDatabaseService db ) { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); try { return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) ); } finally { assertThat( otherThread, isWaiting() ); } } } ); // then assertTrue( "Node creation should succeed", created.get() ); } private static Function<GraphDatabaseService, Void> createUniquenessConstraint( final String label, final String propertyKey ) { return new Function<GraphDatabaseService, Void>() { @Override public Void apply( GraphDatabaseService db ) { db.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create(); return null; } }; } public static OtherThreadExecutor.WorkerCommand<Void, Boolean> createNode( final GraphDatabaseService db, final String label, final String propertyKey, final Object propertyValue ) { return new OtherThreadExecutor.WorkerCommand<Void, Boolean>() { @Override public Boolean doWork( Void nothing ) throws Exception { Transaction tx = db.beginTx(); try { db.createNode( label( label ) ).setProperty( propertyKey, propertyValue ); tx.success(); return true; } catch ( ConstraintViolationException e ) { return false; } finally { tx.finish(); } } }; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_UniquenessConstraintValidationConcurrencyIT.java
983
public class UniquenessConstraintCreationIT extends KernelIntegrationTest { public @Rule TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( getClass() ); public @Rule OtherThreadRule<Void> otherThread = new OtherThreadRule<>(); @Test public void shouldAbortConstraintCreationWhenDuplicatesExist() throws Exception { // given long node1, node2; int foo, name; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // name is not unique for Foo in the existing data Node node = db.createNode( label( "Foo" ) ); node1 = node.getId(); node.setProperty( "name", "foo" ); node = db.createNode( label( "Foo" ) ); node2 = node.getId(); node.setProperty( "name", "foo" ); foo = statement.labelGetForName( "Foo" ); name = statement.propertyKeyGetForName( "name" ); commit(); } // when try { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( foo, name ); fail( "expected exception" ); } // then catch ( CreateConstraintFailureException ex ) { assertEquals( new UniquenessConstraint( foo, name ), ex.constraint() ); Throwable cause = ex.getCause(); assertThat( cause, instanceOf( ConstraintVerificationFailedKernelException.class ) ); assertEquals( asSet( new ConstraintVerificationFailedKernelException.Evidence( new PreexistingIndexEntryConflictException( "foo", node1, node2 ) ) ), ((ConstraintVerificationFailedKernelException) cause).evidence() ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_UniquenessConstraintCreationIT.java
984
public class TransactionIT extends KernelIntegrationTest { @Test public void shouldBeAbleToCommitThroughTransactionManager() throws Exception { // Given TransactionManager txManager = db.getDependencyResolver().resolveDependency( TransactionManager.class ); db.beginTx(); Node node = db.createNode(); node.setProperty( "name", "Bob" ); // When txManager.commit(); // Then write locks should have been released, so I can write to the node from a new tx try( Transaction tx = db.beginTx() ) { node.setProperty( "name", "Other" ); tx.success(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_TransactionIT.java
985
static class CreateConstraintButDoNotShutDown extends SubProcess<Process, String> implements Process { // Would use a CountDownLatch but fields of this class need to be serializable. private volatile boolean started = false; @Override protected void startup( String storeDir ) throws Throwable { GraphDatabaseService database = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); try ( Transaction transaction = database.beginTx() ) { database.schema().constraintFor( label("User") ).assertPropertyIsUnique( "uuid" ).create(); transaction.success(); } started = true; } @Override public void waitForSchemaTransactionCommitted() throws InterruptedException { while (!started) { Thread.sleep( 10 ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_SchemaRecoveryIT.java
986
public class SchemaRecoveryIT { @Test public void schemaTransactionsShouldSurviveRecovery() throws Exception { // given Process process = new CreateConstraintButDoNotShutDown().start( testDirectory.absolutePath() ); process.waitForSchemaTransactionCommitted(); SubProcess.kill( process ); // when GraphDatabaseService recoveredDatabase = new GraphDatabaseFactory().newEmbeddedDatabase( testDirectory.absolutePath() ); // then assertEquals(1, constraints( recoveredDatabase ).size()); assertEquals(1, indexes( recoveredDatabase ).size()); recoveredDatabase.shutdown(); } @Rule public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() ); private List<ConstraintDefinition> constraints( GraphDatabaseService database ) { try ( Transaction ignored = database.beginTx() ) { return asList( database.schema().getConstraints() ); } } private List<IndexDefinition> indexes( GraphDatabaseService database ) { try ( Transaction ignored = database.beginTx() ) { return asList( database.schema().getIndexes() ); } } public interface Process { void waitForSchemaTransactionCommitted() throws InterruptedException; } static class CreateConstraintButDoNotShutDown extends SubProcess<Process, String> implements Process { // Would use a CountDownLatch but fields of this class need to be serializable. private volatile boolean started = false; @Override protected void startup( String storeDir ) throws Throwable { GraphDatabaseService database = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); try ( Transaction transaction = database.beginTx() ) { database.schema().constraintFor( label("User") ).assertPropertyIsUnique( "uuid" ).create(); transaction.success(); } started = true; } @Override public void waitForSchemaTransactionCommitted() throws InterruptedException { while (!started) { Thread.sleep( 10 ); } } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_SchemaRecoveryIT.java
987
{ @Override protected boolean matchesSafely( Property item ) { return item.isDefined(); } @Override public void describeTo( Description description ) { description.appendText( "a defined Property" ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_PropertyIT.java
988
public class PropertyIT extends KernelIntegrationTest { @Test public void shouldSetNodePropertyValue() throws Exception { // GIVEN int propertyKeyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); // WHEN propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, "bozo" ) ); // THEN assertEquals( "bozo", statement.nodeGetProperty( nodeId, propertyKeyId ).value() ); // WHEN commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // THEN assertEquals( "bozo", statement.nodeGetProperty( nodeId, propertyKeyId ).value() ); } } @Test public void shouldRemoveSetNodeProperty() throws Exception { // GIVEN int propertyKeyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, "bozo" ) ); // WHEN statement.nodeRemoveProperty( nodeId, propertyKeyId ); // THEN assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); // WHEN commit(); } // THEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); } } @Test public void shouldRemoveSetNodePropertyAcrossTransactions() throws Exception { // GIVEN int propertyKeyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, "bozo" ) ); commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // WHEN Object previous = statement.nodeRemoveProperty( nodeId, propertyKeyId ).value(); // THEN assertEquals( "bozo", previous ); assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); // WHEN commit(); } // THEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); } } @Test public void shouldSilentlyNotRemoveMissingNodeProperty() throws Exception { // GIVEN int propertyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); propertyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // WHEN Property result = statement.nodeRemoveProperty( nodeId, propertyId ); // THEN assertFalse( "Return no property if removing missing", result.isDefined() ); } } @Test public void nodeHasPropertyIfSet() throws Exception { // GIVEN int propertyKeyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); // WHEN propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, "bozo" ) ); // THEN assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), isDefinedProperty() ); // WHEN commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // THEN assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), isDefinedProperty() ); } } @Test public void nodeHasNotPropertyIfUnset() throws Exception { int propertyKeyId; long nodeId; { // GIVEN DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); // WHEN propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); // THEN assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); // WHEN commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // THEN assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); } } @Test public void shouldRollbackSetNodePropertyValue() throws Exception { // GIVEN int propertyKeyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); commit(); } // WHEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, "bozo" ) ); rollback(); } // THEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); assertThat( statement.nodeGetProperty( nodeId, propertyKeyId ), not( isDefinedProperty() ) ); } } @Test public void shouldUpdateNodePropertyValue() throws Exception { // GIVEN int propertyId; long nodeId; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); propertyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyId, "bozo" ) ); commit(); } // WHEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); statement.nodeSetProperty( nodeId, Property.intProperty( propertyId, 42 ) ); commit(); } // THEN { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); assertEquals( 42, statement.nodeGetProperty( nodeId, propertyId ).value() ); } } @Test public void nodeHasStringPropertyIfSetAndLazyPropertyIfRead() throws Exception { // GIVEN int propertyKeyId; long nodeId; String value = "Bozo the Clown is a clown character very popular in the United States, peaking in the 1960s"; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); // WHEN propertyKeyId = statement.propertyKeyGetOrCreateForName( "clown" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, value ) ); // THEN assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).getClass().getSimpleName().equals( "StringProperty" ) ); // WHEN commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // THEN assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).getClass().getSimpleName().equals( "LazyStringProperty" ) ); assertEquals( value, statement.nodeGetProperty( nodeId, propertyKeyId ).value() ); assertEquals( value.hashCode(), statement.nodeGetProperty( nodeId, propertyKeyId ).hashCode() ); assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).valueEquals( value ) ); } } @Test public void nodeHasArrayPropertyIfSetAndLazyPropertyIfRead() throws Exception { // GIVEN int propertyKeyId; long nodeId; int[] value = new int[] {-1,0,1,2,3,4,5,6,7,8,9,10}; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Node node = db.createNode(); // WHEN propertyKeyId = statement.propertyKeyGetOrCreateForName( "numbers" ); nodeId = node.getId(); statement.nodeSetProperty( nodeId, Property.intArrayProperty( propertyKeyId, value ) ); // THEN assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).getClass().getSimpleName().equals( "IntArrayProperty" ) ); // WHEN commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); // THEN assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).getClass().getSimpleName().equals( "LazyArrayProperty" ) ); assertArrayEquals( value, (int[]) statement.nodeGetProperty( nodeId, propertyKeyId ).value() ); assertEquals( Arrays.hashCode( value ), statement.nodeGetProperty( nodeId, propertyKeyId ).hashCode() ); assertTrue( statement.nodeGetProperty( nodeId, propertyKeyId ).valueEquals( value ) ); } } @Test public void shouldListAllPropertyKeys() throws Exception { // given long prop1; long prop2; { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); prop1 = statement.propertyKeyGetOrCreateForName( "prop1" ); prop2 = statement.propertyKeyGetOrCreateForName( "prop2" ); // when Iterator<Token> propIdsBeforeCommit = statement.propertyKeyGetAllTokens(); // then assertThat( asCollection( propIdsBeforeCommit ), hasItems( new Token( "prop1", (int) prop1 ), new Token( "prop2", (int) prop2 )) ); // when commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Iterator<Token> propIdsAfterCommit = statement.propertyKeyGetAllTokens(); // then assertThat(asCollection( propIdsAfterCommit ) , hasItems( new Token( "prop1", (int) prop1 ), new Token( "prop2", (int) prop2 ) )); } } private static Matcher<Property> isDefinedProperty() { return new TypeSafeMatcher<Property>() { @Override protected boolean matchesSafely( Property item ) { return item.isDefined(); } @Override public void describeTo( Description description ) { description.appendText( "a defined Property" ); } }; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_PropertyIT.java
989
{ @Override public void run() { latch.awaitStart(); try ( Transaction tx = db.beginTx() ) { try ( Statement statement = statementContextProvider.instance() ) { statement.readOperations().nodeGetUniqueFromIndexLookup( index, value ); } tx.success(); } catch ( IndexNotFoundKernelException | IndexBrokenKernelException e ) { throw new RuntimeException( e ); } finally { latch.finish(); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_NodeGetUniqueFromIndexLookupIT.java
990
public class NodeGetUniqueFromIndexLookupIT extends KernelIntegrationTest { private int labelId, propertyKeyId; @Before public void createKeys() throws Exception { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); this.labelId = statement.labelGetOrCreateForName( "Person" ); this.propertyKeyId = statement.propertyKeyGetOrCreateForName( "foo" ); commit(); } // nodeGetUniqueWithLabelAndProperty(statement, :Person, foo=val) // // Given we have a unique constraint on :Person(foo) // (If not, throw) // // If there is a node n with n:Person and n.foo == val, return it // If there is no such node, return ? // // Ensure that if that method is called again with the same argument from some other transaction, // that transaction blocks until this transaction has finished // // [X] must return node from the unique index with the given property // [X] must return NO_SUCH_NODE if it is not in the index for the given property // // must block other transactions that try to call it with the same arguments @Test public void shouldFindMatchingNode() throws Exception { // given IndexDescriptor index = createUniquenessConstraint(); String value = "value"; long nodeId = createNodeWithValue( value ); // when looking for it DataWriteOperations statement = dataWriteOperationsInNewTransaction(); long foundId = statement.nodeGetUniqueFromIndexLookup( index, value ); commit(); // then assertTrue( "Created node was not found", nodeId == foundId ); } @Test public void shouldNotFindNonMatchingNode() throws Exception { // given IndexDescriptor index = createUniquenessConstraint(); String value = "value"; createNodeWithValue( "other_" + value ); // when looking for it DataWriteOperations statement = dataWriteOperationsInNewTransaction(); long foundId = statement.nodeGetUniqueFromIndexLookup( index, value ); commit(); // then assertTrue( "Non-matching created node was found", isNoSuchNode( foundId ) ); } @Test(timeout = 1000) public void shouldBlockUniqueNodeLookupFromCompetingTransaction() throws Exception { // This is the interleaving that we are trying to verify works correctly: // ---------------------------------------------------------------------- // Thread1 (main) : Thread2 // create unique node : // lookup(node) : // open start latch -----> // | : lookup(node) // wait for T2 to block : | // : *block* // commit ---------------> *unblock* // wait for T2 end latch : | // : finish failed transaction // : open end latch // *unblock* <-------------‘ // assert that we complete before timeout final DoubleLatch latch = new DoubleLatch(); DependencyResolver resolver = db.getDependencyResolver(); LockManager manager = resolver.resolveDependency( LockManager.class ); final IndexDescriptor index = createUniquenessConstraint(); final String value = "value"; DataWriteOperations dataStatement = dataWriteOperationsInNewTransaction(); long nodeId = dataStatement.nodeCreate(); dataStatement.nodeAddLabel( nodeId, labelId ); // This adds the node to the unique index and should take an index write lock dataStatement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, value ) ); Runnable runnableForThread2 = new Runnable() { @Override public void run() { latch.awaitStart(); try ( Transaction tx = db.beginTx() ) { try ( Statement statement = statementContextProvider.instance() ) { statement.readOperations().nodeGetUniqueFromIndexLookup( index, value ); } tx.success(); } catch ( IndexNotFoundKernelException | IndexBrokenKernelException e ) { throw new RuntimeException( e ); } finally { latch.finish(); } } }; Thread thread2 = new Thread( runnableForThread2, "Transaction Thread 2" ); thread2.start(); latch.start(); spinUntilBlocking: for (; ; ) { for ( LockInfo info : manager.getAllLocks() ) { for ( WaitingThread waiter : info.getWaitingThreads() ) { if ( waiter.getThreadId() == thread2.getId() ) { assertThat( info.getReadCount(), equalTo( 0 ) ); assertThat( info.getWriteCount(), equalTo( 1 ) ); assertThat( info.getResourceType(), equalTo( ResourceType.OTHER ) ); assertThat( info.getResourceId(), equalTo( "IndexEntryLock{labelId=0, propertyKeyId=0, propertyValue=value}" ) ); break spinUntilBlocking; } Thread.yield(); } } } commit(); latch.awaitFinish(); } private boolean isNoSuchNode( long foundId ) { return StatementConstants.NO_SUCH_NODE == foundId; } private long createNodeWithValue( String value ) throws KernelException { DataWriteOperations dataStatement = dataWriteOperationsInNewTransaction(); long nodeId = dataStatement.nodeCreate(); dataStatement.nodeAddLabel( nodeId, labelId ); dataStatement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, value ) ); commit(); return nodeId; } private IndexDescriptor createUniquenessConstraint() throws Exception { SchemaWriteOperations schemaStatement = schemaWriteOperationsInNewTransaction(); schemaStatement.uniquenessConstraintCreate( labelId, propertyKeyId ); IndexDescriptor result = schemaStatement.uniqueIndexGetForLabelAndPropertyKey( labelId, propertyKeyId ); commit(); return result; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_NodeGetUniqueFromIndexLookupIT.java
991
public class LabelIT extends KernelIntegrationTest { @Test public void shouldListAllLabels() throws Exception { // given int label1Id; int label2Id; { TokenWriteOperations statement = tokenWriteOperationsInNewTransaction(); label1Id = statement.labelGetOrCreateForName( "label1" ); label2Id = statement.labelGetOrCreateForName( "label2" ); // when Iterator<Token> labelIdsBeforeCommit = statement.labelsGetAllTokens(); // then assertThat( asCollection( labelIdsBeforeCommit ), hasItems( new Token( "label1", label1Id ), new Token( "label2", label2Id )) ); // when commit(); } { DataWriteOperations statement = dataWriteOperationsInNewTransaction(); Iterator<Token> labelIdsAfterCommit = statement.labelsGetAllTokens(); // then assertThat(asCollection( labelIdsAfterCommit ) , hasItems( new Token( "label1", label1Id ), new Token( "label2", label2Id ) )); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_LabelIT.java
992
public abstract class KernelIntegrationTest { @SuppressWarnings("deprecation") protected GraphDatabaseAPI db; protected ThreadToStatementContextBridge statementContextProvider; private Transaction beansTx; private Statement statement; private EphemeralFileSystemAbstraction fs; protected TokenWriteOperations tokenWriteOperationsInNewTransaction() throws KernelException { beansTx = db.beginTx(); statement = statementContextProvider.instance(); return statement.tokenWriteOperations(); } protected DataWriteOperations dataWriteOperationsInNewTransaction() throws KernelException { beansTx = db.beginTx(); statement = statementContextProvider.instance(); return statement.dataWriteOperations(); } protected SchemaWriteOperations schemaWriteOperationsInNewTransaction() throws KernelException { beansTx = db.beginTx(); statement = statementContextProvider.instance(); return statement.schemaWriteOperations(); } protected ReadOperations readOperationsInNewTransaction() { beansTx = db.beginTx(); statement = statementContextProvider.instance(); return statement.readOperations(); } protected void commit() { statement.close(); statement = null; beansTx.success(); beansTx.finish(); } protected void rollback() { statement.close(); statement = null; beansTx.failure(); beansTx.finish(); } @Before public void setup() { fs = new EphemeralFileSystemAbstraction(); startDb(); } @After public void cleanup() throws Exception { stopDb(); fs.shutdown(); } protected void startDb() { TestGraphDatabaseBuilder graphDatabaseFactory = (TestGraphDatabaseBuilder) new TestGraphDatabaseFactory().setFileSystem(fs).newImpermanentDatabaseBuilder(); //noinspection deprecation db = (GraphDatabaseAPI) graphDatabaseFactory.setConfig(GraphDatabaseSettings.cache_type,"none").newGraphDatabase(); statementContextProvider = db.getDependencyResolver().resolveDependency( ThreadToStatementContextBridge.class ); } protected void stopDb() { if ( beansTx != null ) { beansTx.finish(); } db.shutdown(); } protected void restartDb() { stopDb(); startDb(); } protected NeoStore neoStore() { return ((NeoStoreXaDataSource)db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME )).getNeoStore(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_KernelIntegrationTest.java
993
{ @Override public Object apply( String s ) { result.set( false ); return null; } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_KernelIT.java
994
{ @Override public String apply( String s ) { return maybeSetThisState; } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_KernelIT.java
995
public class KernelIT extends KernelIntegrationTest { // TODO: Split this into area-specific tests, see PropertyIT. /** * While we transition ownership from the Beans API to the Kernel API for core database * interactions, there will be a bit of a mess. Our first goal is an architecture like this: * <p/> * Users * / \ * Beans API Cypher * \ / * Kernel API * | * Kernel Implementation * <p/> * But our current intermediate architecture looks like this: * <p/> * Users * / \ * Beans API <--- Cypher * | \ / * | Kernel API * | | * Kernel Implementation * <p/> * Meaning Kernel API and Beans API both manipulate the underlying kernel, causing lots of corner cases. Most * notably, those corner cases are related to Transactions, and the interplay between three transaction APIs: * - The Beans API * - The JTA Transaction Manager API * - The Kernel TransactionContext API * <p/> * In the long term, the goal is for JTA compliant stuff to live outside of the kernel, as an addon. The Kernel * API will rule supreme over the land of transactions. We are a long way away from there, however, so as a first * intermediary step, the JTA transaction manager rules supreme, and the Kernel API piggybacks on it. * <p/> * This test shows us how to use both the Kernel API and the Beans API together in the same transaction, * during the transition phase. */ @Test public void mixingBeansApiWithKernelAPI() throws Exception { // 1: Start your transactions through the Beans API Transaction beansAPITx = db.beginTx(); // 2: Get a hold of a KernelAPI statement context for the *current* transaction this way: Statement statement = statementContextProvider.instance(); // 3: Now you can interact through both the statement context and the kernel API to manipulate the // same transaction. Node node = db.createNode(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "labello" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); // 4: Close the StatementContext statement.close(); // 5: Commit through the beans API beansAPITx.success(); beansAPITx.finish(); // NOTE: Transactions are still thread-bound right now, because we use JTA to "own" transactions, // meaning if you use // both the Kernel API to create transactions while a Beans API transaction is running in the same // thread, the results are undefined. // When the Kernel API implementation is done, the Kernel API transaction implementation is not meant // to be bound to threads. } @Test public void mixingBeansApiWithKernelAPIForNestedTransaction() throws Exception { // GIVEN Transaction outerTx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN Node node = db.createNode(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "labello" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); statement.close(); outerTx.finish(); } @Test public void changesInTransactionContextShouldBeRolledBackWhenTxIsRolledBack() throws Exception { // GIVEN Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN Node node = db.createNode(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "labello" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); statement.close(); tx.finish(); // THEN tx = db.beginTx(); statement = statementContextProvider.instance(); try { statement.readOperations().nodeHasLabel( node.getId(), labelId ); fail( "should have thrown exception" ); } catch ( EntityNotFoundException e ) { // Yay! } tx.finish(); } @Test public void shouldNotBeAbleToCommitIfFailedTransactionContext() throws Exception { Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN Node node = db.createNode(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "labello" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); statement.close(); tx.failure(); tx.success(); tx.finish(); // THEN tx = db.beginTx(); statement = statementContextProvider.instance(); try { statement.readOperations().nodeHasLabel( node.getId(), labelId ); fail( "should have thrown exception" ); } catch ( EntityNotFoundException e ) { // Yay! } tx.finish(); } @Test public void transactionStateShouldRemovePreviouslyAddedLabel() throws Exception { Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN Node node = db.createNode(); int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName( "labello1" ); int labelId2 = statement.dataWriteOperations().labelGetOrCreateForName( "labello2" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId1 ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId2 ); statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId2 ); statement.close(); tx.success(); tx.finish(); // THEN tx = db.beginTx(); statement = statementContextProvider.instance(); assertEquals( asSet( labelId1 ), asSet( statement.readOperations().nodeGetLabels( node.getId() ) ) ); tx.finish(); } @Test public void transactionStateShouldReflectRemovingAddedLabelImmediately() throws Exception { Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN Node node = db.createNode(); int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName( "labello1" ); int labelId2 = statement.dataWriteOperations().labelGetOrCreateForName( "labello2" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId1 ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId2 ); statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId2 ); // THEN assertFalse( statement.readOperations().nodeHasLabel( node.getId(), labelId2 ) ); assertEquals( asSet( labelId1 ), asSet( statement.readOperations().nodeGetLabels( node.getId() ) ) ); statement.close(); tx.success(); tx.finish(); } @Test public void transactionStateShouldReflectRemovingLabelImmediately() throws Exception { // GIVEN Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); Node node = db.createNode(); int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName( "labello1" ); int labelId2 = statement.dataWriteOperations().labelGetOrCreateForName( "labello2" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId1 ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId2 ); statement.close(); tx.success(); tx.finish(); tx = db.beginTx(); statement = statementContextProvider.instance(); // WHEN statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId2 ); // THEN PrimitiveIntIterator labelsIterator = statement.readOperations().nodeGetLabels( node.getId() ); Set<Integer> labels = asSet( labelsIterator ); assertFalse( statement.readOperations().nodeHasLabel( node.getId(), labelId2 ) ); assertEquals( asSet( labelId1 ), labels ); statement.close(); tx.success(); tx.finish(); } @Test public void labelShouldBeRemovedAfterCommit() throws Exception { // GIVEN Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); Node node = db.createNode(); int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName( "labello1" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId1 ); statement.close(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); statement = statementContextProvider.instance(); statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId1 ); statement.close(); tx.success(); tx.finish(); // THEN tx = db.beginTx(); statement = statementContextProvider.instance(); PrimitiveIntIterator labels = statement.readOperations().nodeGetLabels( node.getId() ); statement.close(); tx.success(); tx.finish(); assertThat( asSet( labels ), equalTo( Collections.<Integer>emptySet() ) ); } @Test public void addingNewLabelToNodeShouldRespondTrue() throws Exception { // GIVEN Transaction tx = db.beginTx(); Node node = db.createNode(); Statement statement = statementContextProvider.instance(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "mylabel" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); statement.close(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); statement = statementContextProvider.instance(); boolean added = statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); // THEN assertFalse( "Shouldn't have been added now", added ); tx.finish(); } @Test public void addingExistingLabelToNodeShouldRespondFalse() throws Exception { // GIVEN Transaction tx = db.beginTx(); Node node = db.createNode(); Statement statement = statementContextProvider.instance(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "mylabel" ); statement.close(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); statement = statementContextProvider.instance(); boolean added = statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); // THEN assertTrue( "Should have been added now", added ); tx.finish(); } @Test public void removingExistingLabelFromNodeShouldRespondTrue() throws Exception { // GIVEN Transaction tx = db.beginTx(); Node node = db.createNode(); Statement statement = statementContextProvider.instance(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "mylabel" ); statement.dataWriteOperations().nodeAddLabel( node.getId(), labelId ); statement.close(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); statement = statementContextProvider.instance(); boolean removed = statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId ); // THEN assertTrue( "Should have been removed now", removed ); tx.finish(); } @Test public void removingNonExistentLabelFromNodeShouldRespondFalse() throws Exception { // GIVEN Transaction tx = db.beginTx(); Node node = db.createNode(); Statement statement = statementContextProvider.instance(); int labelId = statement.dataWriteOperations().labelGetOrCreateForName( "mylabel" ); statement.close(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); statement = statementContextProvider.instance(); boolean removed = statement.dataWriteOperations().nodeRemoveLabel( node.getId(), labelId ); // THEN assertFalse( "Shouldn't have been removed now", removed ); tx.finish(); } @Test public void deletingNodeWithLabelsShouldHaveThoseLabelRemovalsReflectedInTransaction() throws Exception { // GIVEN Transaction tx = db.beginTx(); Label label = label( "labello" ); Node node = db.createNode( label ); tx.success(); tx.finish(); tx = db.beginTx(); Statement statement = statementContextProvider.instance(); // WHEN statement.dataWriteOperations().nodeDelete( node.getId() ); // Then int labelId = statement.readOperations().labelGetForName( label.name() ); Set<Integer> labels = asSet( statement.readOperations().nodeGetLabels( node.getId() ) ); boolean labelIsSet = statement.readOperations().nodeHasLabel( node.getId(), labelId ); Set<Long> nodes = asSet( statement.readOperations().nodesGetForLabel( labelId ) ); statement.close(); tx.success(); tx.finish(); assertEquals( emptySetOf( Long.class ), nodes ); assertEquals( emptySetOf( Integer.class ), labels ); assertFalse( "Label should not be set on node here", labelIsSet ); } @Test public void deletingNodeWithLabelsShouldHaveRemovalReflectedInLabelScans() throws Exception { // GIVEN Transaction tx = db.beginTx(); Label label = label( "labello" ); Node node = db.createNode( label ); tx.success(); tx.finish(); // AND GIVEN I DELETE IT tx = db.beginTx(); node.delete(); tx.success(); tx.finish(); // WHEN tx = db.beginTx(); Statement statement = statementContextProvider.instance(); int labelId = statement.readOperations().labelGetForName( label.name() ); PrimitiveLongIterator nodes = statement.readOperations().nodesGetForLabel( labelId ); Set<Long> nodeSet = asSet( nodes ); tx.success(); tx.finish(); // THEN assertThat( nodeSet, equalTo( Collections.<Long>emptySet() ) ); } @Test public void schemaStateShouldBeEvictedOnIndexComingOnline() throws Exception { // GIVEN schemaWriteOperationsInNewTransaction(); getOrCreateSchemaState( "my key", "my state" ); commit(); // WHEN createIndex( schemaWriteOperationsInNewTransaction() ); commit(); schemaWriteOperationsInNewTransaction(); db.schema().awaitIndexOnline( db.schema().getIndexes().iterator().next(), 20, SECONDS ); commit(); // THEN assertFalse( schemaStateContains( "my key" ) ); } @Test public void schemaStateShouldBeEvictedOnIndexDropped() throws Exception { // GIVEN IndexDescriptor idx = createIndex( schemaWriteOperationsInNewTransaction() ); commit(); schemaWriteOperationsInNewTransaction(); db.schema().awaitIndexOnline( db.schema().getIndexes().iterator().next(), 20, SECONDS ); getOrCreateSchemaState( "my key", "some state" ); commit(); // WHEN schemaWriteOperationsInNewTransaction().indexDrop( idx ); commit(); // THEN assertFalse( schemaStateContains("my key") ); } private IndexDescriptor createIndex( SchemaWriteOperations schemaWriteOperations ) throws SchemaKernelException { return schemaWriteOperations.indexCreate( schemaWriteOperations.labelGetOrCreateForName( "hello" ), schemaWriteOperations.propertyKeyGetOrCreateForName( "hepp" ) ); } private String getOrCreateSchemaState( String key, final String maybeSetThisState ) { Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); String state = statement.readOperations().schemaStateGetOrCreate( key, new Function<String, String>() { @Override public String apply( String s ) { return maybeSetThisState; } } ); tx.success(); tx.finish(); return state; } private boolean schemaStateContains( String key ) { Transaction tx = db.beginTx(); Statement statement = statementContextProvider.instance(); final AtomicBoolean result = new AtomicBoolean( true ); statement.readOperations().schemaStateGetOrCreate( key, new Function<String, Object>() { @Override public Object apply( String s ) { result.set( false ); return null; } } ); tx.success(); tx.finish(); return result.get(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_KernelIT.java
996
private class SchemaStateCheck implements Function<String, Integer> { int invocationCount; private ReadOperations readOperations; @Override public Integer apply( String s ) { invocationCount++; return Integer.parseInt( s ); } public SchemaStateCheck setUp() { this.readOperations = readOperationsInNewTransaction(); checkState(); commit(); return this; } public void assertCleared() { int count = invocationCount; checkState(); assertEquals( "schema state should have been cleared.", count + 1, invocationCount ); } public void assertNotCleared() { int count = invocationCount; checkState(); assertEquals( "schema state should not have been cleared.", count, invocationCount ); } private SchemaStateCheck checkState() { assertEquals( Integer.valueOf( 7 ), readOperations.schemaStateGetOrCreate( "7", this ) ); return this; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_ConstraintsCreationIT.java
997
public class ConstraintsCreationIT extends KernelIntegrationTest { @Test public void shouldBeAbleToStoreAndRetrieveUniquenessConstraintRule() throws Exception { // given UniquenessConstraint constraint; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // when constraint = statement.uniquenessConstraintCreate( labelId, propertyKeyId ); // then assertEquals( constraint, single( statement.constraintsGetForLabelAndPropertyKey( labelId,propertyKeyId ) ) ); assertEquals( constraint, single( statement.constraintsGetForLabel( labelId ) ) ); // given commit(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // when Iterator<UniquenessConstraint> constraints = statement .constraintsGetForLabelAndPropertyKey( labelId, propertyKeyId ); // then assertEquals( constraint, single( constraints ) ); } } @Test public void shouldNotPersistUniquenessConstraintsCreatedInAbortedTransaction() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); // when rollback(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // then Iterator<UniquenessConstraint> constraints = statement.constraintsGetForLabelAndPropertyKey( labelId, propertyKeyId ); assertFalse( "should not have any constraints", constraints.hasNext() ); } } @Test public void shouldNotStoreUniquenessConstraintThatIsRemovedInTheSameTransaction() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); UniquenessConstraint constraint = statement.uniquenessConstraintCreate( labelId, propertyKeyId ); // when statement.constraintDrop( constraint ); // then assertFalse( "should not have any constraints", statement.constraintsGetForLabelAndPropertyKey( labelId, propertyKeyId ).hasNext() ); // when commit(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // then assertFalse( "should not have any constraints", statement.constraintsGetForLabelAndPropertyKey( labelId, propertyKeyId ).hasNext() ); } } @Test public void shouldNotCreateUniquenessConstraintThatAlreadyExists() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); } // when try { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); fail( "Should not have validated" ); } // then catch ( AlreadyConstrainedException e ) { // good } } @Test public void shouldNotRemoveConstraintThatGetsReAdded() throws Exception { // given UniquenessConstraint constraint; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); constraint = statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); } SchemaStateCheck schemaState = new SchemaStateCheck().setUp(); { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // when statement.constraintDrop( constraint ); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // then assertEquals( singletonList( constraint ), asCollection( statement.constraintsGetForLabelAndPropertyKey( labelId, propertyKeyId ) ) ); schemaState.assertNotCleared(); } } @Test public void shouldClearSchemaStateWhenConstraintIsCreated() throws Exception { // given SchemaStateCheck schemaState = new SchemaStateCheck().setUp(); SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // when statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); // then schemaWriteOperationsInNewTransaction(); schemaState.assertCleared(); } @Test public void shouldClearSchemaStateWhenConstraintIsDropped() throws Exception { // given UniquenessConstraint constraint; SchemaStateCheck schemaState; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); constraint = statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); schemaState = new SchemaStateCheck().setUp(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // when statement.constraintDrop( constraint ); commit(); } // then schemaWriteOperationsInNewTransaction(); schemaState.assertCleared(); } @Test public void shouldCreateAnIndexToGoAlongWithAUniquenessConstraint() throws Exception { // when { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); } // then { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( asSet( new IndexDescriptor( labelId, propertyKeyId ) ), asSet( statement.uniqueIndexesGetAll() ) ); } } @Test public void shouldDropCreatedConstraintIndexWhenRollingBackConstraintCreation() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); assertEquals( asSet( new IndexDescriptor( labelId, propertyKeyId ) ), asSet( statement.uniqueIndexesGetAll() ) ); } // when rollback(); // then { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( emptySetOf( IndexDescriptor.class ), asSet( statement.uniqueIndexesGetAll() ) ); commit(); } } @Test public void shouldDropConstraintIndexWhenDroppingConstraint() throws Exception { // given UniquenessConstraint constraint; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); constraint = statement.uniquenessConstraintCreate( labelId, propertyKeyId ); assertEquals( asSet( new IndexDescriptor( labelId, propertyKeyId ) ), asSet( statement.uniqueIndexesGetAll() ) ); commit(); } // when { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.constraintDrop( constraint ); commit(); } // then { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( emptySetOf( IndexDescriptor.class ), asSet( statement.uniqueIndexesGetAll( ) ) ); commit(); } } @Test public void shouldNotDropConstraintThatDoesNotExist() throws Exception { // when { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); try { statement.constraintDrop( new UniquenessConstraint( labelId, propertyKeyId ) ); fail( "Should not have dropped constraint" ); } catch ( DropConstraintFailureException e ) { assertThat( e.getCause(), instanceOf( NoSuchConstraintException.class ) ); } commit(); } // then { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( emptySetOf( IndexDescriptor.class ), asSet( statement.uniqueIndexesGetAll() ) ); commit(); } } @Test public void committedConstraintRuleShouldCrossReferenceTheCorrespondingIndexRule() throws Exception { // when SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKeyId ); commit(); // then SchemaStorage schema = new SchemaStorage( neoStore().getSchemaStore() ); IndexRule indexRule = schema.indexRule( labelId, propertyKeyId ); UniquenessConstraintRule constraintRule = schema.uniquenessConstraint( labelId, propertyKeyId ); assertEquals( constraintRule.getId(), indexRule.getOwningConstraint().longValue() ); assertEquals( indexRule.getId(), constraintRule.getOwnedIndex() ); } @Test public void shouldNotLeaveAnyStateBehindAfterFailingToCreateConstraint() throws Exception { // given try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { assertEquals( Collections.<ConstraintDefinition>emptyList(), asList( db.schema().getConstraints() ) ); assertEquals( Collections.<IndexDefinition, Schema.IndexState>emptyMap(), indexesWithState( db.schema() ) ); db.createNode( label( "Foo" ) ).setProperty( "bar", "baz" ); db.createNode( label( "Foo" ) ).setProperty( "bar", "baz" ); tx.success(); } // when try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { db.schema().constraintFor( label( "Foo" ) ).assertPropertyIsUnique( "bar" ).create(); tx.success(); fail( "expected failure" ); } catch ( ConstraintViolationException e ) { assertTrue( e.getMessage().startsWith( "Unable to create CONSTRAINT" ) ); } // then try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { assertEquals( Collections.<ConstraintDefinition>emptyList(), asList( db.schema().getConstraints() ) ); assertEquals( Collections.<IndexDefinition, Schema.IndexState>emptyMap(), indexesWithState( db.schema() ) ); tx.success(); } } @Test public void shouldBeAbleToResolveConflictsAndRecreateConstraintAfterFailingToCreateConstraintDueToConflict() throws Exception { // given Node node1, node2; try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { assertEquals( Collections.<ConstraintDefinition>emptyList(), asList( db.schema().getConstraints() ) ); assertEquals( Collections.<IndexDefinition, Schema.IndexState>emptyMap(), indexesWithState( db.schema() ) ); (node1 = db.createNode( label( "Foo" ) )).setProperty( "bar", "baz" ); (node2 = db.createNode( label( "Foo" ) )).setProperty( "bar", "baz" ); tx.success(); } // when try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { db.schema().constraintFor( label( "Foo" ) ).assertPropertyIsUnique( "bar" ).create(); tx.success(); fail( "expected failure" ); } catch ( ConstraintViolationException e ) { assertTrue( e.getMessage().startsWith( "Unable to create CONSTRAINT" ) ); } try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { node1.delete(); node2.delete(); tx.success(); } // then - this should not fail try ( org.neo4j.graphdb.Transaction tx = db.beginTx() ) { db.schema().constraintFor( label( "Foo" ) ).assertPropertyIsUnique( "bar" ).create(); tx.success(); } } private static Map<IndexDefinition, Schema.IndexState> indexesWithState( Schema schema ) { HashMap<IndexDefinition, Schema.IndexState> result = new HashMap<>(); for ( IndexDefinition definition : schema.getIndexes() ) { result.put( definition, schema.getIndexState( definition ) ); } return result; } private int labelId, propertyKeyId; @Before public void createKeys() throws KernelException { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); this.labelId = statement.labelGetOrCreateForName( "Foo" ); this.propertyKeyId = statement.propertyKeyGetOrCreateForName( "bar" ); commit(); } private class SchemaStateCheck implements Function<String, Integer> { int invocationCount; private ReadOperations readOperations; @Override public Integer apply( String s ) { invocationCount++; return Integer.parseInt( s ); } public SchemaStateCheck setUp() { this.readOperations = readOperationsInNewTransaction(); checkState(); commit(); return this; } public void assertCleared() { int count = invocationCount; checkState(); assertEquals( "schema state should have been cleared.", count + 1, invocationCount ); } public void assertNotCleared() { int count = invocationCount; checkState(); assertEquals( "schema state should not have been cleared.", count, invocationCount ); } private SchemaStateCheck checkState() { assertEquals( Integer.valueOf( 7 ), readOperations.schemaStateGetOrCreate( "7", this ) ); return this; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_integrationtest_ConstraintsCreationIT.java
998
class UniqueInMemoryIndexReader implements IndexReader { private final HashMap<Object, Long> indexData; UniqueInMemoryIndexReader( Map<Object, Long> indexData ) { this.indexData = new HashMap<>( indexData ); } @Override public PrimitiveLongIterator lookup( Object value ) { Long result = indexData.get( value ); return result != null ? singletonPrimitiveLongIterator( result ) : emptyPrimitiveLongIterator(); } @Override public void close() { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_inmemory_UniqueInMemoryIndexReader.java
999
@Ignore( "This is not a test" ) public class SchemaIndexTestHelper { public static KernelExtensionFactory<SingleInstanceSchemaIndexProviderFactoryDependencies> singleInstanceSchemaIndexProviderFactory( String key, final SchemaIndexProvider provider ) { return new SingleInstanceSchemaIndexProviderFactory( key, provider ); } public interface SingleInstanceSchemaIndexProviderFactoryDependencies { Config config(); } private static class SingleInstanceSchemaIndexProviderFactory extends KernelExtensionFactory<SingleInstanceSchemaIndexProviderFactoryDependencies> { private final SchemaIndexProvider provider; private SingleInstanceSchemaIndexProviderFactory( String key, SchemaIndexProvider provider ) { super( key ); this.provider = provider; } @Override public Lifecycle newKernelExtension( SingleInstanceSchemaIndexProviderFactoryDependencies dependencies ) throws Throwable { return provider; } } public static IndexProxy mockIndexProxy() throws IOException { IndexProxy result = mock( IndexProxy.class ); when( result.drop() ).thenReturn( FutureAdapter.VOID ); when( result.close() ).thenReturn( FutureAdapter.VOID ); return result; } public static <T> T awaitFuture( Future<T> future ) { try { return future.get( 10, SECONDS ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new RuntimeException( e ); } catch ( ExecutionException | TimeoutException e ) { throw new RuntimeException( e ); } } public static void awaitLatch( CountDownLatch latch ) { try { latch.await( 10, SECONDS ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new RuntimeException( e ); } } public static void awaitIndexOnline( ReadOperations readOperations, IndexDescriptor indexRule ) throws IndexNotFoundKernelException { long start = System.currentTimeMillis(); while(true) { if ( readOperations.indexGetState( indexRule ) == InternalIndexState.ONLINE ) { break; } if(start + 1000 * 10 < System.currentTimeMillis()) { throw new RuntimeException( "Index didn't come online within a reasonable time." ); } } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_SchemaIndexTestHelper.java