Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
4,000
|
private class UnknownJoiningMemberWarning extends ClusterListener.Adapter
{
private final List<HostnamePort> initialHosts;
private UnknownJoiningMemberWarning( List<HostnamePort> initialHosts )
{
this.initialHosts = initialHosts;
}
@Override
public void joinedCluster( InstanceId member, URI uri )
{
for ( HostnamePort host : initialHosts )
{
if ( host.matches( uri ) )
{
return;
}
}
logger.info( "Member " + member + "("+uri+") joined cluster but was not part of initial hosts (" +
initialHosts + ")" );
}
@Override
public void leftCluster()
{
cluster.removeClusterListener( this );
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_client_ClusterJoin.java
|
4,001
|
public static class Cluster
{
private final String name;
private final List<Member> members = new ArrayList<Member>();
public Cluster( String name )
{
this.name = name;
}
public String getName()
{
return name;
}
public List<Member> getMembers()
{
return members;
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
Cluster cluster = (Cluster) o;
if ( !name.equals( cluster.name ) )
{
return false;
}
if ( !members.equals( cluster.members ) )
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = name.hashCode();
result = 31 * result + members.hashCode();
return result;
}
public boolean contains( URI serverId )
{
for ( Member member : members )
{
if ( serverId.toString().contains( member.getHost() ) )
{
return true;
}
}
return false;
}
public Member getByUri( URI serverId )
{
for ( Member member : members )
{
if ( serverId.toString().contains( member.getHost() ) )
{
return member;
}
}
return null;
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_client_Clusters.java
|
4,002
|
{
@Override
public void listeningAt( URI myUri )
{
me = myUri;
}
} );
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_OnlineBackupKernelExtension.java
|
4,003
|
public static class Member
{
private String host;
private boolean fullHaMember;
public Member( int port, boolean fullHaMember )
{
this( localhost() + ":" + port, fullHaMember );
}
public Member( String host )
{
this( host, true );
}
public Member( String host, boolean fullHaMember )
{
this.host = host;
this.fullHaMember = fullHaMember;
}
public boolean isFullHaMember()
{
return fullHaMember;
}
private static String localhost()
{
try
{
return InetAddress.getLocalHost().getHostAddress();
}
catch ( UnknownHostException e )
{
throw new RuntimeException( e );
}
}
public String getHost()
{
return host;
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
Member member = (Member) o;
if ( !host.equals( member.host ) )
{
return false;
}
return true;
}
@Override
public int hashCode()
{
return host.hashCode();
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_client_Clusters.java
|
4,004
|
{
@Override
public void listeningAt( URI me )
{
sem.release();
}
@Override
public void channelOpened( URI to )
{
}
@Override
public void channelClosed( URI to )
{
}
} );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,005
|
{
@Override
public int port()
{
return 1235;
}
@Override
public int defaultPort()
{
return 5001;
}
}, receiver, loggingMock );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,006
|
{
@Override
public void stop() throws Throwable
{
super.stop();
sem.release();
}
};
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,007
|
{
@Override
public HostnamePort clusterServer()
{
return new HostnamePort( "127.0.0.1:1235" );
}
@Override
public int defaultPort()
{
return 5001;
}
@Override
public String name()
{
return null;
}
}, new DevNullLoggingService() )
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,008
|
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sem.release();
return null;
}
} ).when( loggerMock ).warn( anyString() );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,009
|
public class NetworkSenderReceiverTest
{
public enum TestMessage implements MessageType
{
helloWorld
}
@Test
public void shouldSendAMessageFromAClientWhichIsReceivedByAServer() throws Exception
{
// given
CountDownLatch latch = new CountDownLatch( 1 );
LifeSupport life = new LifeSupport();
Server server1 = new Server( latch, MapUtil.stringMap( ClusterSettings.cluster_server.name(),
"localhost:1234", ClusterSettings.server_id.name(), "1",
ClusterSettings.initial_hosts.name(), "localhost:1234,localhost:1235" ) );
life.add( server1 );
Server server2 = new Server( latch, MapUtil.stringMap( ClusterSettings.cluster_server.name(), "localhost:1235",
ClusterSettings.server_id.name(), "2",
ClusterSettings.initial_hosts.name(), "localhost:1234,localhost:1235" ) );
life.add( server2 );
life.start();
// when
server1.process( Message.to( TestMessage.helloWorld, URI.create( "cluster://127.0.0.1:1235" ), "Hello World" ) );
// then
latch.await( 5, TimeUnit.SECONDS );
assertTrue( "server1 should have processed the message", server1.processedMessage() );
assertTrue( "server2 should have processed the message", server2.processedMessage() );
life.shutdown();
}
@Test
public void senderThatStartsAfterReceiverShouldEventuallyConnectSuccessfully() throws Throwable
{
/*
* This test verifies that a closed channel from a sender to a receiver is removed from the connections
* mapping in the sender. It starts a sender, connects it to a receiver and sends a message
*/
NetworkSender sender = null;
NetworkReceiver receiver = null;
try
{
Logging loggingMock = mock( Logging.class );
StringLogger loggerMock = mock( StringLogger.class );
when( loggingMock.getMessagesLog( Matchers.<Class>any() ) ).thenReturn( loggerMock );
final Semaphore sem = new Semaphore( 0 );
doAnswer( new Answer<Object>()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sem.release();
return null;
}
} ).when( loggerMock ).warn( anyString() );
receiver = new NetworkReceiver( new NetworkReceiver.Configuration()
{
@Override
public HostnamePort clusterServer()
{
return new HostnamePort( "127.0.0.1:1235" );
}
@Override
public int defaultPort()
{
return 5001;
}
@Override
public String name()
{
return null;
}
}, new DevNullLoggingService() )
{
@Override
public void stop() throws Throwable
{
super.stop();
sem.release();
}
};
sender = new NetworkSender( new NetworkSender.Configuration()
{
@Override
public int port()
{
return 1235;
}
@Override
public int defaultPort()
{
return 5001;
}
}, receiver, loggingMock );
sender.init();
sender.start();
receiver.addNetworkChannelsListener( new NetworkReceiver.NetworkChannelsListener()
{
@Override
public void listeningAt( URI me )
{
sem.release();
}
@Override
public void channelOpened( URI to )
{
}
@Override
public void channelClosed( URI to )
{
}
} );
final AtomicBoolean received = new AtomicBoolean( false );
receiver.addMessageProcessor( new MessageProcessor()
{
@Override
public boolean process( Message<? extends MessageType> message )
{
received.set( true );
sem.release();
return true;
}
} );
receiver.init();
receiver.start();
sem.acquire(); // wait for start from listeningAt() in the NetworkChannelsListener
sender.process( Message.to( TestMessage.helloWorld, URI.create( "cluster://127.0.0.1:1235" ), "Hello World" ) );
sem.acquire(); // wait for the listeningAt trigger on receive (same as the previous but with real URI this time)
sem.acquire(); // wait for process from the MessageProcessor
receiver.stop();
sem.acquire(); // wait for overridden stop method in receiver
sender.process( Message.to( TestMessage.helloWorld, URI.create( "cluster://127.0.0.1:1235" ), "Hello World2" ) );
sem.acquire(); // wait for the warn from the sender
receiver.start();
sem.acquire(); // wait for receiver.listeningAt()
received.set( false );
sender.process( Message.to( TestMessage.helloWorld, URI.create( "cluster://127.0.0.1:1235" ), "Hello World3" ) );
sem.acquire(); // wait for receiver.process();
assertTrue( received.get() );
}
finally
{
if ( sender != null )
{
sender.stop();
sender.shutdown();
}
if ( receiver != null )
{
receiver.stop();
receiver.shutdown();
}
}
}
private static class Server
implements Lifecycle, MessageProcessor
{
private final NetworkReceiver networkReceiver;
private final NetworkSender networkSender;
private final LifeSupport life = new LifeSupport();
private AtomicBoolean processedMessage = new AtomicBoolean();
private Server( final CountDownLatch latch, final Map<String, String> config )
{
final Config conf = new Config( config, ClusterSettings.class );
networkReceiver = life.add(new NetworkReceiver(new NetworkReceiver.Configuration()
{
@Override
public HostnamePort clusterServer()
{
return conf.get( ClusterSettings.cluster_server );
}
@Override
public int defaultPort()
{
return 5001;
}
@Override
public String name()
{
return null;
}
}, new DevNullLoggingService()));
networkSender = life.add(new NetworkSender(new NetworkSender.Configuration()
{
@Override
public int defaultPort()
{
return 5001;
}
@Override
public int port()
{
return conf.get( ClusterSettings.cluster_server ).getPort();
}
}, networkReceiver, new DevNullLoggingService()));
life.add( new LifecycleAdapter()
{
@Override
public void start() throws Throwable
{
networkReceiver.addMessageProcessor( new MessageProcessor()
{
@Override
public boolean process( Message<? extends MessageType> message )
{
// server receives a message
processedMessage.set(true);
latch.countDown();
return true;
}
} );
}
} );
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
life.start();
}
@Override
public void stop() throws Throwable
{
life.stop();
}
@Override
public void shutdown() throws Throwable
{
}
@Override
public boolean process( Message<? extends MessageType> message )
{
// server sends a message
this.processedMessage.set(true);
return networkSender.process( message );
}
public boolean processedMessage()
{
return this.processedMessage.get();
}
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_NetworkSenderReceiverTest.java
|
4,010
|
public class MessageTest
{
@Test
public void respondingToInternalMessageShouldProduceCorrectMessage() throws Exception
{
// Given
final Object payload = new Object();
final MessageType type = mock(MessageType.class);
Message message = Message.internal( type, payload );
// When
Message response = Message.respond( type, message, payload );
// Then
assertTrue( response.isInternal() );
assertEquals( payload, response.getPayload() );
assertEquals( type, response.getMessageType() );
}
@Test
public void respondingToExternalMessageShouldProperlySetToHeaders() throws Exception
{
// Given
final Object payload = new Object();
final MessageType type = mock(MessageType.class);
URI to = URI.create( "cluster://to" );
URI from = URI.create( "cluster://from" );
Message incoming = Message.to( type, to, payload );
incoming.setHeader( Message.FROM, from.toString() );
// When
Message response = Message.respond( type, incoming, payload );
// Then
assertFalse( response.isInternal() );
assertEquals( from.toString(), response.getHeader( Message.TO ) );
assertEquals( payload, response.getPayload() );
assertEquals( type, response.getMessageType() );
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_com_message_MessageTest.java
|
4,011
|
public class Message<MESSAGETYPE extends MessageType>
implements Serializable
{
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> to( MESSAGETYPE messageType, URI to )
{
return to( messageType, to, null );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> to( MESSAGETYPE messageType, URI to,
Object payload )
{
return new Message<MESSAGETYPE>( messageType, payload ).setHeader( TO, to.toString() );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> respond( MESSAGETYPE messageType,
Message<?> message, Object payload )
{
return message.hasHeader( Message.FROM ) ?
new Message<MESSAGETYPE>( messageType, payload ).setHeader( TO, message.getHeader( Message.FROM ) ) :
internal( messageType, payload );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> internal( MESSAGETYPE message )
{
return internal( message, null );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> internal( MESSAGETYPE message, Object payload )
{
return new Message<MESSAGETYPE>( message, payload );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> timeout( MESSAGETYPE message,
Message<?> causedBy )
{
return timeout( message, causedBy, null );
}
public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> timeout( MESSAGETYPE message,
Message<?> causedBy, Object payload )
{
return causedBy.copyHeadersTo( new Message<MESSAGETYPE>( message, payload ), Message.CONVERSATION_ID,
Message.CREATED_BY );
}
// Standard headers
public static final String CONVERSATION_ID = "conversation-id";
public static final String CREATED_BY = "created-by";
public static final String FROM = "from";
public static final String TO = "to";
public static final String INSTANCE_ID = "instance-id";
final private MESSAGETYPE messageType;
final private Object payload;
final private Map<String, String> headers = new HashMap<String, String>();
protected Message( MESSAGETYPE messageType, Object payload )
{
this.messageType = messageType;
this.payload = payload;
}
public MESSAGETYPE getMessageType()
{
return messageType;
}
public <T> T getPayload()
{
return (T) payload;
}
public Message<MESSAGETYPE> setHeader( String name, String value )
{
if ( value == null )
{
throw new IllegalArgumentException( String.format( "Header %s may not be set to null", name ) );
}
headers.put( name, value );
return this;
}
public boolean hasHeader( String name )
{
return headers.containsKey( name );
}
public boolean isInternal()
{
return !headers.containsKey( Message.TO );
}
public String getHeader( String name )
throws IllegalArgumentException
{
String value = headers.get( name );
if ( value == null )
{
throw new IllegalArgumentException( "No such header:" + name );
}
return value;
}
public <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> copyHeadersTo( Message<MESSAGETYPE> message,
String... names )
{
if ( names.length == 0 )
{
for ( Map.Entry<String, String> header : headers.entrySet() )
{
if ( !message.hasHeader( header.getKey() ) )
{
message.setHeader( header.getKey(), header.getValue() );
}
}
}
else
{
for ( String name : names )
{
String value = headers.get( name );
if ( value != null && !message.hasHeader( name ) )
{
message.setHeader( name, value );
}
}
}
return message;
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
Message message = (Message) o;
if ( headers != null ? !headers.equals( message.headers ) : message.headers != null )
{
return false;
}
if ( messageType != null ? !messageType.equals( message.messageType ) : message.messageType != null )
{
return false;
}
if ( payload != null ? !payload.equals( message.payload ) : message.payload != null )
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = messageType != null ? messageType.hashCode() : 0;
result = 31 * result + (payload != null ? payload.hashCode() : 0);
result = 31 * result + (headers != null ? headers.hashCode() : 0);
return result;
}
@Override
public String toString()
{
return messageType.name() + headers + (payload != null && payload instanceof String ? ": " + payload : "");
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_message_Message.java
|
4,012
|
private class NetworkNodePipelineFactory
implements ChannelPipelineFactory
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast( "frameEncoder", new ObjectEncoder( 2048 ) );
pipeline.addLast( "sender", new NetworkMessageSender() );
return pipeline;
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkSender.java
|
4,013
|
{
@Override
public void notify( NetworkChannelsListener listener )
{
listener.channelClosed( uri );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkSender.java
|
4,014
|
{
@Override
public void notify( NetworkChannelsListener listener )
{
listener.channelOpened( uri );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkSender.java
|
4,015
|
{
@Override
public void listeningAt( URI me )
{
NetworkSender.this.me = me;
}
@Override
public void channelOpened( URI to )
{
}
@Override
public void channelClosed( URI to )
{
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkSender.java
|
4,016
|
private class NetworkNodePipelineFactory
implements ChannelPipelineFactory
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast( "frameDecoder",new ObjectDecoder( 1024 * 1000, NetworkNodePipelineFactory.this.getClass().getClassLoader() ) );
pipeline.addLast( "serverHandler", new MessageReceiver() );
return pipeline;
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkReceiver.java
|
4,017
|
{
@Override
public void notify( NetworkChannelsListener listener )
{
listener.channelClosed( uri );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkReceiver.java
|
4,018
|
{
@Override
public void notify( NetworkChannelsListener listener )
{
listener.channelOpened( uri );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkReceiver.java
|
4,019
|
{
@Override
public void notify( NetworkChannelsListener listener )
{
listener.listeningAt( me );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkReceiver.java
|
4,020
|
public class ChannelOpenFailedException extends RuntimeException
{
public ChannelOpenFailedException()
{
super();
}
public ChannelOpenFailedException( String message )
{
super( message );
}
public ChannelOpenFailedException( String message, Throwable cause )
{
super( message, cause );
}
public ChannelOpenFailedException( Throwable cause )
{
super( cause );
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_com_ChannelOpenFailedException.java
|
4,021
|
public class ClustersXMLSerializerTest
{
@Test
public void testWriteRead() throws Exception
{
ClustersXMLSerializer serializer = new ClustersXMLSerializer( DocumentBuilderFactory.newInstance()
.newDocumentBuilder() );
Clusters clusters = new Clusters();
Clusters.Cluster cluster = new Clusters.Cluster( "default" );
clusters.getClusters().add( cluster );
cluster.getMembers().add( new Clusters.Member( "localhost:8001" ) );
cluster.getMembers().add( new Clusters.Member( "localhost:8002" ) );
Document doc = serializer.write( clusters );
Clusters clusters2 = serializer.read( doc );
assertEquals( clusters, clusters2 );
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_client_ClustersXMLSerializerTest.java
|
4,022
|
public class ClustersXMLSerializer
{
private DocumentBuilder documentBuilder;
public ClustersXMLSerializer( DocumentBuilder documentBuilder )
{
this.documentBuilder = documentBuilder;
}
public Clusters read( Document clustersXml )
{
Clusters clusters = new Clusters();
NodeList clustersList = clustersXml.getElementsByTagName( "cluster" );
for ( int i = 0; i < clustersList.getLength(); i++ )
{
Node clusterNode = clustersList.item( i );
Clusters.Cluster cluster = new Clusters.Cluster( clusterNode.getAttributes().getNamedItem( "name" )
.getTextContent() );
NodeList nodeList = clusterNode.getChildNodes();
for ( int j = 0; j < nodeList.getLength(); j++ )
{
Node nodeNode = nodeList.item( j );
String host = nodeNode.getTextContent().trim();
if ( !host.equals( "" ) )
{
Clusters.Member member = new Clusters.Member( nodeNode.getTextContent().trim() );
cluster.getMembers().add( member );
}
}
clusters.getClusters().add( cluster );
}
return clusters;
}
public Document write( Clusters clusters )
{
Document doc = documentBuilder.newDocument();
Node clustersNode = doc.createElement( "clusters" );
doc.appendChild( clustersNode );
for ( int i = 0; i < clusters.getClusters().size(); i++ )
{
Clusters.Cluster cluster = clusters.getClusters().get( i );
Node clusterNode = doc.createElement( "cluster" );
Attr name = doc.createAttribute( "name" );
name.setValue( cluster.getName() );
clusterNode.getAttributes().setNamedItem( name );
clustersNode.appendChild( clusterNode );
for ( Clusters.Member member : cluster.getMembers() )
{
Node nodeNode = doc.createElement( "member" );
nodeNode.setTextContent( member.getHost() );
clusterNode.appendChild( nodeNode );
}
}
return doc;
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_client_ClustersXMLSerializer.java
|
4,023
|
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
return TestMessage.class;
}
});
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_StateMachinesTest.java
|
4,024
|
{
@Override
public void execute( Runnable command )
{
command.run();
}
}, me );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_StateMachinesTest.java
|
4,025
|
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sentOut.addAll( (Collection<? extends Message>) invocation.getArguments()[0] );
return null;
}
} ).when( sender ).process( Matchers.<List<Message<? extends MessageType>>>any() );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_StateMachinesTest.java
|
4,026
|
{
@Override
public void execute( Runnable command )
{
command.run();
}
}, mock( InstanceId.class ) );
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_StateMachinesTest.java
|
4,027
|
{{
this.in = newIn;
this.out = newOut;
}};
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,028
|
public class ClusterAssertion
{
protected Map<Integer, InstanceAssertion> in;
protected Map<Integer, InstanceAssertion> out;
private ClusterAssertion()
{
}
public static ClusterAssertion basedOn( int[] serverIds )
{
Map<Integer, InstanceAssertion> out = new HashMap<Integer, InstanceAssertion>();
for ( int i = 0; i < serverIds.length; i++ )
{
out.put( i + 1, new InstanceAssertion( serverIds[i], URI.create( "cluster://server" + serverIds[i] ) ) );
}
ClusterAssertion result = new ClusterAssertion();
result.in = new HashMap<Integer, InstanceAssertion>( );
result.out = out;
return result;
}
protected void copy( ClusterAssertion assertion )
{
this.in = assertion.in;
this.out = assertion.out;
}
public ClusterAssertion joins( int... joiners )
{
final Map<Integer, InstanceAssertion> newIn = new HashMap<Integer, InstanceAssertion>( in );
final Map<Integer, InstanceAssertion> newOut = new HashMap<Integer, InstanceAssertion>( out );
for ( int joiner : joiners )
{
newIn.put( joiner, newOut.remove( joiner ) );
}
return new ClusterAssertion()
{{
this.in = newIn;
this.out = newOut;
}};
}
public ClusterAssertion failed( final int failed )
{
final Map<Integer, InstanceAssertion> newIn = new HashMap<Integer, InstanceAssertion>( in );
final InstanceAssertion current = in.get( failed );
InstanceAssertion failedInstance = new InstanceAssertion()
{{
copy( current );
this.isFailed = true;
}};
newIn.put( failed, failedInstance );
final ClusterAssertion realThis = this;
return new ClusterAssertion()
{{
copy( realThis );
this.in = newIn;
}};
}
public ClusterAssertion elected( final int elected, final String atRole )
{
final Map<Integer, InstanceAssertion> newIn = new HashMap<Integer, InstanceAssertion>();
for ( final Map.Entry<Integer, InstanceAssertion> instanceAssertionEntry : in.entrySet() )
{
final InstanceAssertion assertion = instanceAssertionEntry.getValue();
if ( !instanceAssertionEntry.getValue().isFailed )
{
newIn.put( instanceAssertionEntry.getKey(), new InstanceAssertion()
{{
copy( assertion );
this.roles.put( atRole, elected );
}});
}
else
{
newIn.put( instanceAssertionEntry.getKey(), instanceAssertionEntry.getValue() );
}
}
final ClusterAssertion realThis = this;
return new ClusterAssertion()
{{
copy( realThis );
this.in = newIn;
}};
}
public InstanceAssertion[] snapshot()
{
InstanceAssertion[] result = new InstanceAssertion[in.size()+out.size()];
for ( Map.Entry<Integer, InstanceAssertion> inEntry : in.entrySet() )
{
int key = inEntry.getKey() - 1;
assert result[ key ] == null : "double entry for "+inEntry.getKey();
result[ key ] = inEntry.getValue();
}
for ( Map.Entry<Integer, InstanceAssertion> outEntry : out.entrySet() )
{
int key = outEntry.getKey() - 1;
assert result[ key ] == null : "double entry for " + outEntry.getKey();
result[ key ] = outEntry.getValue();
}
return result;
}
public static class InstanceAssertion
{
int serverId;
URI uri;
boolean isFailed;
Map<Integer, URI> reachableInstances = new HashMap<Integer, URI>();
Map<Integer, URI> failedInstances = new HashMap<Integer, URI>();
Map<String, Integer> roles = new HashMap<String, Integer>();
public InstanceAssertion()
{}
public InstanceAssertion( int serverId, URI uri )
{
this.serverId = serverId;
this.uri = uri;
}
protected void copy( InstanceAssertion instance )
{
this.serverId = instance.serverId;
this.uri = instance.uri;
this.isFailed = instance.isFailed;
this.reachableInstances = new HashMap<Integer, URI>( instance.reachableInstances );
this.failedInstances = new HashMap<Integer, URI>( instance.failedInstances );
this.roles = new HashMap<String, Integer>( instance.roles );
}
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,029
|
@Service.Implementation( BackupExtensionService.class )
public class ExitOnCallBackupProvider extends BackupExtensionService
{
public ExitOnCallBackupProvider()
{
super( "exit" );
}
@Override
public URI resolve( URI from, Args args, Logging logging )
{
System.exit( from.getPort() );
return null;
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_test_ExitOnCallBackupProvider.java
|
4,030
|
@Service.Implementation(TransactionInterceptorProvider.class)
@Deprecated
public class VerifyingTransactionInterceptorProvider
extends org.neo4j.consistency.checking.incremental.intercept.VerifyingTransactionInterceptorProvider
{
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_log_VerifyingTransactionInterceptorProvider.java
|
4,031
|
@Service.Implementation(TransactionInterceptorProvider.class)
@Deprecated
public class InconsistencyLoggingTransactionInterceptorProvider
extends org.neo4j.consistency.checking.incremental.intercept.InconsistencyLoggingTransactionInterceptorProvider
{
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_log_InconsistencyLoggingTransactionInterceptorProvider.java
|
4,032
|
NONE( null, null )
{
@Override
public void configure( Map<String, String> config )
{
// do nothing
}
},
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_VerificationLevel.java
|
4,033
|
public class TestOnlineBackupExtension extends KernelExtensionFactoryContractTest
{
public TestOnlineBackupExtension()
{
super( OnlineBackupExtensionFactory.KEY, OnlineBackupExtensionFactory.class );
}
@Override
protected Map<String, String> configuration( boolean shouldLoad, int instance )
{
Map<String, String> configuration = super.configuration( shouldLoad, instance );
if ( shouldLoad )
{
configuration.put( OnlineBackupSettings.online_backup_enabled.name(), Settings.TRUE );
configuration.put( OnlineBackupSettings.online_backup_server.name(), ":"+(BackupServer.DEFAULT_PORT + instance) );
}
return configuration;
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestOnlineBackupExtension.java
|
4,034
|
public class TestExtensions
{
@Test
public void testLoadDummyOk() throws Exception
{
assertEquals( 125,
BackupEmbeddedIT.runBackupToolFromOtherJvmToGetExitCode(
"-full", "-from", "exit://localhost:125", "-to",
"foobar/123" ) );
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestExtensions.java
|
4,035
|
public class TestConfiguration
{
private static final String SOURCE_DIR = "target/db";
private static final String BACKUP_DIR = "target/full-backup";
@Before
public void before() throws Exception
{
FileUtils.deleteDirectory( new File( SOURCE_DIR ) );
FileUtils.deleteDirectory( new File( BACKUP_DIR ) );
}
@Test
public void testOnByDefault() throws Exception
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( SOURCE_DIR );
OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).full( BACKUP_DIR );
db.shutdown();
}
@Test
public void testOffByConfig() throws Exception
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( SOURCE_DIR ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.FALSE ).
newGraphDatabase();
try
{
OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).full( BACKUP_DIR );
fail( "Shouldn't be possible" );
}
catch ( Exception e )
{ // Good
}
db.shutdown();
}
@Test
public void testEnableDefaultsInConfig() throws Exception
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( SOURCE_DIR ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
newGraphDatabase();
OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).full( BACKUP_DIR );
db.shutdown();
}
@Test
public void testEnableCustomPortInConfig() throws Exception
{
String customPort = "12345";
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( SOURCE_DIR ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
setConfig( OnlineBackupSettings.online_backup_server, ":"+customPort ).newGraphDatabase();
try
{
OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).full( BACKUP_DIR );
fail( "Shouldn't be possible" );
}
catch ( Exception e )
{ // Good
}
OnlineBackup.from( InetAddress.getLocalHost().getHostAddress(), Integer.parseInt(customPort) ).full( BACKUP_DIR );
db.shutdown();
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestConfiguration.java
|
4,036
|
@SuppressWarnings( "serial" )
private static class LockProcess extends SubProcess<StartupChecker, String> implements StartupChecker
{
private volatile Object state;
@Override
public boolean startupOk()
{
Object result;
do
{
result = state;
}
while ( result == null );
return !( state instanceof Exception );
}
@Override
protected void startup( String path ) throws Throwable
{
GraphDatabaseService db = null;
try
{
db = new GraphDatabaseFactory().newEmbeddedDatabase( path );
}
catch ( RuntimeException ex )
{
if (ex.getCause().getCause() instanceof StoreLockException )
{
state = ex;
return;
}
}
state = new Object();
if ( db != null )
{
db.shutdown();
}
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestBackup.java
|
4,037
|
{
@Override
public boolean accept( File dir, String name )
{
return name.startsWith( "nioneo_logical.log" )
&& !name.endsWith( "active" );
}
} ).length;
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestBackup.java
|
4,038
|
public class TestBackup
{
private File serverPath;
private File otherServerPath;
private File backupPath;
@Rule
public TestName testName = new TestName();
@Before
public void before() throws Exception
{
File base = TargetDirectory.forTest( getClass() ).cleanDirectory( testName.getMethodName() );
serverPath = new File( base, "server" );
otherServerPath = new File( base, "server2" );
backupPath = new File( base, "backuedup-serverdb" );
}
// TODO MP: What happens if the server database keeps growing, virtually making the files endless?
@Test
public void makeSureFullFailsWhenDbExists() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
createInitialDataSet( backupPath );
try
{
backup.full( backupPath.getPath() );
fail( "Shouldn't be able to do full backup into existing db" );
}
catch ( Exception e )
{
// good
}
shutdownServer( server );
}
@Test
public void makeSureIncrementalFailsWhenNoDb() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
try
{
backup.incremental( backupPath.getPath() );
fail( "Shouldn't be able to do incremental backup into non-existing db" );
}
catch ( Exception e )
{
// Good
}
shutdownServer( server );
}
@Test
public void backupLeavesLastTxInLog() throws Exception
{
GraphDatabaseAPI db = null;
ServerInterface server = null;
try
{
createInitialDataSet( serverPath );
server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
shutdownServer( server );
server = null;
db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( backupPath.getPath() );
for ( XaDataSource ds : db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getAllRegisteredDataSources() )
{
ds.getMasterForCommittedTx( ds.getLastCommittedTxId() );
}
db.shutdown();
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
shutdownServer( server );
server = null;
db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( backupPath.getPath() );
for ( XaDataSource ds : db.getDependencyResolver().resolveDependency( XaDataSourceManager.class).getAllRegisteredDataSources() )
{
ds.getMasterForCommittedTx( ds.getLastCommittedTxId() );
}
}
finally
{
if ( db != null )
{
db.shutdown();
}
if ( server != null )
{
shutdownServer( server );
}
}
}
@Test
public void incrementalBackupLeavesOnlyLastTxInLog() throws Exception
{
GraphDatabaseAPI db = null;
ServerInterface server = null;
try
{
createInitialDataSet( serverPath );
server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
shutdownServer( server );
server = null;
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
shutdownServer( server );
server = null;
// do 2 rotations, add two empty logs
new GraphDatabaseFactory().newEmbeddedDatabase( backupPath.getPath() ).shutdown();
new GraphDatabaseFactory().newEmbeddedDatabase( backupPath.getPath() ).shutdown();
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
shutdownServer( server );
server = null;
int logsFound = backupPath.listFiles( new FilenameFilter()
{
@Override
public boolean accept( File dir, String name )
{
return name.startsWith( "nioneo_logical.log" )
&& !name.endsWith( "active" );
}
} ).length;
// 2 one the real and the other from the rotation of shutdown
assertEquals( 2, logsFound );
db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( backupPath.getPath() );
for ( XaDataSource ds : db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getAllRegisteredDataSources() )
{
ds.getMasterForCommittedTx( ds.getLastCommittedTxId() );
}
}
finally
{
if ( db != null )
{
db.shutdown();
}
if ( server != null )
{
shutdownServer( server );
}
}
}
@Test
public void fullThenIncremental() throws Exception
{
DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
// START SNIPPET: onlineBackup
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
// END SNIPPET: onlineBackup
assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) );
shutdownServer( server );
DbRepresentation furtherRepresentation = addMoreData( serverPath );
server = startServer( serverPath );
// START SNIPPET: onlineBackup
backup.incremental( backupPath.getPath() );
// END SNIPPET: onlineBackup
assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) );
shutdownServer( server );
}
@Test
public void makeSureNoLogFileRemains() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
// First check full
backup.full( backupPath.getPath() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
// Then check empty incremental
backup.incremental( backupPath.getPath() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
// Then check real incremental
shutdownServer( server );
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
shutdownServer( server );
}
@Test
public void makeSureStoreIdIsEnforced() throws Exception
{
// Create data set X on server A
DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
// Grab initial backup from server A
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) );
shutdownServer( server );
// Create data set X+Y on server B
createInitialDataSet( otherServerPath );
addMoreData( otherServerPath );
server = startServer( otherServerPath );
// Try to grab incremental backup from server B.
// Data should be OK, but store id check should prevent that.
try
{
backup.incremental( backupPath.getPath() );
fail( "Shouldn't work" );
}
catch ( MismatchingStoreIdException e )
{ // Good
}
shutdownServer( server );
// Just make sure incremental backup can be received properly from
// server A, even after a failed attempt from server B
DbRepresentation furtherRepresentation = addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) );
shutdownServer( server );
}
private ServerInterface startServer( File path ) throws Exception
{
/*
ServerProcess server = new ServerProcess();
try
{
server.startup( Pair.of( path, "true" ) );
}
catch ( Throwable e )
{
// TODO Auto-generated catch block
throw new RuntimeException( e );
}
*/
ServerInterface server = new EmbeddedServer( path.getPath(), "127.0.0.1:6362" );
server.awaitStarted();
return server;
}
private void shutdownServer( ServerInterface server ) throws Exception
{
server.shutdown();
Thread.sleep( 1000 );
}
private DbRepresentation addMoreData( File path )
{
GraphDatabaseService db = startGraphDatabase( path );
Transaction tx = db.beginTx();
Node node = db.createNode();
node.setProperty( "backup", "Is great" );
db.createNode().createRelationshipTo( node,
DynamicRelationshipType.withName( "LOVES" ) );
tx.success();
tx.finish();
DbRepresentation result = DbRepresentation.of( db );
db.shutdown();
return result;
}
private GraphDatabaseService startGraphDatabase( File path )
{
return new GraphDatabaseFactory().
newEmbeddedDatabaseBuilder( path.getPath() ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.FALSE ).
setConfig( GraphDatabaseSettings.keep_logical_logs, Settings.TRUE ).
newGraphDatabase();
}
private DbRepresentation createInitialDataSet( File path )
{
GraphDatabaseService db = startGraphDatabase( path );
Transaction tx = db.beginTx();
Node node = db.createNode();
node.setProperty( "myKey", "myValue" );
Index<Node> nodeIndex = db.index().forNodes( "db-index" );
nodeIndex.add( node, "myKey", "myValue" );
db.createNode().createRelationshipTo( node,
DynamicRelationshipType.withName( "KNOWS" ) );
tx.success();
tx.finish();
DbRepresentation result = DbRepresentation.of( db );
db.shutdown();
return result;
}
@Test
public void multipleIncrementals() throws Exception
{
GraphDatabaseService db = null;
try
{
db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath.getPath() ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
newGraphDatabase();
Transaction tx = db.beginTx();
Index<Node> index = db.index().forNodes( "yo" );
index.add( db.createNode(), "justTo", "commitATx" );
tx.success();
tx.finish();
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
long lastCommittedTxForLucene = getLastCommittedTx( backupPath.getPath() );
for ( int i = 0; i < 5; i++ )
{
tx = db.beginTx();
Node node = db.createNode();
index.add( node, "key", "value" + i );
tx.success();
tx.finish();
backup = backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( lastCommittedTxForLucene + i + 1,
getLastCommittedTx( backupPath.getPath() ) );
}
}
finally
{
if ( db != null )
{
db.shutdown();
}
}
}
@Test
public void backupIndexWithNoCommits() throws Exception
{
GraphDatabaseService db = null;
try
{
db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath.getPath() ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
newGraphDatabase();
Transaction transaction = db.beginTx();
try
{
db.index().forNodes( "created-no-commits" );
transaction.success();
}
finally
{
transaction.finish();
}
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
}
finally
{
if ( db != null )
{
db.shutdown();
}
}
}
@SuppressWarnings("deprecation")
private long getLastCommittedTx( String path )
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( path );
try
{
XaDataSource ds = ((GraphDatabaseAPI)db).getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getNeoStoreDataSource();
return ds.getLastCommittedTxId();
}
finally
{
db.shutdown();
}
}
@Test
public void backupEmptyIndex() throws Exception
{
String key = "name";
String value = "Neo";
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath.getPath() ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
newGraphDatabase();
Transaction tx = db.beginTx();
Index<Node> index;
Node node;
try
{
index = db.index().forNodes( key );
node = db.createNode();
node.setProperty( key, value );
tx.success();
}
finally
{
tx.finish();
}
OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertEquals( DbRepresentation.of( db ), DbRepresentation.of( backupPath ) );
FileUtils.deleteDirectory( new File( backupPath.getPath() ) );
OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertEquals( DbRepresentation.of( db ), DbRepresentation.of( backupPath ) );
tx = db.beginTx();
try
{
index.add( node, key, value );
tx.success();
}
finally
{
tx.finish();
}
FileUtils.deleteDirectory( new File( backupPath.getPath() ) );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( DbRepresentation.of( db ), DbRepresentation.of( backupPath ) );
db.shutdown();
}
@Test
public void shouldRetainFileLocksAfterFullBackupOnLiveDatabase() throws Exception
{
String sourcePath = "target/var/serverdb-lock";
FileUtils.deleteDirectory( new File( sourcePath ) );
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( sourcePath ).
setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
newGraphDatabase();
try
{
assertStoreIsLocked( sourcePath );
OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertStoreIsLocked( sourcePath );
}
finally
{
db.shutdown();
}
}
private static void assertStoreIsLocked( String path )
{
try
{
new GraphDatabaseFactory().newEmbeddedDatabase( path).shutdown();
fail( "Could start up database in same process, store not locked" );
}
catch ( RuntimeException ex )
{
assertThat( ex.getCause().getCause(), instanceOf( StoreLockException.class ) );
}
StartupChecker proc = new LockProcess().start( path );
try
{
assertFalse( "Could start up database in subprocess, store is not locked", proc.startupOk() );
}
finally
{
SubProcess.stop( proc );
}
}
public interface StartupChecker
{
boolean startupOk();
}
@SuppressWarnings( "serial" )
private static class LockProcess extends SubProcess<StartupChecker, String> implements StartupChecker
{
private volatile Object state;
@Override
public boolean startupOk()
{
Object result;
do
{
result = state;
}
while ( result == null );
return !( state instanceof Exception );
}
@Override
protected void startup( String path ) throws Throwable
{
GraphDatabaseService db = null;
try
{
db = new GraphDatabaseFactory().newEmbeddedDatabase( path );
}
catch ( RuntimeException ex )
{
if (ex.getCause().getCause() instanceof StoreLockException )
{
state = ex;
return;
}
}
state = new Object();
if ( db != null )
{
db.shutdown();
}
}
}
private static boolean checkLogFileExistence( String directory )
{
return new File( directory, StringLogger.DEFAULT_NAME ).exists();
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_TestBackup.java
|
4,039
|
{
@Override
public void run()
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
shutdownProcess();
}
}.start();
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_ServerProcess.java
|
4,040
|
public class ServerProcess extends SubProcess<ServerInterface, Pair<String, String>> implements ServerInterface
{
private volatile transient GraphDatabaseService db;
@Override
public void startup( Pair<String, String> config ) throws Throwable
{
String storeDir = config.first();
String backupConfigValue = config.other();
if ( backupConfigValue == null )
{
this.db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir );
}
else
{
// TODO This is using the old config style - is this class even used anywhere!?
this.db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( storeDir ).setConfig( "enable_online_backup", backupConfigValue ).newGraphDatabase();
}
}
@Override
public void awaitStarted()
{
while ( db == null )
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
}
@Override
public void shutdown( boolean normal )
{
db.shutdown();
new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
shutdownProcess();
}
}.start();
}
protected void shutdownProcess()
{
super.shutdown();
}
}
| false
|
enterprise_backup_src_test_java_org_neo4j_backup_ServerProcess.java
|
4,041
|
private static class TxDiffLogConfig implements ConfigParam
{
private final String targetFile;
private final VerificationLevel level;
TxDiffLogConfig( VerificationLevel level, String targetFile )
{
this.level = level;
this.targetFile = targetFile;
}
@Override
public void configure( Map<String, String> config )
{
if ( targetFile != null )
{
level.configureWithDiffLog( config, targetFile );
}
else
{
level.configure( config );
}
}
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_RebuildFromLogs.java
|
4,042
|
private static class CommandFactory extends XaCommandFactory
{
@Override
public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException
{
return Command.readCommand( null, null, byteChannel, buffer );
}
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_RebuildFromLogs.java
|
4,043
|
class RebuildFromLogs
{
private static final FileSystemAbstraction FS = new DefaultFileSystemAbstraction();
/*
* TODO: This process can be sped up if the target db doesn't have to write tx logs.
*/
private final NeoStoreXaDataSource nioneo;
private final StoreAccess stores;
RebuildFromLogs( GraphDatabaseAPI graphdb )
{
this.nioneo = getDataSource( graphdb, NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
this.stores = new StoreAccess( graphdb );
}
RebuildFromLogs applyTransactionsFrom( ProgressListener progress, File sourceDir ) throws IOException
{
LogExtractor extractor = null;
try
{
extractor = LogExtractor.from( FS, sourceDir, new Monitors().newMonitor( ByteCounterMonitor.class ) );
for ( InMemoryLogBuffer buffer = new InMemoryLogBuffer(); ; buffer.reset() )
{
long txId = extractor.extractNext( buffer );
if ( txId == -1 )
{
break;
}
applyTransaction( txId, buffer );
progress.set( txId );
}
}
finally
{
if ( extractor != null )
{
extractor.close();
}
progress.done();
}
return this;
}
public void applyTransaction( long txId, ReadableByteChannel txData ) throws IOException
{
nioneo.applyCommittedTransaction( txId, txData );
}
private static NeoStoreXaDataSource getDataSource( GraphDatabaseAPI graphdb, String name )
{
NeoStoreXaDataSource datasource = graphdb.getDependencyResolver().resolveDependency( XaDataSourceManager.class )
.getNeoStoreDataSource();
if ( datasource == null )
{
throw new NullPointerException( "Could not access " + name );
}
return datasource;
}
public static void main( String[] args )
{
if ( args == null )
{
printUsage();
return;
}
Args params = new Args( args );
@SuppressWarnings("boxing")
boolean full = params.getBoolean( "full", false, true );
List<String> orphans = params.orphans();
args = orphans.toArray( new String[orphans.size()] );
if ( args.length != 2 )
{
printUsage( "Exactly two positional arguments expected: "
+ "<source dir with logs> <target dir for graphdb>, got " + args.length );
System.exit( -1 );
return;
}
File source = new File( args[0] ), target = new File( args[1] );
if ( !source.isDirectory() )
{
printUsage( source + " is not a directory" );
System.exit( -1 );
return;
}
if ( target.exists() )
{
if ( target.isDirectory() )
{
if ( new BackupService().directoryContainsDb( target.getAbsolutePath() ) )
{
printUsage( "target graph database already exists" );
System.exit( -1 );
return;
}
else
{
System.err.println( "WARNING: the directory " + target + " already exists" );
}
}
else
{
printUsage( target + " is a file" );
System.exit( -1 );
return;
}
}
long maxFileId = findMaxLogFileId( source );
if ( maxFileId < 0 )
{
printUsage( "Inconsistent number of log files found in " + source );
System.exit( -1 );
return;
}
long txCount = findLastTransactionId( source, LOGICAL_LOG_DEFAULT_NAME + ".v" + maxFileId );
String txdifflog = params.get( "txdifflog", null, new File( target, "txdiff.log" ).getAbsolutePath() );
GraphDatabaseAPI graphdb = BackupService.startTemporaryDb( target.getAbsolutePath(),
new TxDiffLogConfig( full
? VerificationLevel.FULL_WITH_LOGGING
: VerificationLevel.LOGGING, txdifflog ) );
ProgressMonitorFactory progress;
if ( txCount < 0 )
{
progress = ProgressMonitorFactory.NONE;
System.err.println( "Unable to report progress, cannot find highest txId, attempting rebuild anyhow." );
}
else
{
progress = ProgressMonitorFactory.textual( System.err );
}
try
{
try
{
ProgressListener listener = progress
.singlePart( String.format( "Rebuilding store from %s transactions ", txCount ), txCount );
RebuildFromLogs rebuilder = new RebuildFromLogs( graphdb ).applyTransactionsFrom( listener, source );
// if we didn't run the full checker for each transaction, run it afterwards
if ( !full )
{
rebuilder.checkConsistency();
}
}
finally
{
graphdb.shutdown();
}
}
catch ( Exception e )
{
System.err.println();
e.printStackTrace( System.err );
System.exit( -1 );
}
}
private static long findLastTransactionId( File storeDir, String logFileName )
{
long txId;
try
{
FileChannel channel = new RandomAccessFile( new File( storeDir, logFileName ), "r" ).getChannel();
try
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 );
txId = LogIoUtils.readLogHeader( buffer, channel, true )[1];
XaCommandFactory cf = new CommandFactory();
for ( LogEntry entry; (entry = LogIoUtils.readEntry( buffer, channel, cf )) != null; )
{
if ( entry instanceof LogEntry.Commit )
{
txId = ((LogEntry.Commit) entry).getTxId();
}
}
}
finally
{
if ( channel != null )
{
channel.close();
}
}
}
catch ( IOException e )
{
return -1;
}
return txId;
}
private void checkConsistency() throws ConsistencyCheckIncompleteException
{
Config tuningConfiguration = new Config( stringMap(),
GraphDatabaseSettings.class, ConsistencyCheckSettings.class );
new FullCheck( tuningConfiguration, ProgressMonitorFactory.textual( System.err ) )
.execute( new DirectStoreAccess( stores, nioneo.getLabelScanStore(), nioneo.getIndexProvider() ), StringLogger.SYSTEM );
}
private static void printUsage( String... msgLines )
{
for ( String line : msgLines )
{
System.err.println( line );
}
System.err.println( Args.jarUsage( RebuildFromLogs.class, "[-full] <source dir with logs> <target dir for " +
"graphdb>" ) );
System.err.println( "WHERE: <source dir> is the path for where transactions to rebuild from are stored" );
System.err.println( " <target dir> is the path for where to create the new graph database" );
System.err.println( " -full -- to run a full check over the entire store for each transaction" );
}
private static long findMaxLogFileId( File source )
{
return getHighestHistoryLogVersion( FS, source, LOGICAL_LOG_DEFAULT_NAME );
}
private static class TxDiffLogConfig implements ConfigParam
{
private final String targetFile;
private final VerificationLevel level;
TxDiffLogConfig( VerificationLevel level, String targetFile )
{
this.level = level;
this.targetFile = targetFile;
}
@Override
public void configure( Map<String, String> config )
{
if ( targetFile != null )
{
level.configureWithDiffLog( config, targetFile );
}
else
{
level.configure( config );
}
}
}
private static class CommandFactory extends XaCommandFactory
{
@Override
public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException
{
return Command.readCommand( null, null, byteChannel, buffer );
}
}
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_RebuildFromLogs.java
|
4,044
|
public class OnlineBackupSettings
{
@Description("Enable support for running online backups")
public static final Setting<Boolean> online_backup_enabled = setting( "online_backup_enabled", BOOLEAN, TRUE );
@Description("Listening server for online backups")
public static final Setting<HostnamePort> online_backup_server = setting( "online_backup_server", HOSTNAME_PORT,
"0.0.0.0:6362-6372" );
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_OnlineBackupSettings.java
|
4,045
|
private class StartBindingListener extends ClusterMemberListener.Adapter
{
@Override
public void memberIsAvailable( String role, InstanceId available, URI availableAtUri )
{
if ( graphDatabaseAPI.getDependencyResolver().resolveDependency( ClusterClient.class ).
getServerId().equals( available ) && "master".equals( role ) )
{
// It was me and i am master - yey!
{
try
{
URI backupUri = createBackupURI();
ClusterMemberAvailability ha = getClusterMemberAvailability();
ha.memberIsAvailable( BACKUP, backupUri );
}
catch ( Throwable t )
{
throw new RuntimeException( t );
}
}
}
}
@Override
public void memberIsUnavailable( String role, InstanceId unavailableId )
{
if ( graphDatabaseAPI.getDependencyResolver().resolveDependency( ClusterClient.class ).
getServerId().equals( unavailableId ) && "master".equals( role ) )
{
// It was me and i am master - yey!
{
try
{
ClusterMemberAvailability ha = getClusterMemberAvailability();
ha.memberIsUnavailable( BACKUP );
}
catch ( Throwable t )
{
throw new RuntimeException( t );
}
}
}
}
}
| false
|
enterprise_backup_src_main_java_org_neo4j_backup_OnlineBackupKernelExtension.java
|
4,046
|
{{
copy( current );
this.isFailed = true;
}};
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,047
|
{{
copy( realThis );
this.in = newIn;
}};
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,048
|
{{
copy( assertion );
this.roles.put( atRole, elected );
}});
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,049
|
private static class MessageDelivery
{
long messageDeliveryTime;
Message<? extends MessageType> message;
TestProtocolServer server;
private MessageDelivery( long messageDeliveryTime, Message<? extends MessageType> message,
TestProtocolServer server )
{
this.messageDeliveryTime = messageDeliveryTime;
this.message = message;
this.server = server;
}
public long getMessageDeliveryTime()
{
return messageDeliveryTime;
}
public Message<? extends MessageType> getMessage()
{
return message;
}
public TestProtocolServer getServer()
{
return server;
}
@Override
public String toString()
{
return "Deliver " + message.getMessageType().name() + " to " + server.getServer().getServerId() + " at "
+ messageDeliveryTime;
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_NetworkMock.java
|
4,050
|
public class StateMachinesTest
{
@Test
public void whenMessageHandlingCausesNewMessagesThenEnsureCorrectOrder() throws Exception
{
// Given
StateMachines stateMachines = new StateMachines( Mockito.mock(MessageSource.class),
Mockito.mock( MessageSender.class), Mockito.mock( Timeouts.class),
Mockito.mock(DelayedDirectExecutor.class), new Executor()
{
@Override
public void execute( Runnable command )
{
command.run();
}
}, mock( InstanceId.class ) );
ArrayList<TestMessage> handleOrder = new ArrayList<>( );
StateMachine stateMachine = new StateMachine( handleOrder, TestMessage.class, TestState.test,
mock( Logging.class ) );
stateMachines.addStateMachine( stateMachine );
// When
stateMachines.process( internal( TestMessage.message1 ) );
// Then
assertThat( handleOrder.toString(), equalTo( "[message1, message2, message4, message5, message3]" ) );
}
@Test
public void shouldAlwaysAddItsInstanceIdToOutgoingMessages() throws Exception
{
InstanceId me = new InstanceId( 42 );
final List<Message> sentOut = new LinkedList<Message>();
/*
* Lots of setup required. Must have a sender that keeps messages so we can see what the machine sent out.
* We must have the StateMachines actually delegate the incoming message and retrieve the generated outgoing.
* That means we need an actual StateMachine with a registered MessageType. And most of those are void
* methods, which means lots of Answer objects.
*/
// Given
MessageSender sender = mock( MessageSender.class );
// The sender, which adds messages outgoing to the list above.
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sentOut.addAll( (Collection<? extends Message>) invocation.getArguments()[0] );
return null;
}
} ).when( sender ).process( Matchers.<List<Message<? extends MessageType>>>any() );
StateMachines stateMachines = new StateMachines( mock( MessageSource.class ), sender,
mock( Timeouts.class ), mock( DelayedDirectExecutor.class ), new Executor()
{
@Override
public void execute( Runnable command )
{
command.run();
}
}, me );
// The state machine, which has a TestMessage message type and simply adds a TO header to the messages it
// is handed to handle.
StateMachine machine = mock( StateMachine.class );
when( machine.getMessageType() ).then( new Answer<Object>()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
return TestMessage.class;
}
});
doAnswer( new Answer<Object>()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
Message message = (Message) invocation.getArguments()[0];
MessageHolder holder = (MessageHolder) invocation.getArguments()[1];
message.setHeader( Message.TO, "to://neverland" );
holder.offer( message );
return null;
}
} ).when( machine ).handle( any( Message.class ), any( MessageHolder.class ) );
stateMachines.addStateMachine( machine );
// When
stateMachines.process( Message.internal( TestMessage.message1 ) );
// Then
assertEquals( "StateMachines should not make up messages from thin air", 1, sentOut.size() );
Message sent = sentOut.get( 0 );
assertTrue( "StateMachines should add the instance-id header", sent.hasHeader( Message.INSTANCE_ID ) );
assertEquals( "StateMachines should add instance-id header that has the correct value",
me.toString(), sent.getHeader( Message.INSTANCE_ID ) );
}
public enum TestMessage
implements MessageType
{
message1, message2, message3, message4, message5;
}
public enum TestState
implements State<List, TestMessage>
{
test
{
@Override
public State<?, ?> handle( List context, Message<TestMessage> message, MessageHolder outgoing ) throws Throwable
{
context.add(message.getMessageType());
switch ( message.getMessageType() )
{
case message1:
{
outgoing.offer( internal( TestMessage.message2 ) );
outgoing.offer( internal( TestMessage.message3 ) );
break;
}
case message2:
{
outgoing.offer( internal( TestMessage.message4 ) );
outgoing.offer( internal( TestMessage.message5 ) );
break;
}
}
return this;
}
};
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_StateMachinesTest.java
|
4,051
|
public class ScriptableNetworkFailureLatencyStrategy
implements NetworkLatencyStrategy
{
List<String> nodesDown = new ArrayList<String>( );
List<String[]> linksDown = new ArrayList<String[]>( );
public ScriptableNetworkFailureLatencyStrategy nodeIsDown(String id)
{
nodesDown.add( id );
return this;
}
public ScriptableNetworkFailureLatencyStrategy nodeIsUp(String id)
{
nodesDown.remove( id );
return this;
}
public ScriptableNetworkFailureLatencyStrategy linkIsDown(String node1, String node2)
{
linksDown.add( new String[]{node1, node2} );
linksDown.add( new String[]{ node2, node1 } );
return this;
}
public ScriptableNetworkFailureLatencyStrategy linkIsUp(String node1, String node2)
{
linksDown.remove( new String[]{ node1, node2 } );
linksDown.remove( new String[]{ node2, node1 } );
return this;
}
@Override
public long messageDelay(Message<? extends MessageType> message, String serverIdTo)
{
if (nodesDown.contains( serverIdTo ) || nodesDown.contains( message.getHeader( Message.FROM ) ))
return LOST;
if (linksDown.contains( new String[]{message.getHeader( Message.FROM ),serverIdTo} ))
return LOST;
return 0;
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ScriptableNetworkFailureLatencyStrategy.java
|
4,052
|
public class RandomDropNetworkFailureLatencyStrategy
implements NetworkLatencyStrategy
{
Random random;
private double rate;
/**
*
* @param seed Provide a seed for the Random, in order to produce repeatable tests.
* @param rate 1.0=no dropped messages, 0.0=all messages are lost
*/
public RandomDropNetworkFailureLatencyStrategy(long seed, double rate)
{
setRate( rate );
this.random = new Random( seed );
}
public void setRate( double rate )
{
this.rate = rate;
}
@Override
public long messageDelay(Message<? extends MessageType> message, String serverIdTo)
{
return random.nextDouble() > rate ? 0 : LOST;
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_RandomDropNetworkFailureLatencyStrategy.java
|
4,053
|
{
@Override
public void notify( BindingListener listener )
{
listener.listeningAt( me );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_ProtocolServer.java
|
4,054
|
public class ProtocolServer implements BindingNotifier
{
private final InstanceId me;
private URI boundAt;
protected StateMachineProxyFactory proxyFactory;
protected final StateMachines stateMachines;
private Iterable<BindingListener> bindingListeners = Listeners.newListeners();
private final StringLogger msgLog;
public ProtocolServer( InstanceId me, StateMachines stateMachines, Logging logging )
{
this.me = me;
this.stateMachines = stateMachines;
this.msgLog = logging.getMessagesLog( getClass() );
StateMachineConversations conversations = new StateMachineConversations(me);
proxyFactory = new StateMachineProxyFactory( stateMachines, conversations, me );
stateMachines.addMessageProcessor( proxyFactory );
}
@Override
public void addBindingListener( BindingListener listener )
{
bindingListeners = Listeners.addListener( listener, bindingListeners );
try
{
if ( boundAt != null )
{
listener.listeningAt( boundAt );
}
}
catch ( Throwable t )
{
msgLog.logMessage( "Failed while adding BindingListener", t );
}
}
@Override
public void removeBindingListener( BindingListener listener )
{
bindingListeners = Listeners.removeListener( listener, bindingListeners );
}
public void listeningAt( final URI me )
{
this.boundAt = me;
Listeners.notifyListeners( bindingListeners, new Listeners.Notification<BindingListener>()
{
@Override
public void notify( BindingListener listener )
{
listener.listeningAt( me );
}
} );
}
/**
* Ok to have this accessible like this?
*
* @return server id
*/
public InstanceId getServerId()
{
return me;
}
public StateMachines getStateMachines()
{
return stateMachines;
}
public void addStateTransitionListener( StateTransitionListener stateTransitionListener )
{
stateMachines.addStateTransitionListener( stateTransitionListener );
}
public <T> T newClient( Class<T> clientProxyInterface )
{
return proxyFactory.newProxy( clientProxyInterface );
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append( "Instance URI: " ).append( boundAt.toString() ).append( "\n" );
for( StateMachine stateMachine : stateMachines.getStateMachines() )
{
builder.append( " " ).append( stateMachine ).append( "\n" );
}
return builder.toString();
}
public Timeouts getTimeouts()
{
return stateMachines.getTimeouts();
}
public URI boundAt()
{
return boundAt;
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_ProtocolServer.java
|
4,055
|
{
@Override
public void run()
{
long now = System.currentTimeMillis();
protocolServer.getTimeouts().tick( now );
}
}, 0, 10, TimeUnit.MILLISECONDS );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_NetworkedServerFactory.java
|
4,056
|
{
private ScheduledExecutorService scheduler;
@Override
public void init()
throws Throwable
{
protocolServer.getTimeouts().tick( System.currentTimeMillis() );
}
@Override
public void start()
throws Throwable
{
scheduler = Executors.newSingleThreadScheduledExecutor( new DaemonThreadFactory( "timeout" ) );
scheduler.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
long now = System.currentTimeMillis();
protocolServer.getTimeouts().tick( now );
}
}, 0, 10, TimeUnit.MILLISECONDS );
}
@Override
public void stop()
throws Throwable
{
scheduler.shutdownNow();
}
@Override
public void shutdown()
throws Throwable
{
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_NetworkedServerFactory.java
|
4,057
|
{
@Override
public ExecutorService newInstance()
{
return Executors.newSingleThreadExecutor( new NamedThreadFactory( "State machine" ) );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_NetworkedServerFactory.java
|
4,058
|
public class MultipleFailureLatencyStrategy
implements NetworkLatencyStrategy
{
private final NetworkLatencyStrategy[] strategies;
public MultipleFailureLatencyStrategy(NetworkLatencyStrategy... strategies)
{
this.strategies = strategies;
}
public <T extends NetworkLatencyStrategy> T getStrategy(Class<T> strategyClass)
{
for( NetworkLatencyStrategy strategy : strategies )
{
if (strategyClass.isInstance( strategy ))
return (T) strategy;
}
throw new IllegalArgumentException( " No strategy of type "+strategyClass.getName()+" found" );
}
@Override
public long messageDelay(Message<? extends MessageType> message, String serverIdTo)
{
long totalDelay = 0;
for (NetworkLatencyStrategy strategy : strategies)
{
long delay = strategy.messageDelay(message, serverIdTo);
if (delay == LOST )
return delay;
totalDelay += delay;
}
return totalDelay;
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_MultipleFailureLatencyStrategy.java
|
4,059
|
{{
copy( realThis );
this.in = newIn;
}};
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,060
|
{
@Override
public void listeningAt( URI me )
{
context.getClusterContext().setBoundAt( me );
}
} );
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_MultiPaxosServerFactory.java
|
4,061
|
public static class GoalNotMetException extends Exception
{
public GoalNotMetException( List<SubGoal> subGoals, String additionalMessage )
{
super( createErrorMessage( subGoals, additionalMessage ) );
}
private static String createErrorMessage( List<SubGoal> subGoals, String additionalMessage )
{
StringBuilder builder = new StringBuilder( "These goals weren't met (" + additionalMessage + "):" );
for ( SubGoal subGoal : subGoals )
if ( subGoal.met() )
builder.append( "\n " + subGoal );
return builder.toString();
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_Goal.java
|
4,062
|
public class Goal
{
public static interface SubGoal
{
boolean met();
}
private final List<SubGoal> subGoals = new ArrayList<SubGoal>();
private final int maxMillisToWait;
private final int waitAfterAllFulfilled;
public Goal( int maxMillisToWait, int waitAfterAllFulfilled )
{
this.maxMillisToWait = maxMillisToWait;
this.waitAfterAllFulfilled = waitAfterAllFulfilled;
}
public Goal add( SubGoal subGoal )
{
subGoals.add( subGoal );
return this;
}
public void await() throws GoalNotMetException
{
long endTime = System.currentTimeMillis() + maxMillisToWait;
while ( !goalsAreMet() && System.currentTimeMillis() < endTime )
sleep( 100 );
if ( !goalsAreMet() )
throw new GoalNotMetException( subGoals, "timed out awaiting goals" );
// Wait a while to see if something makes a goal not valid shortly after it has
// been fulfilled, for example some unexpected state transition.
sleep( waitAfterAllFulfilled );
if ( !goalsAreMet() )
throw new GoalNotMetException( subGoals, "goals became unfulfilled after first being fulfilled" );
}
private void sleep( int millis )
{
try
{
Thread.sleep( millis );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
private boolean goalsAreMet()
{
for ( SubGoal subGoal : subGoals )
if ( !subGoal.met() )
return false;
return true;
}
public static class GoalNotMetException extends Exception
{
public GoalNotMetException( List<SubGoal> subGoals, String additionalMessage )
{
super( createErrorMessage( subGoals, additionalMessage ) );
}
private static String createErrorMessage( List<SubGoal> subGoals, String additionalMessage )
{
StringBuilder builder = new StringBuilder( "These goals weren't met (" + additionalMessage + "):" );
for ( SubGoal subGoal : subGoals )
if ( subGoal.met() )
builder.append( "\n " + subGoal );
return builder.toString();
}
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_Goal.java
|
4,063
|
public class FixedNetworkLatencyStrategy
implements NetworkLatencyStrategy
{
private long delay = 0;
public FixedNetworkLatencyStrategy()
{
this(0);
}
public FixedNetworkLatencyStrategy(long delay)
{
this.delay = delay;
}
@Override
public long messageDelay(Message<? extends MessageType> message, String serverIdTo)
{
return delay;
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_FixedNetworkLatencyStrategy.java
|
4,064
|
public class ExecutorLifecycleAdapter
implements Lifecycle, Executor
{
private ExecutorService executor;
private Factory<ExecutorService> executorServiceFactory;
public ExecutorLifecycleAdapter( Factory<ExecutorService> executorServiceFactory )
{
this.executorServiceFactory = executorServiceFactory;
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
executor = executorServiceFactory.newInstance();
}
@Override
public void stop() throws Throwable
{
if (executor != null)
{
executor.shutdown();
executor.awaitTermination( 30, TimeUnit.SECONDS );
executor = null;
}
}
@Override
public void shutdown() throws Throwable
{
}
@Override
public void execute( Runnable command )
{
if (executor != null)
executor.execute( command );
else
{
command.run();
}
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_ExecutorLifecycleAdapter.java
|
4,065
|
public class DelayedDirectExecutor
extends AbstractExecutorService
{
List<Runnable> runnables = new ArrayList<Runnable>();
@Override
public void shutdown()
{
}
@Override
public List<Runnable> shutdownNow()
{
return Collections.emptyList();
}
@Override
public boolean isShutdown()
{
return false;
}
@Override
public boolean isTerminated()
{
return false;
}
@Override
public boolean awaitTermination( long timeout, TimeUnit unit ) throws InterruptedException
{
return true;
}
@Override
public void execute( Runnable command )
{
runnables.add( command );
}
public void drain()
{
List<Runnable> current = runnables;
runnables = new ArrayList<Runnable>();
for ( Runnable runnable : current )
{
try
{
runnable.run();
}
catch ( Throwable e )
{
e.printStackTrace();
}
}
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_DelayedDirectExecutor.java
|
4,066
|
public class ClusterSettings
{
@Description( "Id for a cluster instance. Must be unique within the cluster." )
public static final Setting<Integer> server_id = setting( "ha.server_id", INTEGER, MANDATORY );
@Description( "The name of a cluster." )
public static final Setting<String> cluster_name = setting( "ha.cluster_name", STRING, "neo4j.ha",
illegalValueMessage( "Must be a valid cluster name" , matches( ANY ) ) );
@Description( "A comma-separated list of other members of the cluster to join." )
public static final Setting<List<HostnamePort>> initial_hosts = setting( "ha.initial_hosts",
list( ",", HOSTNAME_PORT ), MANDATORY );
@Description( "Host & port to bind the cluster management communication." )
public static final Setting<HostnamePort> cluster_server = setting( "ha.cluster_server", HOSTNAME_PORT,
"0.0.0.0:5001-5099" );
@Description( "Whether to allow this instance to create a cluster if unable to join." )
public static final Setting<Boolean> allow_init_cluster = setting( "ha.allow_init_cluster", BOOLEAN, TRUE );
// Timeout settings
/*
* ha.heartbeat_interval
* ha.paxos_timeout
* ha.learn_timeout
*/
@Description( "Default timeout used for clustering timeouts. Override specific timeout settings with proper" +
" values if necessary. This value is the default value for settings ha.heartbeat_interval," +
" ha.paxos_timeout and ha.learn_timeout." )
public static final Setting<Long> default_timeout = setting( "ha.default_timeout", DURATION, "5s" );
@Description( "How often heartbeat messages should be sent. Defaults to ha.default_timeout." )
public static final Setting<Long> heartbeat_interval = setting( "ha.heartbeat_interval", DURATION,
default_timeout );
@Description( "Timeout for heartbeats between cluster members. Should be at least twice that of ha.heartbeat_interval." )
public static final Setting<Long> heartbeat_timeout = setting( "ha.heartbeat_timeout", DURATION, "11s" );
/*
* ha.join_timeout
* ha.leave_timeout
*/
@Description( "Timeout for broadcasting values in cluster. Must consider end-to-end duration of Paxos algorithm." +
" This value is the default value for settings ha.join_timeout and ha.leave_timeout." )
public static final Setting<Long> broadcast_timeout = setting( "ha.broadcast_timeout", DURATION, "30s" );
@Description( "Timeout for joining a cluster. Defaults to ha.broadcast_timeout." )
public static final Setting<Long> join_timeout = setting( "ha.join_timeout", DURATION, broadcast_timeout );
@Description( "Timeout for waiting for configuration from an existing cluster member during cluster join." )
public static final Setting<Long> configuration_timeout = setting( "ha.configuration_timeout", DURATION, "1s" );
@Description( "Timeout for waiting for cluster leave to finish. Defaults to ha.broadcast_timeout." )
public static final Setting<Long> leave_timeout = setting( "ha.leave_timeout", DURATION, broadcast_timeout );
/*
* ha.phase1_timeout
* ha.phase2_timeout
* ha.election_timeout
*/
@Description( "Default timeout for all Paxos timeouts. Defaults to ha.default_timeout. This value is the default" +
" value for settings ha.phase1_timeout, ha.phase2_timeout and ha.election_timeout." )
public static final Setting<Long> paxos_timeout = setting( "ha.paxos_timeout", DURATION, default_timeout );
@Description( "Timeout for Paxos phase 1. Defaults to ha.paxos_timeout." )
public static final Setting<Long> phase1_timeout = setting( "ha.phase1_timeout", DURATION, paxos_timeout );
@Description( "Timeout for Paxos phase 2. Defaults to ha.paxos_timeout." )
public static final Setting<Long> phase2_timeout = setting( "ha.phase2_timeout", DURATION, paxos_timeout );
@Description( "Timeout for learning values. Defaults to ha.default_timeout." )
public static final Setting<Long> learn_timeout = setting( "ha.learn_timeout", DURATION, default_timeout );
@Description( "Timeout for waiting for other members to finish a role election. Defaults to ha.paxos_timeout." )
public static final Setting<Long> election_timeout = setting( "ha.election_timeout", DURATION, paxos_timeout );
public static final Setting<String> instance_name = setting("ha.instance_name", STRING, (String) null);
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_ClusterSettings.java
|
4,067
|
public static class InstanceAssertion
{
int serverId;
URI uri;
boolean isFailed;
Map<Integer, URI> reachableInstances = new HashMap<Integer, URI>();
Map<Integer, URI> failedInstances = new HashMap<Integer, URI>();
Map<String, Integer> roles = new HashMap<String, Integer>();
public InstanceAssertion()
{}
public InstanceAssertion( int serverId, URI uri )
{
this.serverId = serverId;
this.uri = uri;
}
protected void copy( InstanceAssertion instance )
{
this.serverId = instance.serverId;
this.uri = instance.uri;
this.isFailed = instance.isFailed;
this.reachableInstances = new HashMap<Integer, URI>( instance.reachableInstances );
this.failedInstances = new HashMap<Integer, URI>( instance.failedInstances );
this.roles = new HashMap<String, Integer>( instance.roles );
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_ClusterAssertion.java
|
4,068
|
public class ServerIdElectionCredentialsProvider
implements ElectionCredentialsProvider, BindingListener
{
private volatile URI me;
@Override
public void listeningAt( URI me )
{
this.me = me;
}
@Override
public ElectionCredentials getCredentials( String role )
{
return new ServerIdElectionCredentials( me );
}
}
| false
|
enterprise_cluster_src_main_java_org_neo4j_cluster_protocol_election_ServerIdElectionCredentialsProvider.java
|
4,069
|
public class HeartbeatIAmAliveProcessorTest
{
@Test
public void shouldNotCreateHeartbeatsForNonExistingInstances() throws Exception
{
// GIVEN
MessageHolder outgoing = mock( MessageHolder.class );
ClusterContext mockContext = mock( ClusterContext.class );
ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
when( mockConfiguration.getMembers() ).thenReturn(
new HashMap<InstanceId, URI>()
{{
put( new InstanceId( 1 ), URI.create( "ha://1" ) );
put( new InstanceId( 2 ), URI.create( "ha://2" ) );
}}
);
when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );
HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( outgoing, mockContext );
Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
.setHeader( Message.FROM, "some://value" ).setHeader( Message.INSTANCE_ID, "5" );
// WHEN
processor.process( incoming );
// THEN
verifyZeroInteractions( outgoing );
}
@Test
public void shouldNotProcessMessagesWithEqualFromAndToHeaders() throws Exception
{
URI to = URI.create( "ha://someAwesomeInstanceInJapan" );
// GIVEN
MessageHolder outgoing = mock( MessageHolder.class );
ClusterContext mockContext = mock( ClusterContext.class );
ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
when( mockConfiguration.getMembers() ).thenReturn(
new HashMap<InstanceId, URI>()
{{
put( new InstanceId( 1 ), URI.create( "ha://1" ) );
put( new InstanceId( 2 ), URI.create( "ha://2" ) );
}}
);
when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );
HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( outgoing, mockContext );
Message incoming = Message.to( mock( MessageType.class ), to ).setHeader( Message.FROM, to.toASCIIString() )
.setHeader( Message.INSTANCE_ID, "1" );
// WHEN
processor.process( incoming );
// THEN
verifyZeroInteractions( outgoing );
}
@Test
public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() throws Exception
{
final List<Message> sentOut = new LinkedList<Message>();
// Given
MessageHolder holder = mock( MessageHolder.class );
// The sender, which adds messages outgoing to the list above.
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sentOut.add( (Message) invocation.getArguments()[0] );
return null;
}
} ).when( holder ).offer( Matchers.<Message<MessageType>>any() );
ClusterContext mockContext = mock( ClusterContext.class );
ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
when( mockConfiguration.getMembers() ).thenReturn(
new HashMap<InstanceId, URI>()
{{
put( new InstanceId( 1 ), URI.create( "ha://1" ) );
put( new InstanceId( 2 ), URI.create( "ha://2" ) );
}}
);
when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );
HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );
Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
.setHeader( Message.INSTANCE_ID, "2" ).setHeader( Message.FROM, "ha://2" );
// WHEN
processor.process( incoming );
// THEN
assertEquals( 1, sentOut.size() );
assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
}
/*
* This test is required to ensure compatibility with the previous version. If we fail on non existing INSTANCE_ID
* header then heartbeats may pause during rolling upgrades and cause timeouts, which we don't want.
*/
@Test
public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception
{
final List<Message> sentOut = new LinkedList<Message>();
String instance2UriString = "ha://2";
// Given
MessageHolder holder = mock( MessageHolder.class );
// The sender, which adds messages outgoing to the list above.
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
sentOut.add( (Message) invocation.getArguments()[0] );
return null;
}
} ).when( holder ).offer( Matchers.<Message<MessageType>>any() );
ClusterContext mockContext = mock( ClusterContext.class );
ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
when( mockConfiguration.getIdForUri( URI.create( instance2UriString ) ) ).thenReturn( new InstanceId( 2 ) );
when( mockConfiguration.getMembers() ).thenReturn(
new HashMap<InstanceId, URI>()
{{
put( new InstanceId( 1 ), URI.create( "ha://1" ) );
put( new InstanceId( 2 ), URI.create( "ha://2" ) );
}}
);
when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );
HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );
Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
.setHeader( Message.FROM, instance2UriString );
// WHEN
processor.process( incoming );
// THEN
assertEquals( 1, sentOut.size() );
assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
}
}
| false
|
enterprise_cluster_src_test_java_org_neo4j_cluster_protocol_heartbeat_HeartbeatIAmAliveProcessorTest.java
|
4,070
|
{
@Override
protected void generateInitialData( GraphDatabaseService graphDb )
{
org.neo4j.graphdb.Transaction tx = graphDb.beginTx();
try
{
Node node1 = set( graphDb.createNode(),
property( "long short short", LONG_SHORT_STRING ) );
Node node2 = set( graphDb.createNode(),
property( "long string", LONG_STRING ) );
Node node3 = set( graphDb.createNode(),
property( "one", "1" ),
property( "two", "2" ),
property( "three", "3" ),
property( "four", "4" ),
property( "five", "5" ) );
Node node4 = set( graphDb.createNode(),
property( "name", "Leeloo Dallas" ) );
Node node5 = set( graphDb.createNode(),
property( "payload", LONG_SHORT_STRING ),
property( "more", LONG_STRING ) );
Node node6 = set( graphDb.createNode() );
set( node1.createRelationshipTo( node2, withName( "WHEEL" ) ) );
set( node2.createRelationshipTo( node3, withName( "WHEEL" ) ) );
set( node3.createRelationshipTo( node4, withName( "WHEEL" ) ) );
set( node4.createRelationshipTo( node5, withName( "WHEEL" ) ) );
set( node5.createRelationshipTo( node1, withName( "WHEEL" ) ) );
set( node6.createRelationshipTo( node1, withName( "STAR" ) ) );
set( node6.createRelationshipTo( node2, withName( "STAR" ) ) );
set( node6.createRelationshipTo( node3, withName( "STAR" ) ) );
set( node6.createRelationshipTo( node4, withName( "STAR" ) ) );
set( node6.createRelationshipTo( node5, withName( "STAR" ) ) );
tx.success();
}
finally
{
tx.finish();
}
}
@Override
protected Map<String, String> configuration( boolean initialData )
{
Map<String, String> config = super.configuration( initialData );
if ( !initialData )
{
config.put( GraphDatabaseSettings.intercept_deserialized_transactions.name(), "true" );
config.put( GraphDatabaseSettings.intercept_committing_transactions.name(), "true" );
config.put( TransactionInterceptorProvider.class.getSimpleName() + "." +
VerifyingTransactionInterceptorProvider.NAME, "true" );
}
return config;
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
4,071
|
{
@Override
public void checkReference( DynamicRecord record, PropertyKeyTokenRecord propertyKeyTokenRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
RecordAccess records )
{
if ( !propertyKeyTokenRecord.inUse() )
{
engine.report().propertyKeyNotInUse( propertyKeyTokenRecord );
}
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_SchemaRecordCheck.java
|
4,072
|
public class SchemaRecordCheck implements RecordCheck<DynamicRecord, ConsistencyReport.SchemaConsistencyReport>
{
enum Phase
{
/**
* Verify rules can be de-serialized, have valid forward references, and build up internal state
* for checking in back references in later phases (obligations)
*/
CHECK_RULES,
/** Verify obligations, that is correct back references */
CHECK_OBLIGATIONS
}
final SchemaRuleAccess ruleAccess;
final Map<Long, DynamicRecord> indexObligations;
final Map<Long, DynamicRecord> constraintObligations;
final Map<SchemaRuleContent, DynamicRecord> contentMap;
final Phase phase;
private SchemaRecordCheck(
SchemaRuleAccess ruleAccess,
Map<Long, DynamicRecord> indexObligations,
Map<Long, DynamicRecord> constraintObligations,
Map<SchemaRuleContent, DynamicRecord> contentMap,
Phase phase )
{
this.ruleAccess = ruleAccess;
this.indexObligations = indexObligations;
this.constraintObligations = constraintObligations;
this.contentMap = contentMap;
this.phase = phase;
}
public SchemaRecordCheck( SchemaRuleAccess ruleAccess )
{
this( ruleAccess,
new HashMap<Long, DynamicRecord>(),
new HashMap<Long, DynamicRecord>(),
new HashMap<SchemaRuleContent, DynamicRecord>(),
Phase.CHECK_RULES );
}
public SchemaRecordCheck forObligationChecking()
{
return new SchemaRecordCheck(
ruleAccess, indexObligations, constraintObligations, contentMap, Phase.CHECK_OBLIGATIONS );
}
@Override
public void check( DynamicRecord record,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
RecordAccess records )
{
if ( record.inUse() && record.isStartRecord() )
{
// parse schema rule
SchemaRule rule;
try
{
rule = ruleAccess.loadSingleSchemaRule( record.getId() );
}
catch ( MalformedSchemaRuleException e )
{
engine.report().malformedSchemaRule();
return;
}
// given a parsed schema rule
if ( Phase.CHECK_RULES == phase )
{
engine.comparativeCheck( records.label( rule.getLabel() ), VALID_LABEL );
SchemaRuleContent content = new SchemaRuleContent( rule );
DynamicRecord previousContentRecord = contentMap.put( content, record );
if ( null != previousContentRecord )
{
engine.report().duplicateRuleContent( previousContentRecord );
}
}
SchemaRule.Kind kind = rule.getKind();
switch ( kind )
{
case INDEX_RULE:
case CONSTRAINT_INDEX_RULE:
checkIndexRule( (IndexRule) rule, engine, record, records );
break;
case UNIQUENESS_CONSTRAINT:
checkUniquenessConstraintRule( (UniquenessConstraintRule) rule, engine, record, records );
break;
default:
engine.report().unsupportedSchemaRuleKind( kind );
}
}
}
private void checkUniquenessConstraintRule( UniquenessConstraintRule rule,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
DynamicRecord record, RecordAccess records )
{
if ( phase == Phase.CHECK_RULES )
{
engine.comparativeCheck( records.propertyKey( rule.getPropertyKey() ), VALID_PROPERTY_KEY );
DynamicRecord previousObligation = indexObligations.put( rule.getOwnedIndex(), record );
if ( null != previousObligation )
{
engine.report().duplicateObligation( previousObligation );
}
}
else if ( phase == Phase.CHECK_OBLIGATIONS )
{
DynamicRecord obligation = constraintObligations.get( rule.getId() );
if ( null == obligation)
{
engine.report().missingObligation( SchemaRule.Kind.CONSTRAINT_INDEX_RULE );
}
else
{
if ( obligation.getId() != rule.getOwnedIndex() )
{
engine.report().uniquenessConstraintNotReferencingBack( obligation );
}
}
}
}
private void checkIndexRule( IndexRule rule,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
DynamicRecord record, RecordAccess records )
{
if ( phase == Phase.CHECK_RULES )
{
engine.comparativeCheck( records.propertyKey( rule.getPropertyKey() ), VALID_PROPERTY_KEY );
if ( rule.isConstraintIndex() && rule.getOwningConstraint() != null )
{
DynamicRecord previousObligation = constraintObligations.put( rule.getOwningConstraint(), record );
if ( null != previousObligation )
{
engine.report().duplicateObligation( previousObligation );
}
}
}
else if ( phase == Phase.CHECK_OBLIGATIONS )
{
if ( rule.isConstraintIndex() )
{
DynamicRecord obligation = indexObligations.get( rule.getId() );
if ( null == obligation ) // no pointer to here
{
if ( rule.getOwningConstraint() != null ) // we only expect a pointer if we have an owner
{
engine.report().missingObligation( SchemaRule.Kind.UNIQUENESS_CONSTRAINT );
}
}
else
{
// if someone points to here, it must be our owner
if ( obligation.getId() != rule.getOwningConstraint() )
{
engine.report().constraintIndexRuleNotReferencingBack( obligation );
}
}
}
}
}
@Override
public void checkChange( DynamicRecord oldRecord, DynamicRecord newRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
DiffRecordAccess records )
{
}
public static final ComparativeRecordChecker<DynamicRecord,LabelTokenRecord,
ConsistencyReport.SchemaConsistencyReport> VALID_LABEL =
new ComparativeRecordChecker<DynamicRecord, LabelTokenRecord, ConsistencyReport.SchemaConsistencyReport>()
{
@Override
public void checkReference( DynamicRecord record, LabelTokenRecord labelTokenRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
RecordAccess records )
{
if ( !labelTokenRecord.inUse() )
{
engine.report().labelNotInUse( labelTokenRecord );
}
}
};
public static final ComparativeRecordChecker<DynamicRecord, PropertyKeyTokenRecord,
ConsistencyReport.SchemaConsistencyReport> VALID_PROPERTY_KEY =
new ComparativeRecordChecker<DynamicRecord, PropertyKeyTokenRecord, ConsistencyReport.SchemaConsistencyReport>()
{
@Override
public void checkReference( DynamicRecord record, PropertyKeyTokenRecord propertyKeyTokenRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
RecordAccess records )
{
if ( !propertyKeyTokenRecord.inUse() )
{
engine.report().propertyKeyNotInUse( propertyKeyTokenRecord );
}
}
};
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_SchemaRecordCheck.java
|
4,073
|
public class RelationshipTypeTokenRecordCheckTest extends
RecordCheckTestBase<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport, RelationshipTypeTokenRecordCheck>
{
public RelationshipTypeTokenRecordCheckTest()
{
super( new RelationshipTypeTokenRecordCheck(), ConsistencyReport.RelationshipTypeConsistencyReport.class );
}
@Test
public void shouldNotReportAnythingForRecordNotInUse() throws Exception
{
// given
RelationshipTypeTokenRecord label = notInUse( new RelationshipTypeTokenRecord( 42 ) );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = check( label );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingForRecordThatDoesNotReferenceADynamicBlock() throws Exception
{
// given
RelationshipTypeTokenRecord label = inUse( new RelationshipTypeTokenRecord( 42 ) );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = check( label );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportDynamicBlockNotInUse() throws Exception
{
// given
RelationshipTypeTokenRecord label = inUse( new RelationshipTypeTokenRecord( 42 ) );
DynamicRecord name = addRelationshipTypeName( notInUse( new DynamicRecord( 6 ) ) );
label.setNameId( (int) name.getId() );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = check( label );
// then
verify( report ).nameBlockNotInUse( name );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportEmptyName() throws Exception
{
// given
RelationshipTypeTokenRecord label = inUse( new RelationshipTypeTokenRecord( 42 ) );
DynamicRecord name = addRelationshipTypeName( inUse( new DynamicRecord( 6 ) ) );
label.setNameId( (int) name.getId() );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = check( label );
// then
verify( report ).emptyName( name );
verifyNoMoreInteractions( report );
}
// change checking
@Test
public void shouldNotReportAnythingForConsistentlyChangedRecord() throws Exception
{
// given
RelationshipTypeTokenRecord oldRecord = notInUse( new RelationshipTypeTokenRecord( 42 ) );
RelationshipTypeTokenRecord newRecord = inUse( new RelationshipTypeTokenRecord( 42 ) );
DynamicRecord name = addRelationshipTypeName( inUse( new DynamicRecord( 6 ) ) );
name.setData( new byte[1] );
newRecord.setNameId( (int) name.getId() );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = checkChange( oldRecord, newRecord );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportProblemsWithTheNewStateWhenCheckingChanges() throws Exception
{
// given
RelationshipTypeTokenRecord oldRecord = notInUse( new RelationshipTypeTokenRecord( 42 ) );
RelationshipTypeTokenRecord newRecord = inUse( new RelationshipTypeTokenRecord( 42 ) );
DynamicRecord name = addRelationshipTypeName( notInUse( new DynamicRecord( 6 ) ) );
newRecord.setNameId( (int) name.getId() );
// when
ConsistencyReport.RelationshipTypeConsistencyReport report = checkChange( oldRecord, newRecord );
// then
verify( report ).nameBlockNotInUse( name );
verifyNoMoreInteractions( report );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RelationshipTypeTokenRecordCheckTest.java
|
4,074
|
class RelationshipTypeTokenRecordCheck
extends TokenRecordCheck<RelationshipTypeTokenRecord,ConsistencyReport.RelationshipTypeConsistencyReport>
{
@Override
protected RecordReference<DynamicRecord> name( RecordAccess records, int id )
{
return records.relationshipTypeName( id );
}
@Override
void nameNotInUse( ConsistencyReport.RelationshipTypeConsistencyReport report, DynamicRecord name )
{
report.nameBlockNotInUse( name );
}
@Override
void emptyName( ConsistencyReport.RelationshipTypeConsistencyReport report, DynamicRecord name )
{
report.emptyName( name );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipTypeTokenRecordCheck.java
|
4,075
|
public class RelationshipRecordCheckTest extends
RecordCheckTestBase<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport, RelationshipRecordCheck>
{
public RelationshipRecordCheckTest()
{
super( new RelationshipRecordCheck(), ConsistencyReport.RelationshipConsistencyReport.class );
}
@Test
public void shouldNotReportAnythingForRelationshipNotInUse() throws Exception
{
// given
RelationshipRecord relationship = notInUse( new RelationshipRecord( 42, 0, 0, 0 ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingForRelationshipThatDoesNotReferenceOtherRecords() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingForRelationshipWithConsistentReferences() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, relationship.getId(), NONE ) ) );
add( inUse( new NodeRecord( 2, 53, NONE ) ) );
add( inUse( new NodeRecord( 3, NONE, NONE ) ) );
add( inUse( new PropertyRecord( 101 ) ) );
relationship.setNextProp( 101 );
RelationshipRecord sNext = add( inUse( new RelationshipRecord( 51, 1, 3, 4 ) ) );
RelationshipRecord tNext = add( inUse( new RelationshipRecord( 52, 2, 3, 4 ) ) );
RelationshipRecord tPrev = add( inUse( new RelationshipRecord( 53, 3, 2, 4 ) ) );
relationship.setFirstNextRel( sNext.getId() );
sNext.setFirstPrevRel( relationship.getId() );
relationship.setSecondNextRel( tNext.getId() );
tNext.setFirstPrevRel( relationship.getId() );
relationship.setSecondPrevRel( tPrev.getId() );
tPrev.setSecondNextRel( relationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportIllegalRelationshipType() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, NONE ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).illegalRelationshipType();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportRelationshipTypeNotInUse() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
RelationshipTypeTokenRecord relationshipType = add( notInUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).relationshipTypeNotInUse( relationshipType );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportIllegalSourceNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, NONE, 1, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).illegalSourceNode();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNodeNotInUse() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
NodeRecord node = add( notInUse( new NodeRecord( 1, NONE, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNodeNotInUse( node );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportIllegalTargetNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, NONE, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).illegalTargetNode();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNodeNotInUse() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
NodeRecord node = add( notInUse( new NodeRecord( 2, NONE, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNodeNotInUse( node );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotInUse() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
relationship.setNextProp( 11 );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
PropertyRecord property = add( notInUse( new PropertyRecord( 11 ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).propertyNotInUse( property );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotFirstInChain() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
relationship.setNextProp( 11 );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
PropertyRecord property = add( inUse( new PropertyRecord( 11 ) ) );
property.setPrevProp( 6 );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).propertyNotFirstInChain( property );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNodeNotReferencingBackForFirstRelationshipInSourceChain() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
NodeRecord source = add( inUse( new NodeRecord( 1, 7, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNodeDoesNotReferenceBack( source );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNodeNotReferencingBackForFirstRelationshipInTargetChain() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
NodeRecord target = add( inUse( new NodeRecord( 2, 7, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNodeDoesNotReferenceBack( target );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceAndTargetNodeNotReferencingBackForFirstRelationshipInChains() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
NodeRecord source = add( inUse( new NodeRecord( 1, NONE, NONE ) ) );
NodeRecord target = add( inUse( new NodeRecord( 2, NONE, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNodeDoesNotReferenceBack( source );
verify( report ).targetNodeDoesNotReferenceBack( target );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNodeWithoutChainForRelationshipInTheMiddleOfChain() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
NodeRecord source = add( inUse( new NodeRecord( 1, NONE, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sPrev = add( inUse( new RelationshipRecord( 51, 1, 0, 0 ) ) );
relationship.setFirstPrevRel( sPrev.getId() );
sPrev.setFirstNextRel( relationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNodeHasNoRelationships( source );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNodeWithoutChainForRelationshipInTheMiddleOfChain() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
NodeRecord target = add( inUse( new NodeRecord( 2, NONE, NONE ) ) );
RelationshipRecord tPrev = add( inUse( new RelationshipRecord( 51, 0, 2, 0 ) ) );
relationship.setSecondPrevRel( tPrev.getId() );
tPrev.setSecondNextRel( relationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNodeHasNoRelationships( target );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourcePrevReferencingOtherNodes() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 0, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sPrev = add( inUse( new RelationshipRecord( 51, 8, 9, 0 ) ) );
relationship.setFirstPrevRel( sPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourcePrevReferencesOtherNodes( sPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetPrevReferencingOtherNodes() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 0, NONE ) ) );
RelationshipRecord tPrev = add( inUse( new RelationshipRecord( 51, 8, 9, 0 ) ) );
relationship.setSecondPrevRel( tPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetPrevReferencesOtherNodes( tPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNextReferencingOtherNodes() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sNext = add( inUse( new RelationshipRecord( 51, 8, 9, 0 ) ) );
relationship.setFirstNextRel( sNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNextReferencesOtherNodes( sNext );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNextReferencingOtherNodes() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord tNext = add( inUse( new RelationshipRecord( 51, 8, 9, 0 ) ) );
relationship.setSecondNextRel( tNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNextReferencesOtherNodes( tNext );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourcePrevReferencingOtherNodesWhenReferencingTargetNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 0, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sPrev = add( inUse( new RelationshipRecord( 51, 2, 0, 0 ) ) );
relationship.setFirstPrevRel( sPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourcePrevReferencesOtherNodes( sPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetPrevReferencingOtherNodesWhenReferencingSourceNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 0, NONE ) ) );
RelationshipRecord tPrev = add( inUse( new RelationshipRecord( 51, 1, 0, 0 ) ) );
relationship.setSecondPrevRel( tPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetPrevReferencesOtherNodes( tPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNextReferencingOtherNodesWhenReferencingTargetNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sNext = add( inUse( new RelationshipRecord( 51, 2, 0, 0 ) ) );
relationship.setFirstNextRel( sNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNextReferencesOtherNodes( sNext );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNextReferencingOtherNodesWhenReferencingSourceNode() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord tNext = add( inUse( new RelationshipRecord( 51, 1, 0, 0 ) ) );
relationship.setSecondNextRel( tNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNextReferencesOtherNodes( tNext );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourcePrevNotReferencingBack() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 0, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sPrev = add( inUse( new RelationshipRecord( 51, 1, 3, 0 ) ) );
relationship.setFirstPrevRel( sPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourcePrevDoesNotReferenceBack( sPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetPrevNotReferencingBack() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 0, NONE ) ) );
RelationshipRecord tPrev = add( inUse( new RelationshipRecord( 51, 2, 3, 0 ) ) );
relationship.setSecondPrevRel( tPrev.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetPrevDoesNotReferenceBack( tPrev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNextNotReferencingBack() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord sNext = add( inUse( new RelationshipRecord( 51, 3, 1, 0 ) ) );
relationship.setFirstNextRel( sNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).sourceNextDoesNotReferenceBack( sNext );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNextNotReferencingBack() throws Exception
{
// given
RelationshipRecord relationship = inUse( new RelationshipRecord( 42, 1, 2, 4 ) );
add( inUse( new RelationshipTypeTokenRecord( 4 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord tNext = add( inUse( new RelationshipRecord( 51, 3, 2, 0 ) ) );
relationship.setSecondNextRel( tNext.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = check( relationship );
// then
verify( report ).targetNextDoesNotReferenceBack( tNext );
verifyNoMoreInteractions( report );
}
// change checking
@Test
public void shouldNotReportAnythingForConsistentlyChangedRelationship() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setNextProp( 1 );
oldRelationship.setFirstNextRel( 101 );
oldRelationship.setFirstPrevRel( 102 );
oldRelationship.setSecondNextRel( 103 );
oldRelationship.setSecondPrevRel( 104 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setNextProp( 2 );
newRelationship.setFirstNextRel( 201 );
newRelationship.setFirstPrevRel( 202 );
newRelationship.setSecondNextRel( 203 );
newRelationship.setSecondPrevRel( 204 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( inUse( new PropertyRecord( 1 ) ),
inUse( new PropertyRecord( 1 ) ) );
addChange( inUse( new RelationshipRecord( 101, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 101, 0, 0, 0 ) ) );
addChange( inUse( new RelationshipRecord( 102, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 102, 0, 0, 0 ) ) );
addChange( inUse( new RelationshipRecord( 103, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 103, 0, 0, 0 ) ) );
addChange( inUse( new RelationshipRecord( 104, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 104, 0, 0, 0 ) ) );
addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ) );
addChange( notInUse( new RelationshipRecord( 201, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 201, 11, 0, 0 ) ) ).setFirstPrevRel( 42 );
addChange( notInUse( new RelationshipRecord( 202, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 202, 0, 11, 0 ) ) ).setSecondNextRel( 42 );
addChange( notInUse( new RelationshipRecord( 203, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 203, 0, 12, 0 ) ) ).setSecondPrevRel( 42 );
addChange( notInUse( new RelationshipRecord( 204, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 204, 12, 0, 0 ) ) ).setFirstNextRel( 42 );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportProblemsWithTheNewStateWhenCheckingChanges() throws Exception
{
// given
RelationshipRecord oldRelationship = notInUse( new RelationshipRecord( 42, 0, 0, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
NodeRecord source = add( notInUse( new NodeRecord( 1, 0, 0 ) ) );
NodeRecord target = add( notInUse( new NodeRecord( 2, 0, 0 ) ) );
RelationshipTypeTokenRecord label = add( notInUse( new RelationshipTypeTokenRecord( 0 ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourceNodeNotInUse( source );
verify( report ).targetNodeNotInUse( target );
verify( report ).relationshipTypeNotInUse( label );
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingAnInitialProperty() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
newRelationship.setNextProp( addChange( notInUse( new PropertyRecord( 10 ) ),
inUse( new PropertyRecord( 10 ) ) ).getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingProperty() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
PropertyRecord oldProp = addChange( inUse( new PropertyRecord( 10 ) ),
inUse( new PropertyRecord( 10 ) ) );
PropertyRecord newProp = addChange( notInUse( new PropertyRecord( 11 ) ),
inUse( new PropertyRecord( 11 ) ) );
oldProp.setPrevProp( newProp.getId() );
newProp.setNextProp( oldProp.getId() );
oldRelationship.setNextProp( oldProp.getId() );
newRelationship.setNextProp( newProp.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingPrevSourceRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
addChange( inUse( new NodeRecord( 1, 42, NONE ) ),
inUse( new NodeRecord( 1, 10, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord prev = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 1, 3, 0 ) ) );
newRelationship.setFirstPrevRel( prev.getId() );
prev.setFirstNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingPrevTargetRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
addChange( inUse( new NodeRecord( 2, 42, NONE ) ),
inUse( new NodeRecord( 2, 10, NONE ) ) );
RelationshipRecord prev = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 3, 2, 0 ) ) );
newRelationship.setSecondPrevRel( prev.getId() );
prev.setSecondNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingNextSourceRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord next = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 1, 3, 0 ) ) );
newRelationship.setFirstNextRel( next.getId() );
next.setFirstPrevRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingNextTargetRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord next = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 3, 2, 0 ) ) );
newRelationship.setSecondNextRel( next.getId() );
next.setSecondPrevRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingPrevSourceRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord oldPrev = inUse( new RelationshipRecord( 10, 1, 3, 0 ) );
addChange( oldPrev, inUse( new RelationshipRecord( 10, 1, 3, 0 ) ) );
RelationshipRecord newPrev = addChange( notInUse( new RelationshipRecord( 11, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 11, 1, 3, 0 ) ) );
oldRelationship.setFirstPrevRel( oldPrev.getId() );
oldPrev.setFirstNextRel( oldRelationship.getId() );
newRelationship.setFirstPrevRel( newPrev.getId() );
newPrev.setFirstNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingNextSourceRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord oldNext = inUse( new RelationshipRecord( 10, 1, 3, 0 ) );
addChange( oldNext, inUse( new RelationshipRecord( 10, 1, 3, 0 ) ) );
RelationshipRecord newNext = addChange( notInUse( new RelationshipRecord( 11, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 11, 1, 3, 0 ) ) );
oldRelationship.setFirstNextRel( oldNext.getId() );
oldNext.setFirstPrevRel( oldRelationship.getId() );
newRelationship.setFirstNextRel( newNext.getId() );
newNext.setFirstPrevRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingPrevTargetRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord oldPrev = inUse( new RelationshipRecord( 10, 3, 2, 0 ) );
addChange( oldPrev, inUse( new RelationshipRecord( 10, 3, 2, 0 ) ) );
RelationshipRecord newPrev = addChange( notInUse( new RelationshipRecord( 11, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 11, 3, 2, 0 ) ) );
oldRelationship.setSecondPrevRel( oldPrev.getId() );
oldPrev.setSecondNextRel( oldRelationship.getId() );
newRelationship.setSecondPrevRel( newPrev.getId() );
newPrev.setSecondNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingNextTargetRelationship() throws Exception
{
// given
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord oldNext = inUse( new RelationshipRecord( 10, 3, 2, 0 ) );
addChange( oldNext, inUse( new RelationshipRecord( 10, 3, 2, 0 ) ) );
RelationshipRecord newNext = addChange( notInUse( new RelationshipRecord( 11, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 11, 3, 2, 0 ) ) );
oldRelationship.setSecondNextRel( oldNext.getId() );
oldNext.setSecondPrevRel( oldRelationship.getId() );
newRelationship.setSecondNextRel( newNext.getId() );
newNext.setSecondPrevRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChainReplacedButNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setNextProp( 1 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
newRelationship.setNextProp( 2 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).propertyNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourcePreviousReplacedButNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setFirstPrevRel( 101 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
newRelationship.setFirstPrevRel( 201 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( notInUse( new RelationshipRecord( 201, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 201, 0, 11, 0 ) ) ).setSecondNextRel( 42 );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourcePrevNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourceNextReplacedButNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setFirstNextRel( 101 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
newRelationship.setFirstNextRel( 201 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( notInUse( new RelationshipRecord( 201, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 201, 0, 11, 0 ) ) ).setSecondPrevRel( 42 );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourceNextNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetPreviousReplacedButNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setSecondPrevRel( 101 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
newRelationship.setSecondPrevRel( 201 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( notInUse( new RelationshipRecord( 201, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 201, 12, 0, 0 ) ) ).setFirstNextRel( 42 );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).targetPrevNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetNextReplacedButNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setSecondNextRel( 101 );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
newRelationship.setSecondNextRel( 201 );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
addChange( notInUse( new RelationshipRecord( 201, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 201, 12, 0, 0 ) ) ).setFirstPrevRel( 42 );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).targetNextNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportDeletedButReferencesNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
oldRelationship.setFirstPrevRel( add( inUse( new RelationshipRecord( 101, 11, 12, 0 ) ) ).getId() );
oldRelationship.setFirstNextRel( add( inUse( new RelationshipRecord( 102, 11, 12, 0 ) ) ).getId() );
oldRelationship.setSecondPrevRel( add( inUse( new RelationshipRecord( 103, 11, 12, 0 ) ) ).getId() );
oldRelationship.setSecondNextRel( add( inUse( new RelationshipRecord( 104, 11, 12, 0 ) ) ).getId() );
oldRelationship.setNextProp( add( inUse( new PropertyRecord( 201 ) ) ).getId() );
RelationshipRecord newRelationship = notInUse( new RelationshipRecord( 42, 0, 0, 0 ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourcePrevNotUpdated();
verify( report ).sourceNextNotUpdated();
verify( report ).targetPrevNotUpdated();
verify( report ).targetNextNotUpdated();
verify( report ).propertyNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportSourcePrevAddedButNodeNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord prev = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 1, 3, 0 ) ) );
newRelationship.setFirstPrevRel( prev.getId() );
prev.setFirstNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourceNodeNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportTargetPrevAddedButNodeNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
RelationshipRecord newRelationship = inUse( new RelationshipRecord( 42, 1, 2, 0 ) );
add( inUse( new RelationshipTypeTokenRecord( 0 ) ) );
add( inUse( new NodeRecord( 1, 42, NONE ) ) );
add( inUse( new NodeRecord( 2, 42, NONE ) ) );
RelationshipRecord prev = addChange( notInUse( new RelationshipRecord( 10, 0, 0, 0 ) ),
inUse( new RelationshipRecord( 10, 3, 2, 0 ) ) );
newRelationship.setSecondPrevRel( prev.getId() );
prev.setSecondNextRel( newRelationship.getId() );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).targetNodeNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportDeletedFirstButReferencedNodesNotUpdated() throws Exception
{
// given
RelationshipRecord oldRelationship = inUse( new RelationshipRecord( 42, 11, 12, 0 ) );
RelationshipRecord newRelationship = notInUse( new RelationshipRecord( 42, 0, 0, 0 ) );
add( inUse( new NodeRecord( 11, 42, NONE ) ) );
add( inUse( new NodeRecord( 12, 42, NONE ) ) );
// when
ConsistencyReport.RelationshipConsistencyReport report = checkChange( oldRelationship, newRelationship );
// then
verify( report ).sourceNodeNotUpdated();
verify( report ).targetNodeNotUpdated();
verifyNoMoreInteractions( report );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RelationshipRecordCheckTest.java
|
4,076
|
TARGET_NEXT( NodeField.TARGET, Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getSecondNextRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.prev( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.targetNextReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.targetNextDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.targetNextNotUpdated();
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipRecordCheck.java
|
4,077
|
TARGET_PREV( NodeField.TARGET, Record.NO_PREV_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getSecondPrevRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.next( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.targetPrevReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.targetPrevDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.targetPrevNotUpdated();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipRecordCheck.java
|
4,078
|
SOURCE_NEXT( NodeField.SOURCE, Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getFirstNextRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.prev( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.sourceNextReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.sourceNextDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.sourceNextNotUpdated();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipRecordCheck.java
|
4,079
|
SOURCE_PREV( NodeField.SOURCE, Record.NO_PREV_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getFirstPrevRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.next( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.sourcePrevReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.sourcePrevDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.sourcePrevNotUpdated();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipRecordCheck.java
|
4,080
|
class RelationshipRecordCheck
extends PrimitiveRecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport>
{
RelationshipRecordCheck()
{
super( RelationshipTypeField.RELATIONSHIP_TYPE,
NodeField.SOURCE, RelationshipField.SOURCE_PREV, RelationshipField.SOURCE_NEXT,
NodeField.TARGET, RelationshipField.TARGET_PREV, RelationshipField.TARGET_NEXT );
}
private enum RelationshipTypeField implements
RecordField<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport>,
ComparativeRecordChecker<RelationshipRecord, RelationshipTypeTokenRecord, ConsistencyReport.RelationshipConsistencyReport>
{
RELATIONSHIP_TYPE;
@Override
public void checkConsistency( RelationshipRecord record,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
if ( record.getType() < 0 )
{
engine.report().illegalRelationshipType();
}
else
{
engine.comparativeCheck( records.relationshipType( record.getType() ), this );
}
}
@Override
public long valueFrom( RelationshipRecord record )
{
return record.getType();
}
@Override
public void checkChange( RelationshipRecord oldRecord, RelationshipRecord newRecord,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
DiffRecordAccess records )
{
// nothing to check
}
@Override
public void checkReference( RelationshipRecord record, RelationshipTypeTokenRecord referred,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
if ( !referred.inUse() )
{
engine.report().relationshipTypeNotInUse( referred );
}
}
}
private enum RelationshipField implements
RecordField<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport>,
ComparativeRecordChecker<RelationshipRecord, RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport>
{
SOURCE_PREV( NodeField.SOURCE, Record.NO_PREV_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getFirstPrevRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.next( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.sourcePrevReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.sourcePrevDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.sourcePrevNotUpdated();
}
},
SOURCE_NEXT( NodeField.SOURCE, Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getFirstNextRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.prev( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.sourceNextReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.sourceNextDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.sourceNextNotUpdated();
}
},
TARGET_PREV( NodeField.TARGET, Record.NO_PREV_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getSecondPrevRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.next( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.targetPrevReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.targetPrevDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.targetPrevNotUpdated();
}
},
TARGET_NEXT( NodeField.TARGET, Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long valueFrom( RelationshipRecord relationship )
{
return relationship.getSecondNextRel();
}
@Override
long other( NodeField field, RelationshipRecord relationship )
{
return field.prev( relationship );
}
@Override
void otherNode( ConsistencyReport.RelationshipConsistencyReport report, RelationshipRecord relationship )
{
report.targetNextReferencesOtherNodes( relationship );
}
@Override
void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship )
{
report.targetNextDoesNotReferenceBack( relationship );
}
@Override
void notUpdated( ConsistencyReport.RelationshipConsistencyReport report )
{
report.targetNextNotUpdated();
}
};
private final NodeField NODE;
private final Record NONE;
private RelationshipField( NodeField node, Record none )
{
this.NODE = node;
this.NONE = none;
}
@Override
public void checkConsistency( RelationshipRecord relationship,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
if ( !NONE.is( valueFrom( relationship ) ) )
{
engine.comparativeCheck( records.relationship( valueFrom( relationship ) ), this );
}
}
@Override
public void checkReference( RelationshipRecord record, RelationshipRecord referred,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
NodeField field = NodeField.select( referred, node( record ) );
if ( field == null )
{
otherNode( engine.report(), referred );
}
else
{
if ( other( field, referred ) != record.getId() )
{
noBackReference( engine.report(), referred );
}
}
}
@Override
public void checkChange( RelationshipRecord oldRecord, RelationshipRecord newRecord,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
DiffRecordAccess records )
{
if ( !newRecord.inUse() || valueFrom( oldRecord ) != valueFrom( newRecord ) )
{
if ( !NONE.is( valueFrom( oldRecord ) )
&& records.changedRelationship( valueFrom( oldRecord ) ) == null )
{
notUpdated( engine.report() );
}
}
}
abstract void notUpdated( ConsistencyReport.RelationshipConsistencyReport report );
abstract long other( NodeField field, RelationshipRecord relationship );
abstract void otherNode( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship );
abstract void noBackReference( ConsistencyReport.RelationshipConsistencyReport report,
RelationshipRecord relationship );
private long node( RelationshipRecord relationship )
{
return NODE.valueFrom( relationship );
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_RelationshipRecordCheck.java
|
4,081
|
{
@Override
public void check( RelationshipTypeTokenRecord record,
CheckerEngine<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( RelationshipTypeTokenRecord oldRecord, RelationshipTypeTokenRecord newRecord,
CheckerEngine<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,082
|
{
@Override
public void check( PropertyKeyTokenRecord record,
CheckerEngine<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( PropertyKeyTokenRecord oldRecord, PropertyKeyTokenRecord newRecord,
CheckerEngine<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,083
|
{
@Override
public void check( DynamicRecord record,
CheckerEngine<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( DynamicRecord oldRecord, DynamicRecord newRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,084
|
{
@Override
public void check( NeoStoreRecord record,
CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( NeoStoreRecord oldRecord, NeoStoreRecord newRecord,
CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,085
|
{
@Override
public void check( PropertyRecord record,
CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( PropertyRecord oldRecord, PropertyRecord newRecord,
CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,086
|
{
@Override
public void check( RelationshipRecord record,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( RelationshipRecord oldRecord, RelationshipRecord newRecord,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,087
|
{
@Override
public void check( NodeRecord record,
CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( NodeRecord oldRecord, NodeRecord newRecord,
CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,088
|
public abstract class RecordCheckTestBase<RECORD extends AbstractBaseRecord,
REPORT extends ConsistencyReport,
CHECKER extends RecordCheck<RECORD, REPORT>>
{
public static final int NONE = -1;
private final CHECKER checker;
private final Class<REPORT> reportClass;
protected final RecordAccessStub records = new RecordAccessStub();
RecordCheckTestBase( CHECKER checker, Class<REPORT> reportClass )
{
this.checker = checker;
this.reportClass = reportClass;
}
public static PrimitiveRecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> dummyNodeCheck()
{
return new NodeRecordCheck()
{
@Override
public void check( NodeRecord record,
CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( NodeRecord oldRecord, NodeRecord newRecord,
CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static PrimitiveRecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> dummyRelationshipChecker()
{
return new RelationshipRecordCheck()
{
@Override
public void check( RelationshipRecord record,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( RelationshipRecord oldRecord, RelationshipRecord newRecord,
CheckerEngine<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> dummyPropertyChecker()
{
return new RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport>()
{
@Override
public void check( PropertyRecord record,
CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( PropertyRecord oldRecord, PropertyRecord newRecord,
CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static PrimitiveRecordCheck<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> dummyNeoStoreCheck()
{
return new NeoStoreCheck()
{
@Override
public void check( NeoStoreRecord record,
CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( NeoStoreRecord oldRecord, NeoStoreRecord newRecord,
CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static RecordCheck<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> dummyDynamicCheck(
RecordStore<DynamicRecord> store, DynamicStore dereference )
{
return new DynamicRecordCheck(store, dereference )
{
@Override
public void check( DynamicRecord record,
CheckerEngine<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( DynamicRecord oldRecord, DynamicRecord newRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static RecordCheck<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> dummyPropertyKeyCheck()
{
return new PropertyKeyTokenRecordCheck()
{
@Override
public void check( PropertyKeyTokenRecord record,
CheckerEngine<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( PropertyKeyTokenRecord oldRecord, PropertyKeyTokenRecord newRecord,
CheckerEngine<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
public static RecordCheck<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> dummyRelationshipLabelCheck()
{
return new RelationshipTypeTokenRecordCheck()
{
@Override
public void check( RelationshipTypeTokenRecord record,
CheckerEngine<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> engine,
RecordAccess records )
{
}
@Override
public void checkChange( RelationshipTypeTokenRecord oldRecord, RelationshipTypeTokenRecord newRecord,
CheckerEngine<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> engine,
DiffRecordAccess records )
{
}
};
}
final REPORT check( RECORD record )
{
return check( reportClass, checker, record, records );
}
final REPORT check( CHECKER externalChecker, RECORD record )
{
return check( reportClass, externalChecker, record, records );
}
final REPORT checkChange( RECORD oldRecord, RECORD newRecord )
{
return checkChange( reportClass, checker, oldRecord, newRecord, records );
}
public static <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
REPORT check( Class<REPORT> reportClass, RecordCheck<RECORD, REPORT> checker, RECORD record,
final RecordAccessStub records )
{
REPORT report = mock( reportClass );
checker.check( record, records.engine( record, report ), records );
records.checkDeferred();
return report;
}
static <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
REPORT checkChange( Class<REPORT> reportClass, RecordCheck<RECORD, REPORT> checker,
RECORD oldRecord, RECORD newRecord, final RecordAccessStub records )
{
REPORT report = mock( reportClass );
checker.checkChange( oldRecord, newRecord, records.engine( oldRecord, newRecord, report ), records );
records.checkDeferred();
return report;
}
<R extends AbstractBaseRecord> R addChange( R oldRecord, R newRecord )
{
return records.addChange( oldRecord, newRecord );
}
<R extends AbstractBaseRecord> R add( R record )
{
return records.add( record );
}
DynamicRecord addNodeDynamicLabels( DynamicRecord labels )
{
return records.addNodeDynamicLabels( labels );
}
DynamicRecord addKeyName( DynamicRecord name )
{
return records.addPropertyKeyName( name );
}
DynamicRecord addRelationshipTypeName(DynamicRecord name )
{
return records.addRelationshipTypeName( name );
}
DynamicRecord addLabelName( DynamicRecord name )
{
return records.addLabelName( name );
}
public static DynamicRecord string( DynamicRecord record )
{
record.setType( PropertyType.STRING.intValue() );
return record;
}
public static DynamicRecord array( DynamicRecord record )
{
record.setType( PropertyType.ARRAY.intValue() );
return record;
}
static PropertyBlock propertyBlock( PropertyKeyTokenRecord key, DynamicRecord value )
{
PropertyType type;
if ( value.getType() == PropertyType.STRING.intValue() )
{
type = PropertyType.STRING;
}
else if ( value.getType() == PropertyType.ARRAY.intValue() )
{
type = PropertyType.ARRAY;
}
else
{
fail( "Dynamic record must be either STRING or ARRAY" );
return null;
}
return propertyBlock( key, type, value.getId() );
}
public static PropertyBlock propertyBlock( PropertyKeyTokenRecord key, PropertyType type, long value )
{
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( key.getId() | (((long) type.intValue()) << 24) | (value << 28) );
return block;
}
public static <R extends AbstractBaseRecord> R inUse( R record )
{
record.setInUse( true );
return record;
}
public static <R extends AbstractBaseRecord> R notInUse( R record )
{
record.setInUse( false );
return record;
}
protected CHECKER checker()
{
return checker;
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_RecordCheckTestBase.java
|
4,089
|
public class PropertyRecordCheckTest
extends RecordCheckTestBase<PropertyRecord, ConsistencyReport.PropertyConsistencyReport, PropertyRecordCheck>
{
public PropertyRecordCheckTest()
{
super( new PropertyRecordCheck(), ConsistencyReport.PropertyConsistencyReport.class );
}
@Test
public void shouldNotReportAnythingForPropertyRecordNotInUse() throws Exception
{
// given
PropertyRecord property = notInUse( new PropertyRecord( 42 ) );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingForPropertyWithoutBlocksThatDoesNotReferenceAnyOtherRecords() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyKeyNotInUse() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyKeyTokenRecord key = add( notInUse( new PropertyKeyTokenRecord( 0 ) ) );
PropertyBlock block = propertyBlock( key, PropertyType.INT, 0 );
property.addPropertyBlock( block );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).keyNotInUse( block, key );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPreviousPropertyNotInUse() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyRecord prev = add( notInUse( new PropertyRecord( 51 ) ) );
property.setPrevProp( prev.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).prevNotInUse( prev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportNextPropertyNotInUse() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyRecord next = add( notInUse( new PropertyRecord( 51 ) ) );
property.setNextProp( next.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).nextNotInUse( next );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPreviousPropertyNotReferringBack() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyRecord prev = add( inUse( new PropertyRecord( 51 ) ) );
property.setPrevProp( prev.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).previousDoesNotReferenceBack( prev );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportNextPropertyNotReferringBack() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyRecord next = add( inUse( new PropertyRecord( 51 ) ) );
property.setNextProp( next.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).nextDoesNotReferenceBack( next );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportStringRecordNotInUse() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyKeyTokenRecord key = add( inUse( new PropertyKeyTokenRecord( 6 ) ) );
DynamicRecord value = add( notInUse( string( new DynamicRecord( 1001 ) ) ) );
PropertyBlock block = propertyBlock( key, value );
property.addPropertyBlock( block );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).stringNotInUse( block, value );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportArrayRecordNotInUse() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyKeyTokenRecord key = add( inUse( new PropertyKeyTokenRecord( 6 ) ) );
DynamicRecord value = add( notInUse( array( new DynamicRecord( 1001 ) ) ) );
PropertyBlock block = propertyBlock( key, value );
property.addPropertyBlock( block );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).arrayNotInUse( block, value );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportEmptyStringRecord() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyKeyTokenRecord key = add( inUse( new PropertyKeyTokenRecord( 6 ) ) );
DynamicRecord value = add( inUse( string( new DynamicRecord( 1001 ) ) ) );
PropertyBlock block = propertyBlock( key, value );
property.addPropertyBlock( block );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).stringEmpty( block, value );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportEmptyArrayRecord() throws Exception
{
// given
PropertyRecord property = inUse( new PropertyRecord( 42 ) );
PropertyKeyTokenRecord key = add( inUse( new PropertyKeyTokenRecord( 6 ) ) );
DynamicRecord value = add( inUse( array( new DynamicRecord( 1001 ) ) ) );
PropertyBlock block = propertyBlock( key, value );
property.addPropertyBlock( block );
// when
ConsistencyReport.PropertyConsistencyReport report = check( property );
// then
verify( report ).arrayEmpty( block, value );
verifyNoMoreInteractions( report );
}
// change checking
@Test
public void shouldNotReportAnythingForConsistentlyChangedProperty() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
oldProperty.setPrevProp( 1 );
oldProperty.setNextProp( 2 );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setPrevProp( 11 );
newProperty.setNextProp( 12 );
newProperty.setNodeId( addChange( inUse( new NodeRecord( 100, NONE, 1 ) ),
inUse( new NodeRecord( 100, NONE, 11 ) ) ).getId() );
PropertyRecord oldPrev = inUse( new PropertyRecord( 1 ) );
addChange( oldPrev, notInUse( new PropertyRecord( 1 ) ) );
oldPrev.setNextProp( 42 );
addChange( inUse( new PropertyRecord( 2 ) ),
notInUse( new PropertyRecord( 2 ) ) );
addChange( notInUse( new PropertyRecord( 11 ) ),
inUse( new PropertyRecord( 11 ) ) ).setNextProp( 42 );
addChange( notInUse( new PropertyRecord( 12 ) ),
inUse( new PropertyRecord( 12 ) ) ).setPrevProp( 42 );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportProblemsWithTheNewStateWhenCheckingChanges() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setNodeId( add( notInUse( new NodeRecord( 10, 0, 0 ) ) ).getId() );
newProperty.setPrevProp( 1 );
newProperty.setNextProp( 2 );
PropertyRecord prev = add( notInUse( new PropertyRecord( 1 ) ) );
PropertyRecord next = add( notInUse( new PropertyRecord( 2 ) ) );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).prevNotInUse( prev );
verify( report ).nextNotInUse( next );
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingAnInitialNextProperty() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord nextProperty = addChange( notInUse( new PropertyRecord( 1 ) ),
inUse( new PropertyRecord( 1 ) ) );
nextProperty.setPrevProp( 42 );
newProperty.setNextProp( nextProperty.getId() );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, newProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenAddingAnInitialPrevProperty() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord prevProperty = addChange( notInUse( new PropertyRecord( 1 ) ),
inUse( new PropertyRecord( 1 ) ) );
prevProperty.setNextProp( 42 );
newProperty.setPrevProp( prevProperty.getId() );
newProperty.setNodeId( addChange( inUse( new NodeRecord( 100, NONE, oldProperty.getId() ) ),
inUse( new NodeRecord( 100, NONE, prevProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingNextProperty() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord oldNext = inUse( new PropertyRecord( 1 ) );
addChange( oldNext, inUse( new PropertyRecord( 1 ) ) );
PropertyRecord newNext = addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ));
oldProperty.setNextProp( oldNext.getId() );
oldNext.setPrevProp( 42 );
newProperty.setNextProp( newNext.getId() );
newNext.setPrevProp( newProperty.getId() );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, newProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldNotReportAnythingWhenChangingPrevProperty() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord oldPrev = inUse( new PropertyRecord( 1 ) );
addChange( oldPrev, inUse( new PropertyRecord( 1 ) ) );
PropertyRecord newPrev = addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ));
oldProperty.setPrevProp( oldPrev.getId() );
oldPrev.setNextProp( 42 );
newProperty.setPrevProp( newPrev.getId() );
newPrev.setNextProp( newProperty.getId() );
newProperty.setNodeId( addChange( inUse( new NodeRecord( 100, NONE, oldPrev.getId() ) ),
inUse( new NodeRecord( 100, NONE, newPrev.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPreviousReplacedButNotUpdated() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
oldProperty.setPrevProp( 1 );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setPrevProp( 2 );
add( inUse( new PropertyRecord( 1 ) ) ).setNextProp( 42 );
addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ) ).setNextProp( 42 );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, 1 ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).prevNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportNextReplacedButNotUpdated() throws Exception
{
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
oldProperty.setNextProp( 1 );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setNextProp( 2 );
addChange( notInUse( new PropertyRecord( 2 ) ),
inUse( new PropertyRecord( 2 ) ) ).setPrevProp( 42 );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, newProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).nextNotUpdated();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportStringValueUnreferencedButStillInUse() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyBlock block = propertyBlock( add( inUse( new PropertyKeyTokenRecord( 1 ) ) ),
add( string( inUse( new DynamicRecord( 100 ) ) ) ) );
oldProperty.addPropertyBlock( block );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, newProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).stringUnreferencedButNotDeleted( block );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportArrayValueUnreferencedButStillInUse() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyBlock block = propertyBlock( add( inUse( new PropertyKeyTokenRecord( 1 ) ) ),
add( array( inUse( new DynamicRecord( 100 ) ) ) ) );
oldProperty.addPropertyBlock( block );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setNodeId( add( inUse( new NodeRecord( 100, NONE, newProperty.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).arrayUnreferencedButNotDeleted( block );
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongNode() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
newProperty.setNodeId( 10 );
add( inUse( new NodeRecord( 10, NONE, NONE ) ) );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongNodeWithChain() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
newProperty.setNodeId( add( inUse( new NodeRecord( 10, NONE, a.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongRelationship() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
newProperty.setRelId( 10 );
add( inUse( new RelationshipRecord( 10, 100, 200, 0 ) ) );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongRelationshipWithChain() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
RelationshipRecord rel = add( inUse( new RelationshipRecord( 1, 10, 20, 0 ) ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
rel.setNextProp( a.getId() );
newProperty.setRelId( rel.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongNeoStore() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
add( inUse( new NeoStoreRecord() ) );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyChangedForWrongNeoStoreWithChain() throws Exception
{
// given
PropertyRecord oldProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
add( inUse( new NeoStoreRecord() ) ).setNextProp( a.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).changedForWrongOwner();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromNode() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setNodeId( add( inUse( new NodeRecord( 1, NONE, NONE ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromNodeWithChain() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
newProperty.setNodeId( add( inUse( new NodeRecord( 1, NONE, a.getId() ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromRelationship() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
newProperty.setRelId( add( inUse( new RelationshipRecord( 1, 10, 20, 0 ) ) ).getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromRelationshipWithChain() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
RelationshipRecord rel = add( inUse( new RelationshipRecord( 1, 10, 20, 0 ) ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
rel.setNextProp( a.getId() );
newProperty.setRelId( rel.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromNeoStore() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
add( inUse( new NeoStoreRecord() ) );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
@Test
public void shouldReportPropertyNotReferencedFromNeoStoreWithChain() throws Exception
{
// given
PropertyRecord oldProperty = notInUse( new PropertyRecord( 42 ) );
PropertyRecord newProperty = inUse( new PropertyRecord( 42 ) );
PropertyRecord a = add( inUse( new PropertyRecord( 1 ) ) );
PropertyRecord b = add( inUse( new PropertyRecord( 2 ) ) );
a.setNextProp( b.getId() );
b.setPrevProp( a.getId() );
add( inUse( new NeoStoreRecord() ) ).setNextProp( a.getId() );
// when
ConsistencyReport.PropertyConsistencyReport report = checkChange( oldProperty, newProperty );
// then
verify( report ).ownerDoesNotReferenceBack();
verifyNoMoreInteractions( report );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_PropertyRecordCheckTest.java
|
4,090
|
NEXT( Record.NO_NEXT_PROPERTY )
{
@Override
public long valueFrom( PropertyRecord record )
{
return record.getNextProp();
}
@Override
long otherReference( PropertyRecord record )
{
return record.getPrevProp();
}
@Override
void notInUse( ConsistencyReport.PropertyConsistencyReport report, PropertyRecord property )
{
report.nextNotInUse( property );
}
@Override
void noBackReference( ConsistencyReport.PropertyConsistencyReport report, PropertyRecord property )
{
report.nextDoesNotReferenceBack( property );
}
@Override
void reportNotUpdated( ConsistencyReport.PropertyConsistencyReport report )
{
report.nextNotUpdated();
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_PropertyRecordCheck.java
|
4,091
|
{
@Override
public void checkReference( DynamicRecord record, LabelTokenRecord labelTokenRecord,
CheckerEngine<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> engine,
RecordAccess records )
{
if ( !labelTokenRecord.inUse() )
{
engine.report().labelNotInUse( labelTokenRecord );
}
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_SchemaRecordCheck.java
|
4,092
|
public class SchemaRecordCheckTest
extends RecordCheckTestBase<DynamicRecord, ConsistencyReport.SchemaConsistencyReport, SchemaRecordCheck>
{
public SchemaRecordCheckTest()
{
super( new SchemaRecordCheck( configureSchemaStore() ),
ConsistencyReport.SchemaConsistencyReport.class );
}
public static SchemaStorage configureSchemaStore()
{
return mock( SchemaStorage.class );
}
@Test
public void shouldReportMalformedSchemaRule() throws Exception
{
// given
DynamicRecord badRecord = inUse( new DynamicRecord( 0 ) );
badRecord.setType( RecordAccessStub.SCHEMA_RECORD_TYPE );
when( checker().ruleAccess.loadSingleSchemaRule( 0 ) ).thenThrow( new MalformedSchemaRuleException( "Bad Record" ) );
// when
ConsistencyReport.SchemaConsistencyReport report = check( badRecord );
// then
verify( report ).malformedSchemaRule();
}
@Test
public void shouldReportInvalidLabelReferences() throws Exception
{
// given
int schemaRuleId = 0;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( schemaRuleId ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule = IndexRule.indexRule( schemaRuleId, labelId, propertyKeyId, providerDescriptor );
when( checker().ruleAccess.loadSingleSchemaRule( schemaRuleId ) ).thenReturn( rule );
LabelTokenRecord labelTokenRecord = add ( notInUse( new LabelTokenRecord( labelId ) ) );
add(inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
ConsistencyReport.SchemaConsistencyReport report = check( record );
// then
verify( report ).labelNotInUse( labelTokenRecord );
}
@Test
public void shouldReportInvalidPropertyReferenceFromIndexRule() throws Exception
{
// given
int schemaRuleId = 0;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( schemaRuleId ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule = IndexRule.indexRule( schemaRuleId, labelId, propertyKeyId, providerDescriptor );
when( checker().ruleAccess.loadSingleSchemaRule( schemaRuleId ) ).thenReturn( rule );
add( inUse( new LabelTokenRecord( labelId ) ) );
PropertyKeyTokenRecord propertyKeyToken = add( notInUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
ConsistencyReport.SchemaConsistencyReport report = check( record );
// then
verify( report ).propertyKeyNotInUse( propertyKeyToken );
}
@Test
public void shouldReportInvalidPropertyReferenceFromUniquenessConstraintRule() throws Exception
{
// given
int schemaRuleId = 0;
int indexRuleId = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( schemaRuleId ) );
UniquenessConstraintRule rule = UniquenessConstraintRule.uniquenessConstraintRule( schemaRuleId, labelId, propertyKeyId, indexRuleId );
when( checker().ruleAccess.loadSingleSchemaRule( schemaRuleId ) ).thenReturn( rule );
add( inUse( new LabelTokenRecord( labelId ) ) );
PropertyKeyTokenRecord propertyKeyToken = add( notInUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
ConsistencyReport.SchemaConsistencyReport report = check( record );
// then
verify( report ).propertyKeyNotInUse( propertyKeyToken );
}
@Test
public void shouldReportUniquenessConstraintNotReferencingBack() throws Exception
{
// given
int ruleId1 = 0;
int ruleId2 = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record1 = inUse( dynamicRecord( ruleId1 ) );
DynamicRecord record2 = inUse( dynamicRecord( ruleId2 ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule1 = IndexRule.constraintIndexRule( ruleId1, labelId, propertyKeyId, providerDescriptor, (long) ruleId2 );
UniquenessConstraintRule rule2 = UniquenessConstraintRule.uniquenessConstraintRule( ruleId2, labelId, propertyKeyId, ruleId2 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId1 ) ).thenReturn( rule1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId2 ) ).thenReturn( rule2 );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record1 );
check( record2 );
SchemaRecordCheck obligationChecker = checker().forObligationChecking();
check( obligationChecker, record1 );
ConsistencyReport.SchemaConsistencyReport report = check( obligationChecker, record2 );
// then
verify( report ).uniquenessConstraintNotReferencingBack( record1 );
}
@Test
public void shouldNotReportConstraintIndexRuleWithoutBackReference() throws Exception
{
// given
int ruleId = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( ruleId ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule = IndexRule.constraintIndexRule( ruleId, labelId, propertyKeyId, providerDescriptor, null );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId ) ).thenReturn( rule );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record );
SchemaRecordCheck obligationChecker = checker().forObligationChecking();
ConsistencyReport.SchemaConsistencyReport report = check( obligationChecker, record );
// then
verifyZeroInteractions( report );
}
@Test
public void shouldReportTwoUniquenessConstraintsReferencingSameIndex() throws Exception
{
// given
int ruleId1 = 0;
int ruleId2 = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record1 = inUse( dynamicRecord( ruleId1 ) );
DynamicRecord record2 = inUse( dynamicRecord( ruleId2 ) );
UniquenessConstraintRule rule1 = UniquenessConstraintRule.uniquenessConstraintRule( ruleId1, labelId, propertyKeyId, ruleId2 );
UniquenessConstraintRule rule2 = UniquenessConstraintRule.uniquenessConstraintRule( ruleId2, labelId, propertyKeyId, ruleId2 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId1 ) ).thenReturn( rule1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId2 ) ).thenReturn( rule2 );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record1 );
ConsistencyReport.SchemaConsistencyReport report = check( record2 );
// then
verify( report ).duplicateObligation( record1 );
}
@Test
public void shouldReportUnreferencedUniquenessConstraint() throws Exception
{
// given
int ruleId = 0;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( ruleId ) );
UniquenessConstraintRule rule = UniquenessConstraintRule.uniquenessConstraintRule( ruleId, labelId, propertyKeyId, ruleId );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId ) ).thenReturn( rule );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record );
SchemaRecordCheck obligationChecker = checker().forObligationChecking();
ConsistencyReport.SchemaConsistencyReport report = check( obligationChecker, record );
// then
verify( report ).missingObligation( SchemaRule.Kind.CONSTRAINT_INDEX_RULE );
}
@Test
public void shouldReportConstraintIndexNotReferencingBack() throws Exception
{
// given
int ruleId1 = 0;
int ruleId2 = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record1 = inUse( dynamicRecord( ruleId1 ) );
DynamicRecord record2 = inUse( dynamicRecord( ruleId2) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule1 = IndexRule.constraintIndexRule( ruleId1, labelId, propertyKeyId, providerDescriptor, (long) ruleId1 );
UniquenessConstraintRule rule2 = UniquenessConstraintRule.uniquenessConstraintRule( ruleId2, labelId, propertyKeyId, ruleId1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId1 ) ).thenReturn( rule1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId2 ) ).thenReturn( rule2 );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record1 );
check( record2 );
SchemaRecordCheck obligationChecker = checker().forObligationChecking();
ConsistencyReport.SchemaConsistencyReport report = check( obligationChecker, record1 );
check( obligationChecker, record2 );
// then
verify( report ).constraintIndexRuleNotReferencingBack( record2 );
}
@Test
public void shouldReportTwoConstraintIndexesReferencingSameConstraint() throws Exception
{
// given
int ruleId1 = 0;
int ruleId2 = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record1 = inUse( dynamicRecord( ruleId1 ) );
DynamicRecord record2 = inUse( dynamicRecord( ruleId2 ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule1 = IndexRule.constraintIndexRule( ruleId1, labelId, propertyKeyId, providerDescriptor, (long) ruleId1 );
IndexRule rule2 = IndexRule.constraintIndexRule( ruleId2, labelId, propertyKeyId, providerDescriptor, (long) ruleId1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId1 ) ).thenReturn( rule1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId2 ) ).thenReturn( rule2 );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record1 );
ConsistencyReport.SchemaConsistencyReport report = check( record2 );
// then
verify( report ).duplicateObligation( record1 );
}
@Test
public void shouldReportUnreferencedConstraintIndex() throws Exception
{
// given
int ruleId = 0;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record = inUse( dynamicRecord( ruleId ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule = IndexRule.constraintIndexRule( ruleId, labelId, propertyKeyId, providerDescriptor, (long) ruleId );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId ) ).thenReturn( rule );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record );
SchemaRecordCheck obligationChecker = checker().forObligationChecking();
ConsistencyReport.SchemaConsistencyReport report = check( obligationChecker, record );
// then
verify( report ).missingObligation( SchemaRule.Kind.UNIQUENESS_CONSTRAINT );
}
@Test
public void shouldReportTwoIndexRulesWithDuplicateContent() throws Exception
{
// given
int ruleId1 = 0;
int ruleId2 = 1;
int labelId = 1;
int propertyKeyId = 2;
DynamicRecord record1 = inUse( dynamicRecord( ruleId1 ) );
DynamicRecord record2 = inUse( dynamicRecord( ruleId2 ) );
SchemaIndexProvider.Descriptor providerDescriptor = new SchemaIndexProvider.Descriptor( "in-memory", "1.0" );
IndexRule rule1 = IndexRule.constraintIndexRule( ruleId1, labelId, propertyKeyId, providerDescriptor, (long) ruleId1 );
IndexRule rule2 = IndexRule.constraintIndexRule( ruleId2, labelId, propertyKeyId, providerDescriptor, (long) ruleId2 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId1 ) ).thenReturn( rule1 );
when( checker().ruleAccess.loadSingleSchemaRule( ruleId2 ) ).thenReturn( rule2 );
add( inUse( new LabelTokenRecord( labelId ) ) );
add( inUse( new PropertyKeyTokenRecord( propertyKeyId ) ) );
// when
check( record1 );
ConsistencyReport.SchemaConsistencyReport report = check( record2 );
// then
verify( report ).duplicateRuleContent( record1 );
}
private DynamicRecord dynamicRecord( long id )
{
DynamicRecord record = new DynamicRecord( id );
record.setType( RecordAccessStub.SCHEMA_RECORD_TYPE );
return record;
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_SchemaRecordCheckTest.java
|
4,093
|
{
@Override
void notUsed( ConsistencyReport.PropertyConsistencyReport report, DynamicRecord value )
{
report.arrayNotInUse( block, value );
}
@Override
void empty( ConsistencyReport.PropertyConsistencyReport report, DynamicRecord value )
{
report.arrayEmpty( block, value );
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_PropertyRecordCheck.java
|
4,094
|
public class SchemaRuleContent
{
private final SchemaRule schemaRule;
public SchemaRuleContent( SchemaRule schemaRule )
{
this.schemaRule = schemaRule;
}
@Override
public String toString()
{
return "ContentOf:" + schemaRule.toString();
}
@Override
public boolean equals( Object obj )
{
if ( this == obj )
{
return true;
}
if ( obj instanceof SchemaRuleContent )
{
SchemaRuleContent that = (SchemaRuleContent) obj;
if ( this.schemaRule.getLabel() != that.schemaRule.getLabel() )
{
return false;
}
switch ( schemaRule.getKind() )
{
case INDEX_RULE:
case CONSTRAINT_INDEX_RULE:
if ( !that.schemaRule.getKind().isIndex() )
{
return false;
}
return indexRulesEquals( (IndexRule) this.schemaRule, (IndexRule) that.schemaRule );
case UNIQUENESS_CONSTRAINT:
return this.schemaRule.getKind() == that.schemaRule.getKind() && uniquenessConstraintEquals(
(UniquenessConstraintRule) this.schemaRule,
(UniquenessConstraintRule) that.schemaRule );
default:
throw new IllegalArgumentException( "Invalid SchemaRule kind: " + schemaRule.getKind() );
}
}
return false;
}
private static boolean indexRulesEquals( IndexRule lhs, IndexRule rhs )
{
return lhs.getPropertyKey() == rhs.getPropertyKey();
}
private static boolean uniquenessConstraintEquals( UniquenessConstraintRule lhs, UniquenessConstraintRule rhs )
{
return lhs.getPropertyKey() == rhs.getPropertyKey();
}
@Override
public int hashCode()
{
return (int) schemaRule.getLabel();
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_SchemaRuleContent.java
|
4,095
|
private static class LoggingChecker<REC extends AbstractBaseRecord, REP extends ConsistencyReport>
implements RecordCheck<REC, REP>
{
private final RecordCheck<REC, REP> checker;
private final InvocationLog log;
LoggingChecker( RecordCheck<REC, REP> checker, InvocationLog log )
{
this.checker = checker;
this.log = log;
}
@Override
public void check( REC record, CheckerEngine<REC, REP> engine, RecordAccess records )
{
checker.check( record, engine, new ComparativeLogging( (DiffRecordAccess) records, log ) );
}
@Override
public void checkChange( REC oldRecord, REC newRecord, CheckerEngine<REC, REP> engine,
DiffRecordAccess records )
{
checker.checkChange( oldRecord, newRecord, engine, new ComparativeLogging( records, log ) );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_full_ExecutionOrderIntegrationTest.java
|
4,096
|
private static class LogDecorator implements CheckDecorator
{
private final InvocationLog log;
LogDecorator( InvocationLog log )
{
this.log = log;
}
<REC extends AbstractBaseRecord, REP extends ConsistencyReport> RecordCheck<REC, REP> logging(
RecordCheck<REC, REP> checker )
{
return new LoggingChecker<>( checker, log );
}
@Override
public RecordCheck<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> decorateNeoStoreChecker(
PrimitiveRecordCheck<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> decorateNodeChecker(
PrimitiveRecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport>
decorateRelationshipChecker(
PrimitiveRecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> decoratePropertyChecker(
RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport>
decoratePropertyKeyTokenChecker(
RecordCheck<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> decorateRelationshipTypeTokenChecker(
RecordCheck<RelationshipTypeTokenRecord, ConsistencyReport.RelationshipTypeConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<LabelTokenRecord, ConsistencyReport.LabelTokenConsistencyReport> decorateLabelTokenChecker(
RecordCheck<LabelTokenRecord, ConsistencyReport.LabelTokenConsistencyReport> checker )
{
return logging( checker );
}
@Override
public RecordCheck<NodeRecord, ConsistencyReport.LabelsMatchReport> decorateLabelMatchChecker(
RecordCheck<NodeRecord, ConsistencyReport.LabelsMatchReport> checker )
{
return logging( checker );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_full_ExecutionOrderIntegrationTest.java
|
4,097
|
private static class InvocationLog
{
private final Map<String, Throwable> data = new HashMap<>();
private final Map<String, Integer> duplicates = new HashMap<>();
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
void log( PendingReferenceCheck check, InvocationOnMock invocation )
{
Method method = invocation.getMethod();
if ( Object.class == method.getDeclaringClass() && "finalize".equals( method.getName() ) )
{
/* skip invocations to finalize - they are not of interest to us,
* and GC is not predictable enough to reliably trace this. */
return;
}
StringBuilder entry = new StringBuilder( method.getName() ).append( '(' );
entry.append( check );
for ( Object arg : invocation.getArguments() )
{
if ( arg instanceof AbstractBaseRecord )
{
AbstractBaseRecord record = (AbstractBaseRecord) arg;
entry.append( ',' ).append( record.getClass().getSimpleName() )
.append( '[' ).append( record.getLongId() ).append( ']' );
}
}
String message = entry.append( ')' ).toString();
if ( null != data.put( message, new Throwable( message ) ) )
{
Integer cur = duplicates.get( message );
if ( cur == null )
{
cur = 1;
}
duplicates.put( message, cur + 1 );
}
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_full_ExecutionOrderIntegrationTest.java
|
4,098
|
private static class ComparativeLogging implements DiffRecordAccess
{
private final DiffRecordAccess access;
private final InvocationLog log;
ComparativeLogging( DiffRecordAccess access, InvocationLog log )
{
this.access = access;
this.log = log;
}
private <T extends AbstractBaseRecord> LoggingReference<T> logging( RecordReference<T> actual )
{
return new LoggingReference<>( actual, log );
}
@Override
public RecordReference<NodeRecord> previousNode( long id )
{
return logging( access.previousNode( id ) );
}
@Override
public RecordReference<RelationshipRecord> previousRelationship( long id )
{
return logging( access.previousRelationship( id ) );
}
@Override
public RecordReference<PropertyRecord> previousProperty( long id )
{
return logging( access.previousProperty( id ) );
}
@Override
public RecordReference<NeoStoreRecord> previousGraph()
{
return logging( access.previousGraph() );
}
@Override
public DynamicRecord changedSchema( long id )
{
return access.changedSchema( id );
}
@Override
public NodeRecord changedNode( long id )
{
return access.changedNode( id );
}
@Override
public RelationshipRecord changedRelationship( long id )
{
return access.changedRelationship( id );
}
@Override
public PropertyRecord changedProperty( long id )
{
return access.changedProperty( id );
}
@Override
public DynamicRecord changedString( long id )
{
return access.changedString( id );
}
@Override
public DynamicRecord changedArray( long id )
{
return access.changedArray( id );
}
@Override
public RecordReference<DynamicRecord> schema( long id )
{
return logging( access.schema( id ) );
}
@Override
public RecordReference<NodeRecord> node( long id )
{
return logging( access.node( id ) );
}
@Override
public RecordReference<RelationshipRecord> relationship( long id )
{
return logging( access.relationship( id ) );
}
@Override
public RecordReference<PropertyRecord> property( long id )
{
return logging( access.property( id ) );
}
@Override
public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id )
{
return logging( access.relationshipType( id ) );
}
@Override
public RecordReference<PropertyKeyTokenRecord> propertyKey( int id )
{
return logging( access.propertyKey( id ) );
}
@Override
public RecordReference<DynamicRecord> string( long id )
{
return logging( access.string( id ) );
}
@Override
public RecordReference<DynamicRecord> array( long id )
{
return logging( access.array( id ) );
}
@Override
public RecordReference<DynamicRecord> relationshipTypeName( int id )
{
return logging( access.relationshipTypeName( id ) );
}
@Override
public RecordReference<DynamicRecord> nodeLabels( long id )
{
return logging( access.nodeLabels( id ) );
}
@Override
public RecordReference<LabelTokenRecord> label( int id )
{
return logging( access.label( id ) );
}
@Override
public RecordReference<DynamicRecord> labelName( int id )
{
return logging( access.labelName( id ) );
}
@Override
public RecordReference<DynamicRecord> propertyKeyName( int id )
{
return logging( access.propertyKeyName( id ) );
}
@Override
public RecordReference<NeoStoreRecord> graph()
{
return logging( access.graph() );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_full_ExecutionOrderIntegrationTest.java
|
4,099
|
{
@Override
protected void generateInitialData( GraphDatabaseService graphDb )
{
// TODO: create bigger sample graph here
try ( org.neo4j.graphdb.Transaction tx = graphDb.beginTx() )
{
Node node1 = set( graphDb.createNode() );
Node node2 = set( graphDb.createNode(), property( "key", "value" ) );
node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "C" ) );
tx.success();
}
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_full_ExecutionOrderIntegrationTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.