Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
3,100
private static class Hit { private final DirectionData start; private final DirectionData end; private final Node connectingNode; Hit( DirectionData start, DirectionData end, Node connectingNode ) { this.start = start; this.end = end; this.connectingNode = connectingNode; } @Override public int hashCode() { return connectingNode.hashCode(); } @Override public boolean equals( Object obj ) { Hit o = (Hit) obj; return connectingNode.equals( o.connectingNode ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,101
private static class DirectionDataPath implements Path { private final Node startNode; private Node endNode; private int length; DirectionDataPath( Node startNode ) { this.startNode = startNode; this.endNode = startNode; this.length = 0; } void setEndNode( Node endNode ) { this.endNode = endNode; } void setLength( int length ) { this.length = length; } @Override public Node startNode() { return startNode; } @Override public Node endNode() { return endNode; } @Override public Relationship lastRelationship() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> relationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> reverseRelationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> nodes() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> reverseNodes() { throw new UnsupportedOperationException(); } @Override public int length() { return length; } @Override public Iterator<PropertyContainer> iterator() { throw new UnsupportedOperationException(); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,102
{ @Override protected Iterator<Relationship> createNestedIterator( Node node ) { lastPath.setEndNode( node ); return expander.expand( lastPath, BranchState.NO_STATE ).iterator(); } };
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,103
private class DirectionData extends PrefetchingIterator<Node> { private final Node startNode; private int currentDepth; private Iterator<Relationship> nextRelationships; private final Collection<Node> nextNodes = new ArrayList<Node>(); private Map<Node, LevelData> visitedNodes = new HashMap<Node, LevelData>(); private final Collection<Long> sharedVisitedRels; private final DirectionDataPath lastPath; private final MutableInteger sharedFrozenDepth; private final MutableBoolean sharedStop; private final MutableInteger sharedCurrentDepth; private boolean haveFoundSomething; private boolean stop; private final PathExpander expander; DirectionData( Node startNode, Collection<Long> sharedVisitedRels, MutableInteger sharedFrozenDepth, MutableBoolean sharedStop, MutableInteger sharedCurrentDepth, PathExpander expander ) { this.startNode = startNode; this.visitedNodes.put( startNode, new LevelData( null, 0 ) ); this.nextNodes.add( startNode ); this.sharedFrozenDepth = sharedFrozenDepth; this.sharedStop = sharedStop; this.sharedCurrentDepth = sharedCurrentDepth; this.expander = expander; this.sharedVisitedRels = sharedVisitedRels; this.lastPath = new DirectionDataPath( startNode ); if ( sharedCurrentDepth.value < maxDepth ) { prepareNextLevel(); } else { this.nextRelationships = Collections.<Relationship>emptyList().iterator(); } } private void prepareNextLevel() { Collection<Node> nodesToIterate = new ArrayList<Node>( filterNextLevelNodes( this.nextNodes ) ); this.nextNodes.clear(); this.lastPath.setLength( currentDepth ); this.nextRelationships = new NestingIterator<Relationship, Node>( nodesToIterate.iterator() ) { @Override protected Iterator<Relationship> createNestedIterator( Node node ) { lastPath.setEndNode( node ); return expander.expand( lastPath, BranchState.NO_STATE ).iterator(); } }; this.currentDepth++; this.sharedCurrentDepth.value++; } @Override protected Node fetchNextOrNull() { while ( true ) { Relationship nextRel = fetchNextRelOrNull(); if ( nextRel == null ) { return null; } lastMetadata.rels++; if ( !hitDecider.canVisitRelationship( sharedVisitedRels, nextRel ) ) { continue; } Node result = nextRel.getOtherNode( this.lastPath.endNode() ); LevelData levelData = this.visitedNodes.get( result ); boolean createdLevelData = false; if ( levelData == null ) { levelData = new LevelData( nextRel, this.currentDepth ); this.visitedNodes.put( result, levelData ); createdLevelData = true; } if ( this.currentDepth == levelData.depth && !createdLevelData ) { levelData.addRel( nextRel ); } // Was this level data created right now, i.e. have we visited this node before? // In that case don't add it as next node to traverse if ( createdLevelData ) { this.nextNodes.add( result ); return result; } } } private boolean canGoDeeper() { return this.sharedFrozenDepth.value == MutableInteger.NULL && this.sharedCurrentDepth.value < maxDepth; } private Relationship fetchNextRelOrNull() { if ( this.stop || this.sharedStop.value ) { return null; } boolean hasComeTooFarEmptyHanded = this.sharedFrozenDepth.value != MutableInteger.NULL && this.sharedCurrentDepth.value > this.sharedFrozenDepth.value && !this.haveFoundSomething; if ( hasComeTooFarEmptyHanded ) { return null; } if ( !this.nextRelationships.hasNext() ) { if ( canGoDeeper() ) { prepareNextLevel(); } } return this.nextRelationships.hasNext() ? this.nextRelationships.next() : null; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,104
private static class DepthHitDecider implements HitDecider { private final int depth; DepthHitDecider( int depth ) { this.depth = depth; } public boolean isHit( int depth ) { return this.depth == depth; } public boolean canVisitRelationship( Collection<Long> rels, Relationship rel ) { return rels.add( rel.getId() ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,105
{ public boolean isHit( int depth ) { return true; } public boolean canVisitRelationship( Collection<Long> rels, Relationship rel ) { return true; } };
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,106
{ @Override protected LinkedList<Relationship> underlyingObjectToObject( PathData object ) { return object.rels; } };
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,107
public class AncestorTestCase implements GraphHolder { public @Rule TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor( this, true ) ); private static GraphDatabaseService gdb; @Test @Graph( { "root contains child1", "child1 contains child11", "child1 contains child12", "root contains child2", "child12 contains child121", "child1 contains child13" } ) public void test() { RelationshipExpander expander = Traversal.expanderForTypes(Rels.contains, Direction.INCOMING); List<Node> nodeSet = new ArrayList<Node>(); Map<String, Node> graph = data.get(); nodeSet.add( graph.get( "child1" ) ); nodeSet.add( graph.get( "root" ) ); Transaction transaction = gdb.beginTx(); try { Node ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "root" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "child11" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "child1" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child121" ) ); nodeSet.add( graph.get( "child12" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "child12" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child11" ) ); nodeSet.add( graph.get( "child13" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "child1" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child2" ) ); nodeSet.add( graph.get( "child121" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "root" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child11" ) ); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "child13" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "child1" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child11" ) ); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "child13" ) ); nodeSet.add( graph.get( "child121" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "child1" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child11" ) ); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "child13" ) ); nodeSet.add( graph.get( "child121" ) ); nodeSet.add( graph.get( "child2" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "root" ), ancestor); nodeSet.clear(); nodeSet.add( graph.get( "child11" ) ); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "child13" ) ); nodeSet.add( graph.get( "child121" ) ); nodeSet.add( graph.get( "child12" ) ); nodeSet.add( graph.get( "root" ) ); ancestor = AncestorsUtil.lowestCommonAncestor( nodeSet, expander); assertEquals(graph.get( "root" ), ancestor); } finally { transaction.finish(); } } @Override public GraphDatabaseService graphdb() { return gdb; } @BeforeClass public static void before() { gdb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @AfterClass public static void after() { gdb.shutdown(); } enum Rels implements RelationshipType { contains } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_ancestor_AncestorTestCase.java
3,108
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_StressCentralityTest.java
3,109
public class UdcConstants { public static final String ID = "id"; public static final String VERSION = "v"; public static final String REVISION = "revision"; public static final String EDITION = "edition"; public static final String TAGS = "tags"; public static final String CLUSTER_HASH = "cluster"; public static final String SOURCE = "source"; public static final String REGISTRATION = "reg"; public static final String MAC = "mac"; public static final String PING = "p"; public static final String DISTRIBUTION = "dist"; public static final String USER_AGENTS = "ua"; public static final String UDC_PROPERTY_PREFIX = "neo4j.ext.udc"; public static final String OS_PROPERTY_PREFIX = "os"; public static final String UNKNOWN_DIST = "unknown"; }
false
community_udc_src_main_java_org_neo4j_ext_udc_UdcConstants.java
3,110
public class UtilTest extends Neo4jAlgoTestCase { @Test public void testPathCounter() { // Nodes Node a = graphDb.createNode(); Node b = graphDb.createNode(); Node c = graphDb.createNode(); Node d = graphDb.createNode(); Node e = graphDb.createNode(); Node f = graphDb.createNode(); // Predecessor lists List<Relationship> ap = new LinkedList<Relationship>(); List<Relationship> bp = new LinkedList<Relationship>(); List<Relationship> cp = new LinkedList<Relationship>(); List<Relationship> dp = new LinkedList<Relationship>(); List<Relationship> ep = new LinkedList<Relationship>(); List<Relationship> fp = new LinkedList<Relationship>(); // Predecessor map Map<Node,List<Relationship>> predecessors = new HashMap<Node,List<Relationship>>(); predecessors.put( a, ap ); predecessors.put( b, bp ); predecessors.put( c, cp ); predecessors.put( d, dp ); predecessors.put( e, ep ); predecessors.put( f, fp ); // Add relations fp.add( f.createRelationshipTo( c, MyRelTypes.R1 ) ); fp.add( f.createRelationshipTo( e, MyRelTypes.R1 ) ); ep.add( e.createRelationshipTo( b, MyRelTypes.R1 ) ); ep.add( e.createRelationshipTo( d, MyRelTypes.R1 ) ); dp.add( d.createRelationshipTo( a, MyRelTypes.R1 ) ); cp.add( c.createRelationshipTo( b, MyRelTypes.R1 ) ); bp.add( b.createRelationshipTo( a, MyRelTypes.R1 ) ); // Count PathCounter counter = new Util.PathCounter( predecessors ); assertTrue( counter.getNumberOfPathsToNode( a ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( b ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( c ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( d ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( e ) == 2 ); assertTrue( counter.getNumberOfPathsToNode( f ) == 3 ); // Reverse counter = new Util.PathCounter( Util.reversedPredecessors( predecessors )); assertTrue( counter.getNumberOfPathsToNode( a ) == 3 ); assertTrue( counter.getNumberOfPathsToNode( b ) == 2 ); assertTrue( counter.getNumberOfPathsToNode( c ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( d ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( e ) == 1 ); assertTrue( counter.getNumberOfPathsToNode( f ) == 1 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_UtilTest.java
3,111
public abstract class CommonEvaluators { public static CostEvaluator<Double> doubleCostEvaluator( String relationshipCostPropertyKey ) { return new DoubleEvaluator( relationshipCostPropertyKey ); } public static CostEvaluator<Double> doubleCostEvaluator( String relationshipCostPropertyKey, double defaultCost ) { return new DoubleEvaluatorWithDefault( relationshipCostPropertyKey, defaultCost ); } public static CostEvaluator<Integer> intCostEvaluator( String relationshipCostPropertyKey ) { return new IntegerEvaluator( relationshipCostPropertyKey ); } public static EstimateEvaluator<Double> geoEstimateEvaluator( String latitudePropertyKey, String longitudePropertyKey ) { return new GeoEstimateEvaluator( latitudePropertyKey, longitudePropertyKey ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_CommonEvaluators.java
3,112
public final class OSGiActivator implements BundleActivator { /** * Called whenever the OSGi framework starts our bundle */ public void start( BundleContext bc ) throws Exception { Dictionary props = new Properties(); // Register our example service implementation in the OSGi service registry bc.registerService( KernelExtensionFactory.class.getName(), new UdcKernelExtensionFactory(), props ); } /** * Called whenever the OSGi framework stops our bundle */ public void stop( BundleContext bc ) throws Exception { // no need to unregister our service - the OSGi framework handles it for us } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_osgi_OSGiActivator.java
3,113
public class UdcTimerTask extends TimerTask { // ABKTODO: make this thread safe public static final Map<String, Integer> successCounts = new HashMap<String, Integer>(); public static final Map<String, Integer> failureCounts = new HashMap<String, Integer>(); private final String storeId; private final Pinger pinger; public UdcTimerTask( String hostAddress, UdcInformationCollector collector ) { this.storeId = collector.getStoreId(); successCounts.put( storeId, 0 ); failureCounts.put( storeId, 0 ); pinger = new Pinger( hostAddress, collector ); } @Override public void run() { try { pinger.ping(); incrementSuccessCount( storeId ); } catch ( IOException e ) { incrementFailureCount( storeId ); } } private void incrementSuccessCount( String storeId ) { Integer currentCount = successCounts.get( storeId ); currentCount++; successCounts.put( storeId, currentCount ); } private void incrementFailureCount( String storeId ) { Integer currentCount = failureCounts.get( storeId ); currentCount++; failureCounts.put( storeId, currentCount ); } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_UdcTimerTask.java
3,114
@Service.Implementation(KernelExtensionFactory.class) public class UdcKernelExtensionFactory extends KernelExtensionFactory<UdcKernelExtensionFactory.Dependencies> { static final String KEY = "kernel udc"; public interface Dependencies { Config getConfig(); XaDataSourceManager getXaDataSourceManager(); KernelData getKernelData(); } /** * No-arg constructor, sets the extension key to "kernel udc". */ public UdcKernelExtensionFactory() { super( KEY ); } @Override public Class getSettingsClass() { return UdcSettings.class; } @Override public Lifecycle newKernelExtension( UdcKernelExtensionFactory.Dependencies dependencies ) throws Throwable { return new UdcKernelExtension( loadConfig( dependencies.getConfig() ), dependencies.getXaDataSourceManager(), dependencies.getKernelData(), new Timer( "Neo4j UDC Timer", /*isDaemon=*/true ) ); } private Config loadConfig( Config config ) { Properties udcProps = loadUdcProperties(); HashMap<String, String> configParams = new HashMap<String, String>( config.getParams() ); for ( Map.Entry<Object, Object> entry : udcProps.entrySet() ) { configParams.put( (String) entry.getKey(), (String) entry.getValue() ); } return new Config( configParams ); } private Properties loadUdcProperties() { Properties sysProps = new Properties(); try { InputStream resource = getClass().getResourceAsStream( "/org/neo4j/ext/udc/udc.properties" ); if ( resource != null ) { sysProps.load( resource ); } } catch ( Exception e ) { // AN: commenting out as this provides no value to the user //System.err.println( "failed to load udc.properties, because: " + e ); } return sysProps; } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_UdcKernelExtensionFactory.java
3,115
public class UdcKernelExtension implements Lifecycle { private Timer timer; private Config config; private XaDataSourceManager xadsm; private KernelData kernelData; public UdcKernelExtension( Config config, XaDataSourceManager xadsm, KernelData kernelData, Timer timer ) { this.config = config; this.xadsm = xadsm; this.kernelData = kernelData; this.timer = timer; } @Override public void init() throws Throwable { } @Override public void start() throws Throwable { if ( !config.get( UdcSettings.udc_enabled ) ) { return; } int firstDelay = config.get( UdcSettings.first_delay ); int interval = config.get( UdcSettings.interval ); String hostAddress = config.get(UdcSettings.udc_host); UdcInformationCollector collector = new DefaultUdcInformationCollector( config, xadsm, kernelData ); UdcTimerTask task = new UdcTimerTask( hostAddress, collector ); timer.scheduleAtFixedRate( task, firstDelay, interval ); } @Override public void stop() throws Throwable { if ( timer != null ) { timer.cancel(); timer = null; } } @Override public void shutdown() throws Throwable { } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_UdcKernelExtension.java
3,116
private static class PointerTo<T> { private T value; public PointerTo( T value ) { this.value = value; } public T getValue() { return value; } public void setValue( T value ) { this.value = value; } }
false
community_udc-integration_src_test_java_org_neo4j_ext_udc_impl_UdcExtensionImplTest.java
3,117
{ @Override public boolean isTrue( Integer value ) { return value > 0; } };
false
community_udc-integration_src_test_java_org_neo4j_ext_udc_impl_UdcExtensionImplTest.java
3,118
{ @Override public boolean isTrue( Integer value ) { return value == 0; } };
false
community_udc-integration_src_test_java_org_neo4j_ext_udc_impl_UdcExtensionImplTest.java
3,119
{ @Override public void run() { while ( !flag.getValue() ) { try { HttpGet httpget = new HttpGet( url.toURI() ); httpget.addHeader( "Accept", "application/json" ); DefaultHttpClient client = new DefaultHttpClient(); client.execute( httpget ); // If we get here, the server's ready flag.setValue( true ); latch.countDown(); } catch ( Exception e ) { throw new RuntimeException( e ); } } } } );
false
community_udc-integration_src_test_java_org_neo4j_ext_udc_impl_UdcExtensionImplTest.java
3,120
public class UdcExtensionImplTest { private static final String VersionPattern = "\\d\\.\\d+((\\.|\\-).*)?"; @Rule public TestName testName = new TestName(); private File path; private PingerHandler handler; private Map<String, String> config; @Before public void resetUdcState() { UdcTimerTask.successCounts.clear(); UdcTimerTask.failureCounts.clear(); path = TargetDirectory.forTest( getClass() ).cleanDirectory( testName.getMethodName() ); } /** * Sanity check to make sure a database can be created * and destroyed. * * @throws java.io.IOException */ @Test public void shouldNotCrashNormalGraphdbCreation() throws IOException { GraphDatabaseService graphdb = createDatabase( null ); destroy( graphdb ); } /** * Expect the counts to be initialized. */ @Test public void shouldLoadWhenNormalGraphdbIsCreated() throws Exception { GraphDatabaseService graphdb = createDatabase( null ); // when the UDC extension successfully loads, it initializes the attempts count to 0 assertGotSuccessWithRetry( IS_ZERO ); destroy( graphdb ); } /** * Expect separate counts for each graphdb. */ @Test public void shouldLoadForEachCreatedGraphdb() throws IOException { GraphDatabaseService graphdb1 = createDatabase( null ); GraphDatabaseService graphdb2 = createDatabase( null ); Set<String> successCountValues = UdcTimerTask.successCounts.keySet(); assertThat( successCountValues.size(), equalTo( 2 ) ); assertThat( "this", is( not( "that" ) ) ); destroy( graphdb1 ); destroy( graphdb2 ); } @Test public void shouldRecordFailuresWhenThereIsNoServer() throws Exception { File possibleDirectory = new File( path, "should-record-failures" ); GraphDatabaseService graphdb = new GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( possibleDirectory.getPath() ). loadPropertiesFromURL( getClass().getResource( "/org/neo4j/ext/udc/udc.properties" ) ). setConfig( UdcSettings.first_delay, "100" ). setConfig( UdcSettings.udc_host, "127.0.0.1:1" ). newGraphDatabase(); assertGotFailureWithRetry( IS_GREATER_THAN_ZERO ); destroy( graphdb ); } @Test public void shouldRecordSuccessesWhenThereIsAServer() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertGotFailureWithRetry( IS_ZERO ); destroy( graphdb ); } @Test public void shouldBeAbleToSpecifySourceWithConfig() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "unit-testing", handler.getQueryMap().get( SOURCE ) ); destroy( graphdb ); } private void setupServer() throws Exception { // first, set up the test server LocalTestServer server = new LocalTestServer( null, null ); handler = new PingerHandler(); server.register( "/*", handler ); server.start(); int servicePort = server.getServicePort(); String serviceHostName = server.getServiceHostName(); String serverAddress = serviceHostName + ":" + servicePort; config = new HashMap<>(); config.put( UdcSettings.first_delay.name(), "100" ); config.put( UdcSettings.udc_host.name(), serverAddress ); blockUntilServerAvailable( new URL( "http", serviceHostName, servicePort, "/" ) ); } private void blockUntilServerAvailable( final URL url ) throws Exception { final CountDownLatch latch = new CountDownLatch( 1 ); final PointerTo<Boolean> flag = new PointerTo<>( false ); Thread t = new Thread( new Runnable() { @Override public void run() { while ( !flag.getValue() ) { try { HttpGet httpget = new HttpGet( url.toURI() ); httpget.addHeader( "Accept", "application/json" ); DefaultHttpClient client = new DefaultHttpClient(); client.execute( httpget ); // If we get here, the server's ready flag.setValue( true ); latch.countDown(); } catch ( Exception e ) { throw new RuntimeException( e ); } } } } ); t.run(); latch.await( 1000, TimeUnit.MILLISECONDS ); t.join(); } @Test public void shouldNotBeAbleToSpecifyRegistrationIdWithConfig() throws Exception { setupServer(); config.put( UdcSettings.udc_registration_key.name(), "marketoid" ); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "test-reg", handler.getQueryMap().get( REGISTRATION ) ); destroy( graphdb ); } @Test public void shouldBeAbleToReadDefaultRegistration() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "test-reg", handler.getQueryMap().get( REGISTRATION ) ); destroy( graphdb ); } @Test public void shouldBeAbleToDetermineTestTagFromClasspath() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "test,web", handler.getQueryMap().get( TAGS ) ); destroy( graphdb ); } @Test public void shouldBeAbleToDetermineEditionFromClasspath() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( Edition.community.name(), handler.getQueryMap().get( EDITION ) ); destroy( graphdb ); } @Test public void shouldBeAbleToDetermineUserAgent() throws Exception { makeRequestWithAgent( "test/1.0" ); setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "test/1.0", handler.getQueryMap().get( USER_AGENTS ) ); destroy( graphdb ); } @Test public void shouldBeAbleToDetermineUserAgents() throws Exception { makeRequestWithAgent( "test/1.0" ); makeRequestWithAgent( "foo/bar" ); setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); String userAgents = handler.getQueryMap().get( USER_AGENTS ); assertEquals( true, userAgents.contains( "test/1.0" ) ); assertEquals( true, userAgents.contains( "foo/bar" ) ); destroy( graphdb ); } @Test public void shouldUpdateTheUserAgentsPerPing() throws Exception { makeRequestWithAgent( "test/1.0" ); setupServer(); config.put( UdcSettings.interval.name(), "1000" ); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); String userAgents = handler.getQueryMap().get( USER_AGENTS ); assertEquals( true, userAgents.contains( "test/1.0" ) ); makeRequestWithAgent( "foo/bar" ); Thread.sleep( 1000 ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); userAgents = handler.getQueryMap().get( USER_AGENTS ); assertEquals( true, userAgents.contains( "foo/bar" ) ); assertEquals( false, userAgents.contains( "test/1.0" ) ); destroy( graphdb ); } @Test public void shouldIncludeMacAddressInConfig() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertNotNull( handler.getQueryMap().get( MAC ) ); destroy( graphdb ); } @Test public void shouldIncludePrefixedSystemProperties() throws Exception { setupServer(); System.setProperty( UdcConstants.UDC_PROPERTY_PREFIX + ".test", "udc-property" ); System.setProperty( "os.test", "os-property" ); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( "udc-property", handler.getQueryMap().get( "test" ) ); assertEquals( "os-property", handler.getQueryMap().get( "os.test" ) ); destroy( graphdb ); } @Test public void shouldNotIncludeDistributionForWindows() throws Exception { setupServer(); System.setProperty( "os.name", "Windows" ); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) ); destroy( graphdb ); } @Test public void shouldIncludeDistributionForLinux() throws Exception { if ( !System.getProperty( "os.name" ).equals( "Linux" ) ) { return; } setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( DefaultUdcInformationCollector.searchForPackageSystems(), handler.getQueryMap().get( "dist" ) ); destroy( graphdb ); } @Test public void shouldNotIncludeDistributionForMacOS() throws Exception { setupServer(); System.setProperty( "os.name", "Mac OS X" ); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) ); destroy( graphdb ); } @Test public void shouldIncludeVersionInConfig() throws Exception { setupServer(); GraphDatabaseService graphdb = createDatabase( config ); assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO ); String version = handler.getQueryMap().get( VERSION ); assertTrue( version.matches( VersionPattern ) ); destroy( graphdb ); } @Test public void shouldMatchAllValidVersions() throws Exception { assertTrue( "1.8.M07".matches( VersionPattern ) ); assertTrue( "1.8.RC1".matches( VersionPattern ) ); assertTrue( "1.8.GA".matches( VersionPattern ) ); assertTrue( "1.8".matches( VersionPattern ) ); assertTrue( "1.9".matches( VersionPattern ) ); assertTrue( "1.9-SNAPSHOT".matches( VersionPattern ) ); assertTrue( "2.0-SNAPSHOT".matches( VersionPattern ) ); assertTrue( "1.9.M01".matches( VersionPattern ) ); assertTrue( "1.10".matches( VersionPattern ) ); assertTrue( "1.10-SNAPSHOT".matches( VersionPattern ) ); assertTrue( "1.10.M01".matches( VersionPattern ) ); } @Test public void testUdcPropertyFileKeysMatchSettings() throws Exception { Map<String, String> config = MapUtil.load( getClass().getResourceAsStream( "/org/neo4j/ext/udc/udc" + ".properties" ) ); assertEquals( "test-reg", config.get( UdcSettings.udc_registration_key.name() ) ); assertEquals( "unit-testing", config.get( UdcSettings.udc_source.name() ) ); } @Test public void shouldFilterPlusBuildNumbers() throws Exception { assertThat( new DefaultUdcInformationCollector( null, null, null ).filterVersionForUDC( "1.9.0-M01+00001" ), is( equalTo( "1.9.0-M01" ) ) ); } @Test public void shouldNotFilterSnapshotBuildNumbers() throws Exception { assertThat( new DefaultUdcInformationCollector( null, null, null ).filterVersionForUDC( "2.0-SNAPSHOT" ), is( equalTo( "2.0-SNAPSHOT" ) ) ); } @Test public void shouldNotFilterReleaseBuildNumbers() throws Exception { assertThat( new DefaultUdcInformationCollector( null, null, null ).filterVersionForUDC( "1.9" ), is( equalTo( "1.9" ) ) ); } private static interface Condition<T> { boolean isTrue( T value ); } private static final Condition<Integer> IS_ZERO = new Condition<Integer>() { @Override public boolean isTrue( Integer value ) { return value == 0; } }; private static final Condition<Integer> IS_GREATER_THAN_ZERO = new Condition<Integer>() { @Override public boolean isTrue( Integer value ) { return value > 0; } }; private void assertGotSuccessWithRetry( Condition<Integer> condition ) throws Exception { assertGotPingWithRetry( UdcTimerTask.successCounts, condition ); } private void assertGotFailureWithRetry( Condition<Integer> condition ) throws Exception { assertGotPingWithRetry( UdcTimerTask.failureCounts, condition ); } private void assertGotPingWithRetry( Map<String, Integer> counts, Condition<Integer> condition ) throws Exception { for ( int i = 0; i < 50; i++ ) { Thread.sleep( 200 ); Collection<Integer> countValues = counts.values(); Integer count = countValues.iterator().next(); if ( condition.isTrue( count ) ) { return; } } fail(); } private GraphDatabaseService createDatabase( Map<String, String> config ) throws IOException { GraphDatabaseBuilder graphDatabaseBuilder = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder(); graphDatabaseBuilder.loadPropertiesFromURL( getClass().getResource( "/org/neo4j/ext/udc/udc.properties" ) ); if ( config != null ) { graphDatabaseBuilder.setConfig( config ); } return graphDatabaseBuilder.newGraphDatabase(); } private void destroy( GraphDatabaseService dbToDestroy ) throws IOException { @SuppressWarnings("deprecation") InternalAbstractGraphDatabase db = (InternalAbstractGraphDatabase) dbToDestroy; dbToDestroy.shutdown(); FileUtils.deleteDirectory( new File( db.getStoreDir() ) ); } private static class PointerTo<T> { private T value; public PointerTo( T value ) { this.value = value; } public T getValue() { return value; } public void setValue( T value ) { this.value = value; } } private ContainerRequest makeRequestWithAgent( String agent ) { return CollectUserAgentFilter.instance().filter( request( agent ) ); } private static ContainerRequest request( String... userAgent ) { ContainerRequest request = mock( ContainerRequest.class ); List<String> headers = Arrays.asList( userAgent ); stub(request.getRequestHeader( "User-Agent" )).toReturn( headers ); return request; } }
false
community_udc-integration_src_test_java_org_neo4j_ext_udc_impl_UdcExtensionImplTest.java
3,121
public class TestUdcKernelExtensionFactory extends KernelExtensionFactoryContractTest { public TestUdcKernelExtensionFactory() { super( UdcKernelExtensionFactory.KEY, UdcKernelExtensionFactory.class ); } }
false
community_udc_src_test_java_org_neo4j_ext_udc_impl_TestUdcKernelExtensionFactory.java
3,122
static class TestUdcCollector implements UdcInformationCollector { private final Map<String, String> params; private boolean crashed; TestUdcCollector( Map<String, String> params ) { this.params = params; } @Override public Map<String, String> getUdcParams() { return params; } @Override public String getStoreId() { return getUdcParams().get( ID ); } @Override public boolean getCrashPing() { return crashed; } public UdcInformationCollector withCrash() { crashed = true; return this; } }
false
community_udc_src_test_java_org_neo4j_ext_udc_impl_PingerTest.java
3,123
public class PingerTest { private final String EXPECTED_KERNEL_VERSION = "1.0"; private final String EXPECTED_STORE_ID = "CAFE"; private String hostname = "localhost"; private String serverUrl; private LocalTestServer server = null; PingerHandler handler; @Before public void setUp() throws Exception { handler = new PingerHandler(); server = new LocalTestServer( null, null ); server.register( "/*", handler ); server.start(); hostname = server.getServiceHostName(); serverUrl = "http://" + hostname + ":" + server.getServicePort(); } /** * Test that the LocalTestServer actually works. * * @throws Exception */ @Test public void shouldRespondToHttpClientGet() throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet( serverUrl + "/?id=storeId+v=kernelVersion" ); HttpResponse response = httpclient.execute( httpget ); HttpEntity entity = response.getEntity(); if ( entity != null ) { InputStream instream = entity.getContent(); int l; byte[] tmp = new byte[2048]; while ( (l = instream.read( tmp )) != -1 ) { } } assertThat( response, notNullValue() ); assertThat( response.getStatusLine().getStatusCode(), is( HttpStatus.SC_OK ) ); } static class TestUdcCollector implements UdcInformationCollector { private final Map<String, String> params; private boolean crashed; TestUdcCollector( Map<String, String> params ) { this.params = params; } @Override public Map<String, String> getUdcParams() { return params; } @Override public String getStoreId() { return getUdcParams().get( ID ); } @Override public boolean getCrashPing() { return crashed; } public UdcInformationCollector withCrash() { crashed = true; return this; } } @Test public void shouldPingServer() { final String hostURL = hostname+":"+ server.getServicePort(); final Map<String, String> udcFields = new HashMap<String, String>(); udcFields.put( ID, EXPECTED_STORE_ID ); udcFields.put( UdcConstants.VERSION, EXPECTED_KERNEL_VERSION ); Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) ); Exception thrownException = null; try { p.ping(); } catch ( IOException e ) { thrownException = e; e.printStackTrace(); } assertThat( thrownException, nullValue() ); Map<String, String> actualQueryMap = handler.getQueryMap(); assertThat( actualQueryMap, notNullValue() ); assertThat( actualQueryMap.get( ID ), is( EXPECTED_STORE_ID ) ); } @Test public void shouldIncludePingCountInURI() throws IOException { final int EXPECTED_PING_COUNT = 16; final String hostURL = hostname+":"+ server.getServicePort(); final Map<String, String> udcFields = new HashMap<String, String>(); Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) ); for ( int i = 0; i < EXPECTED_PING_COUNT; i++ ) { p.ping(); } assertThat( p.getPingCount(), is( equalTo( EXPECTED_PING_COUNT ) ) ); Map<String, String> actualQueryMap = handler.getQueryMap(); assertThat( actualQueryMap.get( UdcConstants.PING ), is( Integer.toString( EXPECTED_PING_COUNT ) ) ); } @Test public void normalPingSequenceShouldBeOneThenTwoThenThreeEtc() throws Exception { int[] expectedSequence = {1, 2, 3, 4}; final String hostURL = hostname+":"+ server.getServicePort(); final Map<String, String> udcFields = new HashMap<String, String>(); Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) ); for ( int i = 0; i < expectedSequence.length; i++ ) { p.ping(); int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) ); assertEquals( expectedSequence[i], count ); } } @Test public void crashPingSequenceShouldBeMinusOneThenTwoThenThreeEtc() throws Exception { int[] expectedSequence = {-1, 2, 3, 4}; final String hostURL = hostname+":"+ server.getServicePort(); final Map<String, String> udcFields = new HashMap<String, String>(); Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ).withCrash() ); for ( int i = 0; i < expectedSequence.length; i++ ) { p.ping(); int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) ); assertEquals( expectedSequence[i], count ); } } @After public void tearDown() throws Exception { server.stop(); } }
false
community_udc_src_test_java_org_neo4j_ext_udc_impl_PingerTest.java
3,124
public class PingerHandler implements HttpRequestHandler { private final Map<String, String> queryMap = new HashMap<String, String>(); @Override public void handle( HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext ) throws HttpException, IOException { final String requestUri = httpRequest.getRequestLine().getUri(); final int offset = requestUri.indexOf( "?" ); if ( offset > -1 ) { String query = requestUri.substring( offset + 1 ); String[] params = query.split( "\\+" ); if ( params.length > 0 ) { for ( String param : params ) { String[] pair = param.split( "=" ); String key = URLDecoder.decode( pair[0], "UTF-8" ); String value = URLDecoder.decode( pair[1], "UTF-8" ); queryMap.put( key, value ); } } } } public Map<String, String> getQueryMap() { return queryMap; } }
false
community_udc_src_test_java_org_neo4j_ext_udc_impl_PingerHandler.java
3,125
public class Pinger { private final String address; private final UdcInformationCollector collector; private int pingCount = 0; public Pinger( String address, UdcInformationCollector collector ) { this.address = address; this.collector = collector; if ( collector.getCrashPing() ) { pingCount = -1; } } public void ping() throws IOException { pingCount++; Map<String, String> usageDataMap = collector.getUdcParams(); StringBuilder uri = new StringBuilder( "http://" + address + "/" + "?" ); for ( String key : usageDataMap.keySet() ) { uri.append( key ); uri.append( "=" ); uri.append( usageDataMap.get( key ) ); uri.append( "+" ); } // append counts if ( pingCount == 0 ) { uri.append( PING + "=-1" ); pingCount++; } else { uri.append( PING + "=" ).append( pingCount ); } URL url = new URL( uri.toString() ); URLConnection con = url.openConnection(); con.setDoInput( true ); con.setDoOutput( false ); con.setUseCaches( false ); con.connect(); con.getInputStream(); } public Integer getPingCount() { return pingCount; } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_Pinger.java
3,126
{ @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { crashPing = ds.getXaContainer().getLogicalLog().wasNonClean(); storeId = Long.toHexString( ds.getRandomIdentifier() ); } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { crashPing = false; storeId = null; } } } );
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_DefaultUdcInformationCollector.java
3,127
public class DefaultUdcInformationCollector implements UdcInformationCollector { private final Config config; @SuppressWarnings("deprecation") private final KernelData kernel; private String storeId; private boolean crashPing; public DefaultUdcInformationCollector( Config config, XaDataSourceManager xadsm, @SuppressWarnings("deprecation") KernelData kernel ) { this.config = config; this.kernel = kernel; if (xadsm != null) xadsm.addDataSourceRegistrationListener( new DataSourceRegistrationListener() { @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { crashPing = ds.getXaContainer().getLogicalLog().wasNonClean(); storeId = Long.toHexString( ds.getRandomIdentifier() ); } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { crashPing = false; storeId = null; } } } ); } public String filterVersionForUDC(String version) { if ( !version.contains( "+" ) ) return version; return version.substring(0, version.indexOf("+")); } @Override public Map<String, String> getUdcParams() { String classPath = getClassPath(); Map<String, String> udcFields = new HashMap<>(); add( udcFields, ID, storeId ); add( udcFields, VERSION, filterVersionForUDC(kernel.version().getReleaseVersion() )); add( udcFields, REVISION, filterVersionForUDC(kernel.version().getRevision() )); add( udcFields, EDITION, determineEdition( classPath ) ); add( udcFields, TAGS, determineTags( jarNamesForTags, classPath ) ); add( udcFields, CLUSTER_HASH, determineClusterNameHash() ); add( udcFields, SOURCE, config.get( UdcSettings.udc_source ) ); add( udcFields, REGISTRATION, config.get( UdcSettings.udc_registration_key ) ); add( udcFields, MAC, determineMacAddress() ); add( udcFields, DISTRIBUTION, determineOsDistribution() ); add( udcFields, USER_AGENTS, determineUserAgents() ); udcFields.putAll( determineSystemProperties() ); return udcFields; } private String determineOsDistribution() { if ( System.getProperties().getProperty( "os.name", "" ).equals( "Linux" ) ) { return searchForPackageSystems(); } else { return UNKNOWN_DIST; } } static String searchForPackageSystems() { try { if ( new File( "/bin/rpm" ).exists() ) { return "rpm"; } if ( new File( "/usr/bin/dpkg" ).exists() ) { return "dpkg"; } } catch ( Exception e ) { // ignore } return UNKNOWN_DIST; } private Integer determineClusterNameHash() { try { Class<?> haSettings = Class.forName( "org.neo4j.kernel.ha.HaSettings" ); @SuppressWarnings( "unchecked" ) Setting<String> setting = (Setting<String>) haSettings.getField( "cluster_name" ).get( null ); String name = config.get( setting ); return name != null ? Math.abs( name.hashCode() % Integer.MAX_VALUE ) : null; } catch ( Exception e ) { return null; } } private org.neo4j.ext.udc.Edition determineEdition( String classPath ) { if ( classPath.contains( "neo4j-ha" ) ) { return org.neo4j.ext.udc.Edition.enterprise; } if ( classPath.contains( "neo4j-management" ) ) { return org.neo4j.ext.udc.Edition.advanced; } return Edition.community; } private final Map<String, String> jarNamesForTags = MapUtil.stringMap( "spring-", "spring", "(javax.ejb|ejb-jar)", "ejb", "(weblogic|glassfish|websphere|jboss)", "appserver", "openshift", "openshift", "cloudfoundry", "cloudfoundry", "(junit|testng)", "test", "jruby", "ruby", "clojure", "clojure", "jython", "python", "groovy", "groovy", "(tomcat|jetty)", "web", "spring-data-neo4j", "sdn" ); private String determineTags( Map<String, String> jarNamesForTags, String classPath ) { StringBuilder result = new StringBuilder(); for ( Map.Entry<String, String> entry : jarNamesForTags.entrySet() ) { final Pattern pattern = Pattern.compile( entry.getKey() ); if ( pattern.matcher( classPath ).find() ) { result.append( "," ).append( entry.getValue() ); } } if ( result.length() == 0 ) { return null; } return result.substring( 1 ); } private String getClassPath() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); return runtime.getClassPath(); } private String determineMacAddress() { String formattedMac = "0"; try { InetAddress address = InetAddress.getLocalHost(); NetworkInterface ni = NetworkInterface.getByInetAddress( address ); if ( ni != null ) { byte[] mac = ni.getHardwareAddress(); if ( mac != null ) { StringBuilder sb = new StringBuilder( mac.length * 2 ); Formatter formatter = new Formatter( sb ); for ( byte b : mac ) { formatter.format( "%02x", b ); } formattedMac = sb.toString(); } } } catch ( Throwable t ) { // } return formattedMac; } private String determineUserAgents() { try { Class<?> filterClass = Class.forName( "org.neo4j.server.rest.web.CollectUserAgentFilter" ); Object filterInstance = filterClass.getMethod( "instance" ).invoke( null ); Object agents = filterClass.getMethod( "getUserAgents" ).invoke( filterInstance ); String result = toCommaString( agents ); filterClass.getMethod( "reset" ).invoke( filterInstance ); return result; } catch ( Exception e ) { return null; } } private String toCommaString( Object values ) { StringBuilder result = new StringBuilder(); if ( values instanceof Iterable ) { for ( Object agent : (Iterable) values ) { if ( agent == null ) { continue; } if ( result.length() > 0 ) { result.append( "," ); } result.append( agent ); } } else { result.append( values ); } return result.toString(); } private void add( Map<String, String> udcFields, String name, Object value ) { if ( value == null ) { return; } String str = value.toString().trim(); if ( str.isEmpty() ) { return; } udcFields.put( name, str ); } private String removeUdcPrefix( String propertyName ) { if ( propertyName.startsWith( UDC_PROPERTY_PREFIX ) ) { return propertyName.substring( UDC_PROPERTY_PREFIX.length() + 1 ); } return propertyName; } private String sanitizeUdcProperty( String propertyValue ) { return propertyValue.replace( ' ', '_' ); } private Map<String, String> determineSystemProperties() { Map<String, String> relevantSysProps = new HashMap<>(); Properties sysProps = System.getProperties(); Enumeration sysPropsNames = sysProps.propertyNames(); while ( sysPropsNames.hasMoreElements() ) { String sysPropName = (String) sysPropsNames.nextElement(); if ( sysPropName.startsWith( UDC_PROPERTY_PREFIX ) || sysPropName.startsWith( OS_PROPERTY_PREFIX ) ) { String propertyValue = sysProps.getProperty( sysPropName ); relevantSysProps.put( removeUdcPrefix( sysPropName ), sanitizeUdcProperty( propertyValue ) ); } } return relevantSysProps; } @Override public String getStoreId() { return storeId; } @Override public boolean getCrashPing() { return crashPing; } }
false
community_udc_src_main_java_org_neo4j_ext_udc_impl_DefaultUdcInformationCollector.java
3,128
public class UdcSettingsTest { public static final String TEST_HOST_AND_PORT = "test.ucd.neo4j.org:8080"; @Test public void testUdcHostSettingIsUnchanged() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .setConfig(UdcSettings.udc_host, TEST_HOST_AND_PORT).newGraphDatabase(); Config config = db.getDependencyResolver().resolveDependency(Config.class); assertEquals(TEST_HOST_AND_PORT,config.get(UdcSettings.udc_host)); } }
false
community_udc_src_test_java_org_neo4j_ext_udc_UdcSettingsTest.java
3,129
public class UdcSettings { /** * Configuration key for enabling the UDC extension. */ public static final Setting<Boolean> udc_enabled = setting( "neo4j.ext.udc.enabled", BOOLEAN, TRUE ); /** * Configuration key for the first delay, expressed * in milliseconds. */ public static final Setting<Integer> first_delay = setting( "neo4j.ext.udc.first_delay", INTEGER, Integer.toString( 10 * 1000 * 60 ), min( 1 ) ); /** * Configuration key for the interval for regular updates, * expressed in milliseconds. */ public static final Setting<Integer> interval = setting( "neo4j.ext.udc.interval", INTEGER, Integer.toString( 1000 * 60 * 60 * 24 ), min( 1 ) ); /** * The host address to which UDC updates will be sent. * Should be of the form hostname[:port]. */ public static final Setting<String> udc_host = setting( "neo4j.ext.udc.host", STRING, "udc.neo4j.org" ); /** * Configuration key for overriding the source parameter in UDC */ public static final Setting<String> udc_source = setting( "neo4j.ext.udc.source", STRING, Settings.NO_DEFAULT, illegalValueMessage( "Must be a valid source", matches( ANY ) ) ); /** * Unique registration id */ public static final Setting<String> udc_registration_key = setting( "neo4j.ext.udc.reg", STRING, "unreg", illegalValueMessage( "Must be a valid registration id", matches( ANY ) ) ); }
false
community_udc_src_main_java_org_neo4j_ext_udc_UdcSettings.java
3,130
public abstract class GraphAlgoFactory { /** * Returns an algorithm which can find all available paths between two * nodes. These returned paths can contain loops (i.e. a node can occur * more than once in any returned path). * @see AllPaths * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param maxDepth the max {@link Path#length()} returned paths are * allowed to have. * @return an algorithm which finds all paths between two nodes. */ public static PathFinder<Path> allPaths( RelationshipExpander expander, int maxDepth ) { return new AllPaths( maxDepth, expander ); } /** * Returns an algorithm which can find all available paths between two * nodes. These returned paths can contain loops (i.e. a node can occur * more than once in any returned path). * @see AllPaths * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param maxDepth the max {@link Path#length()} returned paths are * allowed to have. * @return an algorithm which finds all paths between two nodes. */ public static PathFinder<Path> allPaths( PathExpander expander, int maxDepth ) { return new AllPaths( maxDepth, expander ); } /** * Returns an algorithm which can find all simple paths between two * nodes. These returned paths cannot contain loops (i.e. a node cannot * occur more than once in any returned path). * @see AllSimplePaths * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param maxDepth the max {@link Path#length()} returned paths are * allowed to have. * @return an algorithm which finds simple paths between two nodes. */ public static PathFinder<Path> allSimplePaths( RelationshipExpander expander, int maxDepth ) { return new AllSimplePaths( maxDepth, expander ); } /** * Returns an algorithm which can find all simple paths between two * nodes. These returned paths cannot contain loops (i.e. a node cannot * occur more than once in any returned path). * @see AllSimplePaths * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param maxDepth the max {@link Path#length()} returned paths are * allowed to have. * @return an algorithm which finds simple paths between two nodes. */ public static PathFinder<Path> allSimplePaths( PathExpander expander, int maxDepth ) { return new AllSimplePaths( maxDepth, expander ); } /** * Returns an algorithm which can find all shortest paths (that is paths * with as short {@link Path#length()} as possible) between two nodes. These * returned paths cannot contain loops (i.e. a node cannot occur more than * once in any returned path). * * @see ShortestPath * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param maxDepth the max {@link Path#length()} returned paths are allowed * to have. * @return an algorithm which finds shortest paths between two nodes. */ public static PathFinder<Path> shortestPath( RelationshipExpander expander, int maxDepth ) { return new ShortestPath( maxDepth, expander ); } /** * Returns an algorithm which can find all shortest paths (that is paths * with as short {@link Path#length()} as possible) between two nodes. These * returned paths cannot contain loops (i.e. a node cannot occur more than * once in any returned path). * * @see ShortestPath * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param maxDepth the max {@link Path#length()} returned paths are allowed * to have. * @return an algorithm which finds shortest paths between two nodes. */ public static PathFinder<Path> shortestPath( PathExpander expander, int maxDepth ) { return new ShortestPath( maxDepth, expander ); } /** * Returns an algorithm which can find all shortest paths (that is paths * with as short {@link Path#length()} as possible) between two nodes. These * returned paths cannot contain loops (i.e. a node cannot occur more than * once in any returned path). * * @see ShortestPath * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param maxDepth the max {@link Path#length()} returned paths are allowed * to have. * @param maxHitCount the maximum number of {@link Path}s to return. * If this number of found paths are encountered the traversal will stop. * @return an algorithm which finds shortest paths between two nodes. */ public static PathFinder<Path> shortestPath( RelationshipExpander expander, int maxDepth, int maxHitCount ) { return new ShortestPath( maxDepth, expander, maxHitCount ); } /** * Returns an algorithm which can find all shortest paths (that is paths * with as short {@link Path#length()} as possible) between two nodes. These * returned paths cannot contain loops (i.e. a node cannot occur more than * once in any returned path). * * @see ShortestPath * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param maxDepth the max {@link Path#length()} returned paths are allowed * to have. * @param maxHitCount the maximum number of {@link Path}s to return. * If this number of found paths are encountered the traversal will stop. * @return an algorithm which finds shortest paths between two nodes. */ public static PathFinder<Path> shortestPath( PathExpander expander, int maxDepth, int maxHitCount ) { return new ShortestPath( maxDepth, expander, maxHitCount ); } /** * Returns an algorithm which can find simple all paths of a certain length * between two nodes. These returned paths cannot contain loops (i.e. a node * could not occur more than once in any returned path). * * @see ShortestPath * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param length the {@link Path#length()} returned paths will have, if any * paths were found. * @return an algorithm which finds paths of a certain length between two nodes. */ public static PathFinder<Path> pathsWithLength( RelationshipExpander expander, int length ) { return new ShortestPath( length, expander, Integer.MAX_VALUE, true ); } /** * Returns an algorithm which can find simple all paths of a certain length * between two nodes. These returned paths cannot contain loops (i.e. a node * could not occur more than once in any returned path). * * @see ShortestPath * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param length the {@link Path#length()} returned paths will have, if any * paths were found. * @return an algorithm which finds paths of a certain length between two nodes. */ public static PathFinder<Path> pathsWithLength( PathExpander expander, int length ) { return new ShortestPath( length, expander, Integer.MAX_VALUE, true ); } /** * Returns an {@link PathFinder} which uses the A* algorithm to find the * cheapest path between two nodes. The definition of "cheap" is the lowest * possible cost to get from the start node to the end node, where the cost * is returned from {@code lengthEvaluator} and {@code estimateEvaluator}. * These returned paths cannot contain loops (i.e. a node cannot occur more * than once in any returned path). * * See http://en.wikipedia.org/wiki/A*_search_algorithm for more * information. * * @see AStar * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param lengthEvaluator evaluator that can return the cost represented * by each relationship the algorithm traverses. * @param estimateEvaluator evaluator that returns an (optimistic) * estimation of the cost to get from the current node (in the traversal) * to the end node. * @return an algorithm which finds the cheapest path between two nodes * using the A* algorithm. */ public static PathFinder<WeightedPath> aStar( RelationshipExpander expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { return new AStar( expander, lengthEvaluator, estimateEvaluator ); } /** * Returns an {@link PathFinder} which uses the A* algorithm to find the * cheapest path between two nodes. The definition of "cheap" is the lowest * possible cost to get from the start node to the end node, where the cost * is returned from {@code lengthEvaluator} and {@code estimateEvaluator}. * These returned paths cannot contain loops (i.e. a node cannot occur more * than once in any returned path). * * See http://en.wikipedia.org/wiki/A*_search_algorithm for more * information. * * @see AStar * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param lengthEvaluator evaluator that can return the cost represented * by each relationship the algorithm traverses. * @param estimateEvaluator evaluator that returns an (optimistic) * estimation of the cost to get from the current node (in the traversal) * to the end node. * @return an algorithm which finds the cheapest path between two nodes * using the A* algorithm. */ public static PathFinder<WeightedPath> aStar( PathExpander expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { return new AStar( expander, lengthEvaluator, estimateEvaluator ); } /** * Returns an {@link PathFinder} which uses the Dijkstra algorithm to find * the cheapest path between two nodes. The definition of "cheap" is the * lowest possible cost to get from the start node to the end node, where * the cost is returned from {@code costEvaluator}. These returned paths * cannot contain loops (i.e. a node cannot occur more than once in any * returned path). * * See http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm for more * information. * * @see Dijkstra * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param costEvaluator evaluator that can return the cost represented * by each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( RelationshipExpander expander, CostEvaluator<Double> costEvaluator ) { return new Dijkstra( expander, costEvaluator ); } /** * Returns an {@link PathFinder} which uses the Dijkstra algorithm to find * the cheapest path between two nodes. The definition of "cheap" is the * lowest possible cost to get from the start node to the end node, where * the cost is returned from {@code costEvaluator}. These returned paths * cannot contain loops (i.e. a node cannot occur more than once in any * returned path). * * See http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm for more * information. * * @see Dijkstra * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param costEvaluator evaluator that can return the cost represented * by each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, CostEvaluator<Double> costEvaluator ) { return new Dijkstra( expander, costEvaluator ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link RelationshipExpander} to use for expanding * {@link Relationship}s for each {@link Node}. * @param relationshipPropertyRepresentingCost the property to represent cost * on each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( RelationshipExpander expander, String relationshipPropertyRepresentingCost ) { return dijkstra( expander, new DoubleEvaluator( relationshipPropertyRepresentingCost ) ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param relationshipPropertyRepresentingCost the property to represent cost * on each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, String relationshipPropertyRepresentingCost ) { return dijkstra( expander, new DoubleEvaluator( relationshipPropertyRepresentingCost ) ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param stateFactory initial state for the traversal branches. * @param costEvaluator the cost evaluator for each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, InitialStateFactory stateFactory, CostEvaluator<Double> costEvaluator ) { return new Dijkstra( expander, new InitialStateFactory.AsInitialBranchState( stateFactory ), costEvaluator ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param stateFactory initial state for the traversal branches. * @param costEvaluator the cost evaluator for each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, InitialBranchState stateFactory, CostEvaluator<Double> costEvaluator ) { return new Dijkstra( expander, stateFactory, costEvaluator ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param stateFactory initial state for the traversal branches. * @param relationshipPropertyRepresentingCost the property to represent cost * on each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, InitialStateFactory stateFactory, String relationshipPropertyRepresentingCost ) { return dijkstra( expander, stateFactory, new DoubleEvaluator( relationshipPropertyRepresentingCost ) ); } /** * See {@link #dijkstra(RelationshipExpander, CostEvaluator)}. * * Uses a cost evaluator which uses the supplied property key to * represent the cost (values of type <bold>double</bold>). * * @param expander the {@link PathExpander} to use for expanding * {@link Relationship}s for each {@link Path}. * @param stateFactory initial state for the traversal branches. * @param relationshipPropertyRepresentingCost the property to represent cost * on each relationship the algorithm traverses. * @return an algorithm which finds the cheapest path between two nodes * using the Dijkstra algorithm. */ public static PathFinder<WeightedPath> dijkstra( PathExpander expander, InitialBranchState stateFactory, String relationshipPropertyRepresentingCost ) { return dijkstra( expander, stateFactory, new DoubleEvaluator( relationshipPropertyRepresentingCost ) ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_GraphAlgoFactory.java
3,131
public class BetweennessCentralityTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1, MyRelTypes.R2, MyRelTypes.R3 ); } protected void assertCentrality( BetweennessCentrality<Double> betweennessCentrality, String nodeId, Double value ) { assertTrue( betweennessCentrality .getCentrality( graph.getNode( nodeId ) ).equals( value ) ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); BetweennessCentrality<Double> betweennessCentrality = new BetweennessCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); betweennessCentrality.calculate(); assertCentrality( betweennessCentrality, "a", 0.5 ); assertCentrality( betweennessCentrality, "b", 0.5 ); assertCentrality( betweennessCentrality, "c", 0.5 ); assertCentrality( betweennessCentrality, "d", 0.5 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.setCurrentRelType( MyRelTypes.R3 ); graph.makeEdgeChain( "d,b,e" ); BetweennessCentrality<Double> betweennessCentrality = new BetweennessCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); betweennessCentrality.calculate(); assertCentrality( betweennessCentrality, "a", 0.0 ); assertCentrality( betweennessCentrality, "b", 6.0 ); assertCentrality( betweennessCentrality, "c", 0.0 ); assertCentrality( betweennessCentrality, "d", 0.0 ); assertCentrality( betweennessCentrality, "e", 0.0 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); BetweennessCentrality<Double> betweennessCentrality = new BetweennessCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); betweennessCentrality.calculate(); assertCentrality( betweennessCentrality, "a", 0.0 ); assertCentrality( betweennessCentrality, "b", 3.0 ); assertCentrality( betweennessCentrality, "c", 4.0 ); assertCentrality( betweennessCentrality, "d", 3.0 ); assertCentrality( betweennessCentrality, "e", 0.0 ); } @Test public void testXlike() { graph.makeEdgeChain( "a,c,a"); graph.makeEdgeChain( "b,c,b"); graph.makeEdgeChain( "b,d,b"); graph.makeEdgeChain( "c,d,c"); graph.makeEdgeChain( "d,e,d"); graph.makeEdgeChain( "d,f,d"); BetweennessCentrality<Double> betweennessCentrality = new BetweennessCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); betweennessCentrality.calculate(); assertCentrality( betweennessCentrality, "a", 0.0 ); assertCentrality( betweennessCentrality, "b", 0.0 ); assertCentrality( betweennessCentrality, "c", 4.0 ); assertCentrality( betweennessCentrality, "d", 7.0 ); assertCentrality( betweennessCentrality, "e", 0.0 ); assertCentrality( betweennessCentrality, "f", 0.0 ); } @Test public void testDependencyUpdating() { graph.makeEdgeChain( "a,b,d,e,f,h" ); graph.makeEdgeChain( "a,c,d" ); graph.makeEdgeChain( "e,g,h" ); new DependencyTest( getSingleSourceShortestPath(), graph.getAllNodes() ) .test(); } class DependencyTest extends BetweennessCentrality<Double> { public DependencyTest( SingleSourceShortestPath<Double> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, nodeSet ); } public void test() { // avoid starting the real calculation by mistake this.doneCalculation = true; // set things up Node startNode = graph.getNode( "a" ); singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); Map<Node,List<Relationship>> predecessors = singleSourceShortestPath .getPredecessors(); Map<Node,List<Relationship>> successors = Util .reversedPredecessors( predecessors ); PathCounter counter = new Util.PathCounter( predecessors ); // Recursively update the node dependencies getAndUpdateNodeDependency( startNode, true, successors, counter, new HashMap<Node,Double>() ); Double adjustment = 0.5; // since direction is BOTH assertCentrality( this, "a", 0.0 * adjustment ); assertCentrality( this, "b", 2.5 * adjustment ); assertCentrality( this, "c", 2.5 * adjustment ); assertCentrality( this, "d", 4.0 * adjustment ); assertCentrality( this, "e", 3.0 * adjustment ); assertCentrality( this, "f", 0.5 * adjustment ); assertCentrality( this, "g", 0.5 * adjustment ); assertCentrality( this, "h", 0.0 * adjustment ); } } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_BetweennessCentralityTest.java
3,132
public class StressCentralityTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } protected void assertCentrality( StressCentrality<Double> stressCentrality, String nodeId, Double value ) { assertTrue( stressCentrality.getCentrality( graph.getNode( nodeId ) ) .equals( value ) ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); StressCentrality<Double> stressCentrality = new StressCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); stressCentrality.calculate(); assertCentrality( stressCentrality, "a", 1.0 ); assertCentrality( stressCentrality, "b", 1.0 ); assertCentrality( stressCentrality, "c", 1.0 ); assertCentrality( stressCentrality, "d", 1.0 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); StressCentrality<Double> stressCentrality = new StressCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); stressCentrality.calculate(); assertCentrality( stressCentrality, "a", 0.0 ); assertCentrality( stressCentrality, "b", 6.0 ); assertCentrality( stressCentrality, "c", 0.0 ); assertCentrality( stressCentrality, "d", 0.0 ); assertCentrality( stressCentrality, "e", 0.0 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); StressCentrality<Double> stressCentrality = new StressCentrality<Double>( getSingleSourceShortestPath(), graph.getAllNodes() ); stressCentrality.calculate(); assertCentrality( stressCentrality, "a", 0.0 ); assertCentrality( stressCentrality, "b", 3.0 ); assertCentrality( stressCentrality, "c", 4.0 ); assertCentrality( stressCentrality, "d", 3.0 ); assertCentrality( stressCentrality, "e", 0.0 ); } @Test public void testStressUpdating() { graph.makeEdgeChain( "a,b,c,d,e,f" ); new StressTest( getSingleSourceShortestPath(), graph.getAllNodes() ) .test(); } class StressTest extends StressCentrality<Double> { public StressTest( SingleSourceShortestPath<Double> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, nodeSet ); } public void test() { // avoid starting the real calculation by mistake this.doneCalculation = true; // set things up Node startNode = graph.getNode( "c" ); singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); processShortestPaths( startNode, singleSourceShortestPath ); Double adjustment = 0.5; // since direction is BOTH assertCentrality( this, "a", 0.0 * adjustment ); assertCentrality( this, "b", 1.0 * adjustment ); assertCentrality( this, "c", 0.0 * adjustment ); assertCentrality( this, "d", 2.0 * adjustment ); assertCentrality( this, "e", 1.0 * adjustment ); assertCentrality( this, "f", 0.0 * adjustment ); } } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_StressCentralityTest.java
3,133
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_BetweennessCentralityTest.java
3,134
{ public Double divideByCost( Double d, Double c ) { return d / c; } public Double divideCost( Double c, Double d ) { return c / d; } } );
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ParallellCentralityCalculationTest.java
3,135
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ParallellCentralityCalculationTest.java
3,136
public class ParallellCentralityCalculationTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } protected void assertCentrality( ShortestPathBasedCentrality<Double,Double> centrality, String nodeId, Double value ) { assertTrue( centrality.getCentrality( graph.getNode( nodeId ) ).equals( value ) ); } @Test public void testPlusShape() { // Make graph graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); SingleSourceShortestPath<Double> singleSourceShortestPath = getSingleSourceShortestPath(); ParallellCentralityCalculation<Double> pcc = new ParallellCentralityCalculation<Double>( singleSourceShortestPath, graph.getAllNodes() ); BetweennessCentrality<Double> betweennessCentrality = new BetweennessCentrality<Double>( singleSourceShortestPath, graph.getAllNodes() ); StressCentrality<Double> stressCentrality = new StressCentrality<Double>( singleSourceShortestPath, graph.getAllNodes() ); ClosenessCentrality<Double> closenessCentrality = new ClosenessCentrality<Double>( singleSourceShortestPath, new DoubleAdder(), 0.0, graph .getAllNodes(), new CostDivider<Double>() { public Double divideByCost( Double d, Double c ) { return d / c; } public Double divideCost( Double c, Double d ) { return c / d; } } ); pcc.addCalculation( betweennessCentrality ); pcc.addCalculation( stressCentrality ); pcc.addCalculation( closenessCentrality ); pcc.calculate(); assertCentrality( betweennessCentrality, "a", 0.0 ); assertCentrality( betweennessCentrality, "b", 6.0 ); assertCentrality( betweennessCentrality, "c", 0.0 ); assertCentrality( betweennessCentrality, "d", 0.0 ); assertCentrality( betweennessCentrality, "e", 0.0 ); assertCentrality( stressCentrality, "a", 0.0 ); assertCentrality( stressCentrality, "b", 6.0 ); assertCentrality( stressCentrality, "c", 0.0 ); assertCentrality( stressCentrality, "d", 0.0 ); assertCentrality( stressCentrality, "e", 0.0 ); assertCentrality( closenessCentrality, "a", 1.0 / 7 ); assertCentrality( closenessCentrality, "b", 1.0 / 4 ); assertCentrality( closenessCentrality, "c", 1.0 / 7 ); assertCentrality( closenessCentrality, "d", 1.0 / 7 ); assertCentrality( closenessCentrality, "e", 1.0 / 7 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ParallellCentralityCalculationTest.java
3,137
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_NetworkRadiusTest.java
3,138
public class NetworkRadiusTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); NetworkRadius<Double> radius = new NetworkRadius<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( radius.getCentrality( null ) == 2.0 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); NetworkRadius<Double> radius = new NetworkRadius<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( radius.getCentrality( null ) == 1.0 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); NetworkRadius<Double> radius = new NetworkRadius<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( radius.getCentrality( null ) == 2.0 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_NetworkRadiusTest.java
3,139
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_NetworkDiameterTest.java
3,140
public class NetworkDiameterTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); NetworkDiameter<Double> diameter = new NetworkDiameter<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( diameter.getCentrality( null ) == 2.0 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); NetworkDiameter<Double> diameter = new NetworkDiameter<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( diameter.getCentrality( null ) == 2.0 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); NetworkDiameter<Double> diameter = new NetworkDiameter<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); assertTrue( diameter.getCentrality( null ) == 4.0 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_NetworkDiameterTest.java
3,141
{ public Double getCost( Relationship relationship, Direction direction ) { String start = graph .getNodeId( relationship.getStartNode() ); String end = graph.getNodeId( relationship.getEndNode() ); if ( direction == Direction.INCOMING ) { // swap String tmp = end; end = start; start = tmp; } Double value = costs.get( start + "," + end ); if ( value == null ) { return 0.0; } return value; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 );
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityTest.java
3,142
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 );
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityTest.java
3,143
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 );
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityTest.java
3,144
public abstract class EigenvectorCentralityTest extends Neo4jAlgoTestCase { protected void assertCentrality( EigenvectorCentralityPower eigenvectorCentralityPower, String nodeId, Double value ) { assertTrue( eigenvectorCentralityPower.getCentrality( graph.getNode( nodeId ) ).equals( value ) ); } /** * @param eigenvectorCentralityPower * @param nodeId * Id of the node * @param value * The correct value * @param precision * Precision factor (ex. 0.01) */ protected void assertApproximateCentrality( EigenvectorCentrality eigenvectorCentrality, String nodeId, Double value, Double precision ) { Double centrality = eigenvectorCentrality.getCentrality( graph .getNode( nodeId ) ); assertTrue( centrality < value * (1 + precision) && centrality > value * (1 - precision) ); } public abstract EigenvectorCentrality getEigenvectorCentrality( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ); @Test public void testRun() { graph.makeEdgeChain( "a,b,c,d" ); graph.makeEdges( "b,a,c,a" ); EigenvectorCentrality eigenvectorCentrality = getEigenvectorCentrality( Direction.OUTGOING, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 ); // eigenvectorCentrality.setMaxIterations( 100 ); assertApproximateCentrality( eigenvectorCentrality, "a", 0.693, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "b", 0.523, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "c", 0.395, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "d", 0.298, 0.01 ); } /** * Same as above, but inverted direction. */ @Test public void testDirection() { graph.makeEdgeChain( "d,c,b,a" ); graph.makeEdges( "a,b,a,c" ); EigenvectorCentrality eigenvectorCentrality = getEigenvectorCentrality( Direction.INCOMING, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 ); // eigenvectorCentrality.setMaxIterations( 100 ); assertApproximateCentrality( eigenvectorCentrality, "a", 0.693, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "b", 0.523, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "c", 0.395, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "d", 0.298, 0.01 ); } /** * Some weighted relationships. */ @Test public void testWeight() { graph.makeEdgeChain( "a,b", "cost", 1.0 ); graph.makeEdgeChain( "b,c", "cost", 1.0 ); graph.makeEdgeChain( "c,d", "cost", 1.0 ); graph.makeEdgeChain( "c,b", "cost", 0.1 ); graph.makeEdgeChain( "c,a", "cost", 0.1 ); EigenvectorCentrality eigenvectorCentrality = getEigenvectorCentrality( Direction.OUTGOING, CommonEvaluators.doubleCostEvaluator( "cost" ), graph .getAllNodes(), graph.getAllEdges(), 0.01 ); // eigenvectorCentrality.setMaxIterations( 100 ); assertApproximateCentrality( eigenvectorCentrality, "a", 0.0851, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "b", 0.244, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "c", 0.456, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "d", 0.852, 0.01 ); } /** * Same network as above, but with direction BOTH and weights in different * directions are given by a map. */ @Test public void testWeightAndDirection() { graph.makeEdgeChain( "a,b" ); graph.makeEdgeChain( "b,c" ); graph.makeEdgeChain( "c,d" ); graph.makeEdgeChain( "c,a" ); final Map<String,Double> costs = new HashMap<String,Double>(); costs.put( "a,b", 1.0 ); costs.put( "b,c", 1.0 ); costs.put( "c,d", 1.0 ); costs.put( "c,b", 0.1 ); costs.put( "c,a", 0.1 ); EigenvectorCentrality eigenvectorCentrality = getEigenvectorCentrality( Direction.BOTH, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { String start = graph .getNodeId( relationship.getStartNode() ); String end = graph.getNodeId( relationship.getEndNode() ); if ( direction == Direction.INCOMING ) { // swap String tmp = end; end = start; start = tmp; } Double value = costs.get( start + "," + end ); if ( value == null ) { return 0.0; } return value; } }, graph.getAllNodes(), graph.getAllEdges(), 0.01 ); // eigenvectorCentrality.setMaxIterations( 100 ); assertApproximateCentrality( eigenvectorCentrality, "a", 0.0851, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "b", 0.244, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "c", 0.456, 0.01 ); assertApproximateCentrality( eigenvectorCentrality, "d", 0.852, 0.01 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityTest.java
3,145
public class EigenvectorCentralityPowerTest extends EigenvectorCentralityTest { @Override public EigenvectorCentrality getEigenvectorCentrality( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ) { return new EigenvectorCentralityPower( relationDirection, costEvaluator, nodeSet, relationshipSet, precision ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityPowerTest.java
3,146
public class EigenvectorCentralityArnoldiTest extends EigenvectorCentralityTest { @Override public EigenvectorCentrality getEigenvectorCentrality( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ) { return new EigenvectorCentralityArnoldi( relationDirection, costEvaluator, nodeSet, relationshipSet, precision ); } @Test @Override public void testWeight() { // This test keeps failing randomly, like 1 in a 100... no time to fix it, so "disabling" it } @Test @Override public void testWeightAndDirection() { // This test keeps failing randomly, like 1 in a 100... no time to fix it, so "disabling" it } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EigenvectorCentralityArnoldiTest.java
3,147
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EccentricityTest.java
3,148
public class EccentricityTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } Eccentricity<Double> getCentralityAlgorithm() { return new Eccentricity<Double>( getSingleSourceShortestPath(), 0.0, graph.getAllNodes(), new DoubleComparator() ); } protected void assertCentrality( Eccentricity<Double> centrality, String nodeId, Double value ) { assertTrue( centrality.getCentrality( graph.getNode( nodeId ) ).equals( value ) ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); Eccentricity<Double> centrality = getCentralityAlgorithm(); assertCentrality( centrality, "a", 2.0 ); assertCentrality( centrality, "b", 2.0 ); assertCentrality( centrality, "c", 2.0 ); assertCentrality( centrality, "d", 2.0 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); Eccentricity<Double> centrality = getCentralityAlgorithm(); assertCentrality( centrality, "a", 2.0 ); assertCentrality( centrality, "b", 1.0 ); assertCentrality( centrality, "c", 2.0 ); assertCentrality( centrality, "d", 2.0 ); assertCentrality( centrality, "e", 2.0 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); Eccentricity<Double> centrality = getCentralityAlgorithm(); assertCentrality( centrality, "a", 4.0 ); assertCentrality( centrality, "b", 3.0 ); assertCentrality( centrality, "c", 2.0 ); assertCentrality( centrality, "d", 3.0 ); assertCentrality( centrality, "e", 4.0 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_EccentricityTest.java
3,149
{ public Double divideByCost( Double d, Double c ) { return d / c; } public Double divideCost( Double c, Double d ) { return c / d; } } );
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ClosenessCentralityTest.java
3,150
{ public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ClosenessCentralityTest.java
3,151
public class ClosenessCentralityTest extends Neo4jAlgoTestCase { protected SingleSourceShortestPath<Double> getSingleSourceShortestPath() { return new SingleSourceShortestPathDijkstra<Double>( 0.0, null, new CostEvaluator<Double>() { public Double getCost( Relationship relationship, Direction direction ) { return 1.0; } }, new org.neo4j.graphalgo.impl.util.DoubleAdder(), new org.neo4j.graphalgo.impl.util.DoubleComparator(), Direction.BOTH, MyRelTypes.R1 ); } // protected SingleSourceShortestPath<Integer> getSingleSourceShortestPath() // { // return new SingleSourceShortestPathBFS( null, MyRelTypes.R1, // Direction.BOTH ); // } ClosenessCentrality<Double> getCentralityAlgorithm() { return new ClosenessCentrality<Double>( getSingleSourceShortestPath(), new DoubleAdder(), 0.0, graph.getAllNodes(), new CostDivider<Double>() { public Double divideByCost( Double d, Double c ) { return d / c; } public Double divideCost( Double c, Double d ) { return c / d; } } ); } protected void assertCentrality( ClosenessCentrality<Double> closenessCentrality, String nodeId, Double value ) { assertTrue( closenessCentrality.getCentrality( graph.getNode( nodeId ) ) .equals( value ) ); } @Test public void testBox() { graph.makeEdgeChain( "a,b,c,d,a" ); ClosenessCentrality<Double> closenessCentrality = getCentralityAlgorithm(); assertCentrality( closenessCentrality, "a", 1.0 / 4 ); assertCentrality( closenessCentrality, "b", 1.0 / 4 ); assertCentrality( closenessCentrality, "c", 1.0 / 4 ); assertCentrality( closenessCentrality, "d", 1.0 / 4 ); } @Test public void testPlusShape() { graph.makeEdgeChain( "a,b,c" ); graph.makeEdgeChain( "d,b,e" ); ClosenessCentrality<Double> closenessCentrality = getCentralityAlgorithm(); assertCentrality( closenessCentrality, "a", 1.0 / 7 ); assertCentrality( closenessCentrality, "b", 1.0 / 4 ); assertCentrality( closenessCentrality, "c", 1.0 / 7 ); assertCentrality( closenessCentrality, "d", 1.0 / 7 ); assertCentrality( closenessCentrality, "e", 1.0 / 7 ); } @Test public void testChain() { graph.makeEdgeChain( "a,b,c,d,e" ); ClosenessCentrality<Double> closenessCentrality = getCentralityAlgorithm(); assertCentrality( closenessCentrality, "a", 1.0 / 10 ); assertCentrality( closenessCentrality, "b", 1.0 / 7 ); assertCentrality( closenessCentrality, "c", 1.0 / 6 ); assertCentrality( closenessCentrality, "d", 1.0 / 7 ); assertCentrality( closenessCentrality, "e", 1.0 / 10 ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_ClosenessCentralityTest.java
3,152
class DependencyTest extends BetweennessCentrality<Double> { public DependencyTest( SingleSourceShortestPath<Double> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, nodeSet ); } public void test() { // avoid starting the real calculation by mistake this.doneCalculation = true; // set things up Node startNode = graph.getNode( "a" ); singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); Map<Node,List<Relationship>> predecessors = singleSourceShortestPath .getPredecessors(); Map<Node,List<Relationship>> successors = Util .reversedPredecessors( predecessors ); PathCounter counter = new Util.PathCounter( predecessors ); // Recursively update the node dependencies getAndUpdateNodeDependency( startNode, true, successors, counter, new HashMap<Node,Double>() ); Double adjustment = 0.5; // since direction is BOTH assertCentrality( this, "a", 0.0 * adjustment ); assertCentrality( this, "b", 2.5 * adjustment ); assertCentrality( this, "c", 2.5 * adjustment ); assertCentrality( this, "d", 4.0 * adjustment ); assertCentrality( this, "e", 3.0 * adjustment ); assertCentrality( this, "f", 0.5 * adjustment ); assertCentrality( this, "g", 0.5 * adjustment ); assertCentrality( this, "h", 0.0 * adjustment ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_BetweennessCentralityTest.java
3,153
OUTPUT { @Override String process( Block block, State state ) { return OutputHelper.passthroughMarker( "query-output", "span", "simpara" ); } @Override boolean isA( List<String> block ) { return isACommentWith( block, "output" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,154
SETUP { @Override String process( Block block, State state ) { return OutputHelper.passthroughMarker( "setup-query", "span", "simpara" ); } @Override boolean isA( List<String> block ) { return isACommentWith( block, "setup" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,155
HIDE { @Override String process( Block block, State state ) { return OutputHelper.passthroughMarker( "hide-query", "span", "simpara" ); } @Override boolean isA( List<String> block ) { return isACommentWith( block, "hide" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,156
public class RecordAccessStub implements RecordAccess, DiffRecordAccess { public static final int SCHEMA_RECORD_TYPE = 255; public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport> CheckerEngine<RECORD, REPORT> engine( final RECORD record, final REPORT report ) { return new Engine<RECORD, REPORT>( report ) { @Override @SuppressWarnings("unchecked") void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ) { checker.checkReference( record, newReference, this, RecordAccessStub.this ); } }; } public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport> CheckerEngine<RECORD, REPORT> engine( final RECORD oldRecord, final RECORD newRecord, REPORT report ) { return new Engine<RECORD, REPORT>( report ) { @Override @SuppressWarnings("unchecked") void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ) { checker.checkReference( newRecord, newReference, this, RecordAccessStub.this ); } }; } private abstract class Engine<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport> implements CheckerEngine<RECORD, REPORT> { private final REPORT report; protected Engine( REPORT report ) { this.report = report; } @Override public <REFERRED extends AbstractBaseRecord> void comparativeCheck( final RecordReference<REFERRED> other, final ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker ) { deferredTasks.add( new Runnable() { @Override @SuppressWarnings("unchecked") public void run() { PendingReferenceCheck mock = mock( PendingReferenceCheck.class ); DeferredReferenceCheck check = new DeferredReferenceCheck( Engine.this, checker ); doAnswer( check ).when( mock ).checkReference( any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); doAnswer( check ).when( mock ).checkDiffReference( any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); other.dispatch( mock ); } } ); } @Override public REPORT report() { return report; } abstract void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ); } private static class DeferredReferenceCheck implements Answer<Void> { private final Engine dispatch; private final ComparativeRecordChecker checker; DeferredReferenceCheck( Engine dispatch, ComparativeRecordChecker checker ) { this.dispatch = dispatch; this.checker = checker; } @Override public Void answer( InvocationOnMock invocation ) throws Throwable { Object[] arguments = invocation.getArguments(); AbstractBaseRecord oldReference = null, newReference; if ( arguments.length == 3 ) { oldReference = (AbstractBaseRecord) arguments[0]; newReference = (AbstractBaseRecord) arguments[1]; } else { newReference = (AbstractBaseRecord) arguments[0]; } dispatch.checkReference( checker, oldReference, newReference ); return null; } } private final Queue<Runnable> deferredTasks = new LinkedList<>(); public void checkDeferred() { for ( Runnable task; null != (task = deferredTasks.poll()); ) { task.run(); } } private final Map<Long, Delta<DynamicRecord>> schemata = new HashMap<>(); private final Map<Long, Delta<NodeRecord>> nodes = new HashMap<>(); private final Map<Long, Delta<RelationshipRecord>> relationships = new HashMap<>(); private final Map<Long, Delta<PropertyRecord>> properties = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> strings = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> arrays = new HashMap<>(); private final Map<Long, Delta<RelationshipTypeTokenRecord>> relationshipTypeTokens = new HashMap<>(); private final Map<Long, Delta<LabelTokenRecord>> labelTokens = new HashMap<>(); private final Map<Long, Delta<PropertyKeyTokenRecord>> propertyKeyTokens = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> relationshipTypeNames = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> nodeDynamicLabels = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> labelNames = new HashMap<>(); private final Map<Long, Delta<DynamicRecord>> propertyKeyNames = new HashMap<>(); private Delta<NeoStoreRecord> graph; private static class Delta<R extends AbstractBaseRecord> { final R oldRecord, newRecord; Delta( R record ) { this.oldRecord = null; this.newRecord = record; } Delta( R oldRecord, R newRecord ) { this.oldRecord = oldRecord; this.newRecord = newRecord; } } private enum Version { PREV { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.oldRecord == null ? delta.newRecord : delta.oldRecord; } }, LATEST { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.newRecord; } }, NEW { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.oldRecord == null ? null : delta.newRecord; } }; abstract <R extends AbstractBaseRecord> R get( Delta<R> delta ); } private static <R extends AbstractBaseRecord> R add( Map<Long, Delta<R>> records, R record ) { records.put( record.getLongId(), new Delta<>( record ) ); return record; } private static <R extends AbstractBaseRecord> void add( Map<Long, Delta<R>> records, R oldRecord, R newRecord ) { records.put( newRecord.getLongId(), new Delta<>( oldRecord, newRecord ) ); } public DynamicRecord addSchema( DynamicRecord schema ) { return add( schemata, schema); } public DynamicRecord addString( DynamicRecord string ) { return add( strings, string ); } public DynamicRecord addArray( DynamicRecord array ) { return add( arrays, array ); } public DynamicRecord addNodeDynamicLabels( DynamicRecord array ) { return add( nodeDynamicLabels, array ); } public DynamicRecord addPropertyKeyName( DynamicRecord name ) { return add( propertyKeyNames, name ); } public DynamicRecord addRelationshipTypeName( DynamicRecord name ) { return add( relationshipTypeNames, name ); } public DynamicRecord addLabelName( DynamicRecord name ) { return add( labelNames, name ); } public <R extends AbstractBaseRecord> R addChange( R oldRecord, R newRecord ) { if ( newRecord instanceof NodeRecord ) { add( nodes, (NodeRecord) oldRecord, (NodeRecord) newRecord ); } else if ( newRecord instanceof RelationshipRecord ) { add( relationships, (RelationshipRecord) oldRecord, (RelationshipRecord) newRecord ); } else if ( newRecord instanceof PropertyRecord ) { add( properties, (PropertyRecord) oldRecord, (PropertyRecord) newRecord ); } else if ( newRecord instanceof DynamicRecord ) { DynamicRecord dyn = (DynamicRecord) newRecord; if ( dyn.getType() == PropertyType.STRING.intValue() ) { add( strings, (DynamicRecord) oldRecord, dyn ); } else if ( dyn.getType() == PropertyType.ARRAY.intValue() ) { add( arrays, (DynamicRecord) oldRecord, dyn ); } else if ( dyn.getType() == SCHEMA_RECORD_TYPE ) { add( schemata, (DynamicRecord) oldRecord, dyn ); } else { throw new IllegalArgumentException( "Invalid dynamic record type" ); } } else if ( newRecord instanceof RelationshipTypeTokenRecord ) { add( relationshipTypeTokens, (RelationshipTypeTokenRecord) oldRecord, (RelationshipTypeTokenRecord) newRecord ); } else if ( newRecord instanceof PropertyKeyTokenRecord ) { add( propertyKeyTokens, (PropertyKeyTokenRecord) oldRecord, (PropertyKeyTokenRecord) newRecord ); } else if ( newRecord instanceof NeoStoreRecord ) { this.graph = new Delta<>( (NeoStoreRecord) oldRecord, (NeoStoreRecord) newRecord ); } else { throw new IllegalArgumentException( "Invalid record type" ); } return newRecord; } public <R extends AbstractBaseRecord> R add( R record ) { if ( record instanceof NodeRecord ) { add( nodes, (NodeRecord) record ); } else if ( record instanceof RelationshipRecord ) { add( relationships, (RelationshipRecord) record ); } else if ( record instanceof PropertyRecord ) { add( properties, (PropertyRecord) record ); } else if ( record instanceof DynamicRecord ) { DynamicRecord dyn = (DynamicRecord) record; if ( dyn.getType() == PropertyType.STRING.intValue() ) { addString( dyn ); } else if ( dyn.getType() == PropertyType.ARRAY.intValue() ) { addArray( dyn ); } else if ( dyn.getType() == SCHEMA_RECORD_TYPE ) { addSchema( dyn ); } else { throw new IllegalArgumentException( "Invalid dynamic record type" ); } } else if ( record instanceof RelationshipTypeTokenRecord ) { add( relationshipTypeTokens, (RelationshipTypeTokenRecord) record ); } else if ( record instanceof PropertyKeyTokenRecord ) { add( propertyKeyTokens, (PropertyKeyTokenRecord) record ); } else if ( record instanceof LabelTokenRecord ) { add( labelTokens, (LabelTokenRecord) record ); } else if ( record instanceof NeoStoreRecord ) { this.graph = new Delta<>( (NeoStoreRecord) record ); } else { throw new IllegalArgumentException( "Invalid record type" ); } return record; } private <R extends AbstractBaseRecord> DirectRecordReference<R> reference( Map<Long, Delta<R>> records, long id, Version version ) { return new DirectRecordReference<>( record( records, id, version ), this ); } private static <R extends AbstractBaseRecord> R record( Map<Long, Delta<R>> records, long id, Version version ) { Delta<R> delta = records.get( id ); if ( delta == null ) { if ( version == Version.NEW ) { return null; } throw new AssertionError( String.format( "Access to record with id=%d not expected.", id ) ); } return version.get( delta ); } @Override public RecordReference<DynamicRecord> schema( long id ) { return reference( schemata, id, Version.LATEST ); } @Override public RecordReference<NodeRecord> node( long id ) { return reference( nodes, id, Version.LATEST ); } @Override public RecordReference<RelationshipRecord> relationship( long id ) { return reference( relationships, id, Version.LATEST ); } @Override public RecordReference<PropertyRecord> property( long id ) { return reference( properties, id, Version.LATEST ); } @Override public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id ) { return reference( relationshipTypeTokens, id, Version.LATEST ); } @Override public RecordReference<PropertyKeyTokenRecord> propertyKey( int id ) { return reference( propertyKeyTokens, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> string( long id ) { return reference( strings, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> array( long id ) { return reference( arrays, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> relationshipTypeName( int id ) { return reference( relationshipTypeNames, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> nodeLabels( long id ) { return reference( nodeDynamicLabels, id, Version.LATEST ); } @Override public RecordReference<LabelTokenRecord> label( int id ) { return reference( labelTokens, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> labelName( int id ) { return reference( labelNames, id, Version.LATEST ); } @Override public RecordReference<DynamicRecord> propertyKeyName( int id ) { return reference( propertyKeyNames, id, Version.LATEST ); } @Override public RecordReference<NeoStoreRecord> graph() { return reference( singletonMap( -1L, graph ), -1, Version.LATEST ); } @Override public RecordReference<NodeRecord> previousNode( long id ) { return reference( nodes, id, Version.PREV ); } @Override public RecordReference<RelationshipRecord> previousRelationship( long id ) { return reference( relationships, id, Version.PREV ); } @Override public RecordReference<PropertyRecord> previousProperty( long id ) { return reference( properties, id, Version.PREV ); } @Override public DynamicRecord changedSchema( long id ) { return record( schemata, id, Version.NEW ); } @Override public NodeRecord changedNode( long id ) { return record( nodes, id, Version.NEW ); } @Override public RelationshipRecord changedRelationship( long id ) { return record( relationships, id, Version.NEW ); } @Override public PropertyRecord changedProperty( long id ) { return record( properties, id, Version.NEW ); } @Override public DynamicRecord changedString( long id ) { return record( strings, id, Version.NEW ); } @Override public DynamicRecord changedArray( long id ) { return record( arrays, id, Version.NEW ); } @Override public RecordReference<NeoStoreRecord> previousGraph() { return reference( singletonMap( -1L, graph ), -1, Version.PREV ); } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,157
public class DirectRecordReference<RECORD extends AbstractBaseRecord> implements RecordReference<RECORD> { final RECORD record; final RecordAccess records; DirectRecordReference( RECORD record, RecordAccess records ) { this.record = record; this.records = records; } @Override public void dispatch( PendingReferenceCheck<RECORD> reporter ) { reporter.checkReference( record, records ); } public RECORD record() { return record; } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DirectRecordReference.java
3,158
public class DirectRecordAccess implements DiffRecordAccess { final StoreAccess access; public DirectRecordAccess( StoreAccess access ) { this.access = access; } @Override public RecordReference<DynamicRecord> schema( long id ) { return referenceTo( access.getSchemaStore(), id ); } @Override public RecordReference<NodeRecord> node( long id ) { return referenceTo( access.getNodeStore(), id ); } @Override public RecordReference<RelationshipRecord> relationship( long id ) { return referenceTo( access.getRelationshipStore(), id ); } @Override public RecordReference<PropertyRecord> property( long id ) { return referenceTo( access.getPropertyStore(), id ); } @Override public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id ) { return referenceTo( access.getRelationshipTypeTokenStore(), id ); } @Override public RecordReference<PropertyKeyTokenRecord> propertyKey( int id ) { return referenceTo( access.getPropertyKeyTokenStore(), id ); } @Override public RecordReference<DynamicRecord> string( long id ) { return referenceTo( access.getStringStore(), id ); } @Override public RecordReference<DynamicRecord> array( long id ) { return referenceTo( access.getArrayStore(), id ); } @Override public RecordReference<DynamicRecord> relationshipTypeName( int id ) { return referenceTo( access.getRelationshipTypeNameStore(), id ); } @Override public RecordReference<DynamicRecord> nodeLabels( long id ) { return referenceTo( access.getNodeDynamicLabelStore(), id ); } @Override public RecordReference<LabelTokenRecord> label( int id ) { return referenceTo( access.getLabelTokenStore(), id ); } @Override public RecordReference<DynamicRecord> labelName( int id ) { return referenceTo( access.getLabelNameStore(), id ); } @Override public RecordReference<DynamicRecord> propertyKeyName( int id ) { return referenceTo( access.getPropertyKeyNameStore(), id ); } <RECORD extends AbstractBaseRecord> RecordReference<RECORD> referenceTo( RecordStore<RECORD> store, long id ) { return new DirectRecordReference<>( store.forceGetRecord( id ), this ); } @Override public RecordReference<NeoStoreRecord> graph() { return new DirectRecordReference<>( access.getRawNeoStore().asRecord(), this ); } @Override public RecordReference<NodeRecord> previousNode( long id ) { return null; } @Override public RecordReference<RelationshipRecord> previousRelationship( long id ) { return null; } @Override public RecordReference<PropertyRecord> previousProperty( long id ) { return null; } @Override public RecordReference<NeoStoreRecord> previousGraph() { return null; } @Override public DynamicRecord changedSchema( long id ) { return null; } @Override public NodeRecord changedNode( long id ) { return null; } @Override public RelationshipRecord changedRelationship( long id ) { return null; } @Override public PropertyRecord changedProperty( long id ) { return null; } @Override public DynamicRecord changedString( long id ) { return null; } @Override public DynamicRecord changedArray( long id ) { return null; } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DirectRecordAccess.java
3,159
private static class DirectDiffRecordReference<RECORD extends AbstractBaseRecord> extends DirectRecordReference<RECORD> { private final RECORD oldRecord; DirectDiffRecordReference( RECORD newRecord, RECORD oldRecord, RecordAccess records ) { super( newRecord, records ); this.oldRecord = oldRecord; } @Override public void dispatch( PendingReferenceCheck<RECORD> reporter ) { reporter.checkDiffReference( oldRecord, record, records ); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DirectDiffRecordAccess.java
3,160
public class DirectDiffRecordAccess extends DirectRecordAccess implements DiffRecordAccess { public DirectDiffRecordAccess( DiffStore access ) { super( access ); } @Override public RecordReference<NeoStoreRecord> graph() { return new DirectRecordReference<>( ((DiffStore) access).getMasterRecord(), this ); } @Override public RecordReference<NodeRecord> previousNode( long id ) { return referenceTo( access.getNodeStore(), id ); } @Override public RecordReference<RelationshipRecord> previousRelationship( long id ) { return referenceTo( access.getRelationshipStore(), id ); } @Override public RecordReference<PropertyRecord> previousProperty( long id ) { return referenceTo( access.getPropertyStore(), id ); } @Override public DynamicRecord changedSchema( long id ) { return ((DiffStore) access).getSchemaStore().getChangedRecord( id ); } @Override public NodeRecord changedNode( long id ) { return ((DiffStore) access).getNodeStore().getChangedRecord( id ); } @Override public RelationshipRecord changedRelationship( long id ) { return ((DiffStore) access).getRelationshipStore().getChangedRecord( id ); } @Override public PropertyRecord changedProperty( long id ) { return ((DiffStore) access).getPropertyStore().getChangedRecord( id ); } @Override public DynamicRecord changedString( long id ) { return ((DiffStore) access).getStringStore().getChangedRecord( id ); } @Override public DynamicRecord changedArray( long id ) { return ((DiffStore) access).getArrayStore().getChangedRecord( id ); } @Override public RecordReference<NeoStoreRecord> previousGraph() { return new DirectRecordReference<>( access.getRawNeoStore().asRecord(), this ); } @Override <RECORD extends AbstractBaseRecord> RecordReference<RECORD> referenceTo( RecordStore<RECORD> store, long id ) { return new DirectDiffRecordReference<>( store.forceGetRecord( id ), store.forceGetRaw( id ), this ); } private static class DirectDiffRecordReference<RECORD extends AbstractBaseRecord> extends DirectRecordReference<RECORD> { private final RECORD oldRecord; DirectDiffRecordReference( RECORD newRecord, RECORD oldRecord, RecordAccess records ) { super( newRecord, records ); this.oldRecord = oldRecord; } @Override public void dispatch( PendingReferenceCheck<RECORD> reporter ) { reporter.checkDiffReference( oldRecord, record, records ); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DirectDiffRecordAccess.java
3,161
public class DiffStore extends StoreAccess implements CommandRecordVisitor { private NeoStoreRecord masterRecord; public DiffStore( NeoStore store ) { super( store ); } @Override protected <R extends AbstractBaseRecord> RecordStore<R> wrapStore( RecordStore<R> store ) { return new DiffRecordStore<>( store ); } @Override protected <FAILURE extends Exception> void apply( RecordStore.Processor<FAILURE> processor, RecordStore<?> store ) throws FAILURE { processor.applyById( store, (DiffRecordStore<?>) store ); } @Override public void visitNode( NodeRecord record ) { getNodeStore().forceUpdateRecord( record ); record = getNodeStore().forceGetRaw( record ); if ( record.inUse() ) { markProperty( record.getNextProp(), record.getId(), -1 ); markRelationship( record.getNextRel() ); } } @Override public void visitRelationship( RelationshipRecord record ) { getRelationshipStore().forceUpdateRecord( record ); record = getRelationshipStore().forceGetRaw( record ); if ( record.inUse() ) { getNodeStore().markDirty( record.getFirstNode() ); getNodeStore().markDirty( record.getSecondNode() ); markProperty( record.getNextProp(), -1, record.getId() ); markRelationship( record.getFirstNextRel() ); markRelationship( record.getFirstPrevRel() ); markRelationship( record.getSecondNextRel() ); markRelationship( record.getSecondPrevRel() ); } } private void markRelationship( long rel ) { if ( !Record.NO_NEXT_RELATIONSHIP.is( rel ) ) getRelationshipStore().markDirty( rel ); } private void markProperty( long prop, long nodeId, long relId ) { if ( !Record.NO_NEXT_PROPERTY.is( prop ) ) { DiffRecordStore<PropertyRecord> store = getPropertyStore(); PropertyRecord record = store.forceGetRaw( prop ); if ( nodeId != -1 ) { record.setNodeId( nodeId ); } else if ( relId != -1 ) { record.setRelId( relId ); } store.updateRecord( record ); } } @Override public void visitProperty( PropertyRecord record ) { getPropertyStore().forceUpdateRecord( record ); updateDynamic( record ); record = getPropertyStore().forceGetRaw( record ); updateDynamic( record ); if ( record.inUse() ) { markProperty( record.getNextProp(), record.getNodeId(), record.getRelId() ); markProperty( record.getPrevProp(), record.getNodeId(), record.getRelId() ); } } private void updateDynamic( PropertyRecord record ) { for ( PropertyBlock block : record.getPropertyBlocks() ) updateDynamic( block.getValueRecords() ); updateDynamic( record.getDeletedRecords() ); } private void updateDynamic( Collection<DynamicRecord> records ) { for ( DynamicRecord record : records ) { DiffRecordStore<DynamicRecord> store = ( record.getType() == PropertyType.STRING.intValue() ) ? getStringStore() : getArrayStore(); store.forceUpdateRecord( record ); if ( !Record.NO_NEXT_BLOCK.is( record.getNextBlock() ) ) getBlockStore(record.getType()).markDirty( record.getNextBlock() ); } } private DiffRecordStore getBlockStore( int type ) { if ( type == PropertyType.STRING.intValue() ) { return getStringStore(); } else { return getArrayStore(); } } @Override public void visitPropertyKeyToken( PropertyKeyTokenRecord record ) { visitNameStore( getPropertyKeyTokenStore(), getPropertyKeyNameStore(), record ); } @Override public void visitRelationshipTypeToken( RelationshipTypeTokenRecord record ) { visitNameStore( getRelationshipTypeTokenStore(), getRelationshipTypeNameStore(), record ); } @Override public void visitLabelToken( LabelTokenRecord record ) { visitNameStore( getLabelTokenStore(), getLabelNameStore(), record ); } private <R extends TokenRecord> void visitNameStore( RecordStore<R> store, RecordStore<DynamicRecord> nameStore, R record ) { store.forceUpdateRecord( record ); for ( DynamicRecord key : record.getNameRecords() ) nameStore.forceUpdateRecord( key ); } @Override public void visitNeoStore( NeoStoreRecord record ) { this.masterRecord = record; } @Override public void visitSchemaRule( Collection<DynamicRecord> records ) { for ( DynamicRecord record : records ) { getSchemaStore().forceUpdateRecord( record ); } } @Override public DiffRecordStore<DynamicRecord> getSchemaStore() { return (DiffRecordStore<DynamicRecord>) super.getSchemaStore(); } @Override public DiffRecordStore<NodeRecord> getNodeStore() { return (DiffRecordStore<NodeRecord>) super.getNodeStore(); } @Override public DiffRecordStore<RelationshipRecord> getRelationshipStore() { return (DiffRecordStore<RelationshipRecord>) super.getRelationshipStore(); } @Override public DiffRecordStore<PropertyRecord> getPropertyStore() { return (DiffRecordStore<PropertyRecord>) super.getPropertyStore(); } @Override public DiffRecordStore<DynamicRecord> getStringStore() { return (DiffRecordStore<DynamicRecord>) super.getStringStore(); } @Override public DiffRecordStore<DynamicRecord> getArrayStore() { return (DiffRecordStore<DynamicRecord>) super.getArrayStore(); } @Override public DiffRecordStore<RelationshipTypeTokenRecord> getRelationshipTypeTokenStore() { return (DiffRecordStore<RelationshipTypeTokenRecord>) super.getRelationshipTypeTokenStore(); } @Override public DiffRecordStore<DynamicRecord> getRelationshipTypeNameStore() { return (DiffRecordStore<DynamicRecord>) super.getRelationshipTypeNameStore(); } @Override public DiffRecordStore<PropertyKeyTokenRecord> getPropertyKeyTokenStore() { return (DiffRecordStore<PropertyKeyTokenRecord>) super.getPropertyKeyTokenStore(); } @Override public DiffRecordStore<DynamicRecord> getPropertyKeyNameStore() { return (DiffRecordStore<DynamicRecord>) super.getPropertyKeyNameStore(); } public NeoStoreRecord getMasterRecord() { return masterRecord; } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DiffStore.java
3,162
@SuppressWarnings( "unchecked" ) private static class DispatchProcessor<FAILURE extends Exception> extends RecordStore.Processor<FAILURE> { private final DiffRecordStore<?> diffStore; private final RecordStore.Processor<FAILURE> processor; DispatchProcessor( DiffRecordStore<?> diffStore, RecordStore.Processor<FAILURE> processor ) { this.diffStore = diffStore; this.processor = processor; } @Override public void processNode( RecordStore<NodeRecord> store, NodeRecord node ) throws FAILURE { processor.processNode( (RecordStore<NodeRecord>) diffStore, node ); } @Override public void processRelationship( RecordStore<RelationshipRecord> store, RelationshipRecord rel ) throws FAILURE { processor.processRelationship( (RecordStore<RelationshipRecord>) diffStore, rel ); } @Override public void processProperty( RecordStore<PropertyRecord> store, PropertyRecord property ) throws FAILURE { processor.processProperty( (RecordStore<PropertyRecord>) diffStore, property ); } @Override public void processString( RecordStore<DynamicRecord> store, DynamicRecord string, @SuppressWarnings( "deprecation") IdType idType ) throws FAILURE { processor.processString( (RecordStore<DynamicRecord>) diffStore, string, idType ); } @Override public void processArray( RecordStore<DynamicRecord> store, DynamicRecord array ) throws FAILURE { processor.processArray( (RecordStore<DynamicRecord>) diffStore, array ); } @Override public void processLabelArrayWithOwner( RecordStore<DynamicRecord> store, DynamicRecord array ) throws FAILURE { processor.processLabelArrayWithOwner( (RecordStore<DynamicRecord>) diffStore, array ); } @Override public void processSchema( RecordStore<DynamicRecord> store, DynamicRecord schema ) throws FAILURE { processor.processSchema( (RecordStore<DynamicRecord>) diffStore, schema ); } @Override public void processRelationshipTypeToken( RecordStore<RelationshipTypeTokenRecord> store, RelationshipTypeTokenRecord record ) throws FAILURE { processor.processRelationshipTypeToken( (RecordStore<RelationshipTypeTokenRecord>) diffStore, record ); } @Override public void processPropertyKeyToken( RecordStore<PropertyKeyTokenRecord> store, PropertyKeyTokenRecord record ) throws FAILURE { processor.processPropertyKeyToken( (RecordStore<PropertyKeyTokenRecord>) diffStore, record ); } @Override public void processLabelToken(RecordStore<LabelTokenRecord> store, LabelTokenRecord record) throws FAILURE { processor.processLabelToken((RecordStore<LabelTokenRecord>) diffStore, record); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DiffRecordStore.java
3,163
public class DiffRecordStore<R extends AbstractBaseRecord> implements RecordStore<R>, Iterable<Long> { private final RecordStore<R> actual; private final Map<Long, R> diff; private long highId = -1; public DiffRecordStore( RecordStore<R> actual ) { this.actual = actual; this.diff = new HashMap<>(); } @Override public String toString() { return "Diff/" + actual; } public void markDirty( long id ) { if ( !diff.containsKey( id ) ) diff.put( id, null ); } public R forceGetRaw( R record ) { if ( diff.containsKey( record.getLongId() ) ) { return actual.forceGetRecord( record.getLongId() ); } else { return record; } } @Override public R forceGetRaw( long id ) { return actual.forceGetRecord( id ); } @Override public int getRecordHeaderSize() { return actual.getRecordHeaderSize(); } @Override public int getRecordSize() { return actual.getRecordSize(); } @Override public File getStorageFileName() { return actual.getStorageFileName(); } @Override public WindowPoolStats getWindowPoolStats() { return actual.getWindowPoolStats(); } @Override public long getHighId() { return Math.max( highId, actual.getHighId() ); } @Override public long getHighestPossibleIdInUse() { return Math.max( highId, actual.getHighestPossibleIdInUse() ); } @Override public long nextId() { return actual.nextId(); } @Override public R getRecord( long id ) { return getRecord( id, false ); } @Override public R forceGetRecord( long id ) { return getRecord( id, true ); } private R getRecord( long id, boolean force ) { R record = diff.get( id ); if ( record == null ) return force ? actual.forceGetRecord( id ) : actual.getRecord( id ); if ( !force && !record.inUse() ) throw new InvalidRecordException( record.getClass().getSimpleName() + "[" + id + "] not in use" ); return record; } @Override public Collection<R> getRecords( long id ) { Collection<R> result = new ArrayList<>(); R record; for ( Long nextId = id; nextId != null; nextId = getNextRecordReference( record ) ) { result.add( record = forceGetRecord( nextId ) ); } return result; } @Override public Long getNextRecordReference( R record ) { return actual.getNextRecordReference( record ); } @Override public void updateRecord( R record ) { if ( record.getLongId() > highId ) highId = record.getLongId(); diff.put( record.getLongId(), record ); } @Override public void forceUpdateRecord( R record ) { updateRecord( record ); } @Override public <FAILURE extends Exception> void accept( RecordStore.Processor<FAILURE> processor, R record ) throws FAILURE { actual.accept( new DispatchProcessor<>( this, processor ), record ); } @Override public Iterator<Long> iterator() { return diff.keySet().iterator(); } @Override public void close() { diff.clear(); actual.close(); } public R getChangedRecord( long id ) { return diff.get( id ); } public boolean hasChanges() { return !diff.isEmpty(); } @SuppressWarnings( "unchecked" ) private static class DispatchProcessor<FAILURE extends Exception> extends RecordStore.Processor<FAILURE> { private final DiffRecordStore<?> diffStore; private final RecordStore.Processor<FAILURE> processor; DispatchProcessor( DiffRecordStore<?> diffStore, RecordStore.Processor<FAILURE> processor ) { this.diffStore = diffStore; this.processor = processor; } @Override public void processNode( RecordStore<NodeRecord> store, NodeRecord node ) throws FAILURE { processor.processNode( (RecordStore<NodeRecord>) diffStore, node ); } @Override public void processRelationship( RecordStore<RelationshipRecord> store, RelationshipRecord rel ) throws FAILURE { processor.processRelationship( (RecordStore<RelationshipRecord>) diffStore, rel ); } @Override public void processProperty( RecordStore<PropertyRecord> store, PropertyRecord property ) throws FAILURE { processor.processProperty( (RecordStore<PropertyRecord>) diffStore, property ); } @Override public void processString( RecordStore<DynamicRecord> store, DynamicRecord string, @SuppressWarnings( "deprecation") IdType idType ) throws FAILURE { processor.processString( (RecordStore<DynamicRecord>) diffStore, string, idType ); } @Override public void processArray( RecordStore<DynamicRecord> store, DynamicRecord array ) throws FAILURE { processor.processArray( (RecordStore<DynamicRecord>) diffStore, array ); } @Override public void processLabelArrayWithOwner( RecordStore<DynamicRecord> store, DynamicRecord array ) throws FAILURE { processor.processLabelArrayWithOwner( (RecordStore<DynamicRecord>) diffStore, array ); } @Override public void processSchema( RecordStore<DynamicRecord> store, DynamicRecord schema ) throws FAILURE { processor.processSchema( (RecordStore<DynamicRecord>) diffStore, schema ); } @Override public void processRelationshipTypeToken( RecordStore<RelationshipTypeTokenRecord> store, RelationshipTypeTokenRecord record ) throws FAILURE { processor.processRelationshipTypeToken( (RecordStore<RelationshipTypeTokenRecord>) diffStore, record ); } @Override public void processPropertyKeyToken( RecordStore<PropertyKeyTokenRecord> store, PropertyKeyTokenRecord record ) throws FAILURE { processor.processPropertyKeyToken( (RecordStore<PropertyKeyTokenRecord>) diffStore, record ); } @Override public void processLabelToken(RecordStore<LabelTokenRecord> store, LabelTokenRecord record) throws FAILURE { processor.processLabelToken((RecordStore<LabelTokenRecord>) diffStore, record); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DiffRecordStore.java
3,164
public class DelegatingRecordAccess implements DiffRecordAccess { private final DiffRecordAccess delegate; public DelegatingRecordAccess( DiffRecordAccess delegate ) { this.delegate = delegate; } @Override public RecordReference<NodeRecord> previousNode( long id ) { return delegate.previousNode( id ); } @Override public RecordReference<RelationshipRecord> previousRelationship( long id ) { return delegate.previousRelationship( id ); } @Override public RecordReference<PropertyRecord> previousProperty( long id ) { return delegate.previousProperty( id ); } @Override public RecordReference<NeoStoreRecord> previousGraph() { return delegate.previousGraph(); } @Override public DynamicRecord changedSchema( long id ) { return delegate.changedSchema( id ); } @Override public NodeRecord changedNode( long id ) { return delegate.changedNode( id ); } @Override public RelationshipRecord changedRelationship( long id ) { return delegate.changedRelationship( id ); } @Override public PropertyRecord changedProperty( long id ) { return delegate.changedProperty( id ); } @Override public DynamicRecord changedString( long id ) { return delegate.changedString( id ); } @Override public DynamicRecord changedArray( long id ) { return delegate.changedArray( id ); } @Override public RecordReference<DynamicRecord> schema( long id ) { return delegate.schema( id ); } @Override public RecordReference<NodeRecord> node( long id ) { return delegate.node( id ); } @Override public RecordReference<RelationshipRecord> relationship( long id ) { return delegate.relationship( id ); } @Override public RecordReference<PropertyRecord> property( long id ) { return delegate.property( id ); } @Override public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id ) { return delegate.relationshipType( id ); } @Override public RecordReference<PropertyKeyTokenRecord> propertyKey( int id ) { return delegate.propertyKey( id ); } @Override public RecordReference<DynamicRecord> string( long id ) { return delegate.string( id ); } @Override public RecordReference<DynamicRecord> array( long id ) { return delegate.array( id ); } @Override public RecordReference<DynamicRecord> relationshipTypeName( int id ) { return delegate.relationshipTypeName( id ); } @Override public RecordReference<DynamicRecord> nodeLabels( long id ) { return delegate.nodeLabels( id ); } @Override public RecordReference<LabelTokenRecord> label( int id ) { return delegate.label( id ); } @Override public RecordReference<DynamicRecord> labelName( int id ) { return delegate.labelName( id ); } @Override public RecordReference<DynamicRecord> propertyKeyName( int id ) { return delegate.propertyKeyName( id ); } @Override public RecordReference<NeoStoreRecord> graph() { return delegate.graph(); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_DelegatingRecordAccess.java
3,165
private static class DirectReferenceMatcher<T extends AbstractBaseRecord> extends TypeSafeMatcher<DirectRecordReference<T>> { private final T record; @SuppressWarnings("unchecked") DirectReferenceMatcher( T record ) { super( (Class) DirectRecordReference.class ); this.record = record; } @Override public boolean matchesSafely( DirectRecordReference<T> reference ) { return record == reference.record(); } @Override public void describeTo( Description description ) { description.appendText( DirectRecordReference.class.getName() ) .appendText( "( " ).appendValue( record ).appendText( " )" ); } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_CacheSmallStoresRecordAccessTest.java
3,166
public class CacheSmallStoresRecordAccessTest { @Test public void shouldDelegateLookupForMostStores() throws Exception { // given DiffRecordAccess delegate = mock( DiffRecordAccess.class ); CacheSmallStoresRecordAccess recordAccess = new CacheSmallStoresRecordAccess( delegate, null, null, null ); // when recordAccess.node( 42 ); recordAccess.relationship( 2001 ); recordAccess.property( 2468 ); recordAccess.string( 666 ); recordAccess.array( 11 ); // then verify( delegate ).node( 42 ); verify( delegate ).relationship( 2001 ); verify( delegate ).property( 2468 ); verify( delegate ).string( 666 ); verify( delegate ).array( 11 ); } @Test public void shouldServePropertyKeysAndRelationshipLabelsFromSuppliedArrayCaches() throws Exception { // given DiffRecordAccess delegate = mock( DiffRecordAccess.class ); PropertyKeyTokenRecord propertyKey0 = new PropertyKeyTokenRecord( 0 ); PropertyKeyTokenRecord propertyKey2 = new PropertyKeyTokenRecord( 2 ); PropertyKeyTokenRecord propertyKey1 = new PropertyKeyTokenRecord( 1 ); RelationshipTypeTokenRecord relationshipType0 = new RelationshipTypeTokenRecord( 0 ); RelationshipTypeTokenRecord relationshipType1 = new RelationshipTypeTokenRecord( 1 ); RelationshipTypeTokenRecord relationshipType2 = new RelationshipTypeTokenRecord( 2 ); LabelTokenRecord label0 = new LabelTokenRecord( 0 ); LabelTokenRecord label1 = new LabelTokenRecord( 1 ); LabelTokenRecord label2 = new LabelTokenRecord( 2 ); CacheSmallStoresRecordAccess recordAccess = new CacheSmallStoresRecordAccess( delegate, new PropertyKeyTokenRecord[]{ propertyKey0, propertyKey1, propertyKey2, }, new RelationshipTypeTokenRecord[]{ relationshipType0, relationshipType1, relationshipType2, }, new LabelTokenRecord[]{ label0, label1, label2, } ); // when assertThat( recordAccess.propertyKey( 0 ), isDirectReferenceTo( propertyKey0 ) ); assertThat( recordAccess.propertyKey( 1 ), isDirectReferenceTo( propertyKey1 ) ); assertThat( recordAccess.propertyKey( 2 ), isDirectReferenceTo( propertyKey2 ) ); assertThat( recordAccess.relationshipType( 0 ), isDirectReferenceTo( relationshipType0 ) ); assertThat( recordAccess.relationshipType( 1 ), isDirectReferenceTo( relationshipType1 ) ); assertThat( recordAccess.relationshipType( 2 ), isDirectReferenceTo( relationshipType2 ) ); assertThat( recordAccess.label( 0 ), isDirectReferenceTo( label0 ) ); assertThat( recordAccess.label( 1 ), isDirectReferenceTo( label1 ) ); assertThat( recordAccess.label( 2 ), isDirectReferenceTo( label2 ) ); // then verifyZeroInteractions( delegate ); } @SuppressWarnings("unchecked") private static <T extends AbstractBaseRecord> Matcher<RecordReference<T>> isDirectReferenceTo( T record ) { return (Matcher) new DirectReferenceMatcher<T>( record ); } private static class DirectReferenceMatcher<T extends AbstractBaseRecord> extends TypeSafeMatcher<DirectRecordReference<T>> { private final T record; @SuppressWarnings("unchecked") DirectReferenceMatcher( T record ) { super( (Class) DirectRecordReference.class ); this.record = record; } @Override public boolean matchesSafely( DirectRecordReference<T> reference ) { return record == reference.record(); } @Override public void describeTo( Description description ) { description.appendText( DirectRecordReference.class.getName() ) .appendText( "( " ).appendValue( record ).appendText( " )" ); } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_CacheSmallStoresRecordAccessTest.java
3,167
public class CacheSmallStoresRecordAccess extends DelegatingRecordAccess { private final PropertyKeyTokenRecord[] propertyKeys; private final RelationshipTypeTokenRecord[] relationshipTypes; private final LabelTokenRecord[] labels; public CacheSmallStoresRecordAccess( DiffRecordAccess delegate, PropertyKeyTokenRecord[] propertyKeys, RelationshipTypeTokenRecord[] relationshipTypes, LabelTokenRecord[] labels ) { super(delegate); this.propertyKeys = propertyKeys; this.relationshipTypes = relationshipTypes; this.labels = labels; } @Override public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id ) { if ( id < relationshipTypes.length ) { return new DirectRecordReference<>( relationshipTypes[id], this ); } else { return super.relationshipType( id ); } } @Override public RecordReference<PropertyKeyTokenRecord> propertyKey( int id ) { if ( id < propertyKeys.length ) { return new DirectRecordReference<>( propertyKeys[id], this ); } else { return super.propertyKey( id ); } } @Override public RecordReference<LabelTokenRecord> label( int id ) { if ( id < labels.length ) { return new DirectRecordReference<>( labels[id], this ); } else { return super.label( id ); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_CacheSmallStoresRecordAccess.java
3,168
public class PendingReferenceCheckTest { // given { @SuppressWarnings("unchecked") ConsistencyReporter.ReportHandler handler = new ConsistencyReporter.ReportHandler( mock( InconsistencyReport.class ), mock( ConsistencyReporter.ProxyFactory.class ), RecordType.PROPERTY, new PropertyRecord( 0 ) ); this.referenceCheck = new PendingReferenceCheck<>( handler, mock( ComparativeRecordChecker.class ) ); } private final PendingReferenceCheck<PropertyRecord> referenceCheck; @Test public void shouldAllowSkipAfterSkip() throws Exception { // given referenceCheck.skip(); // when referenceCheck.skip(); } @Test public void shouldAllowSkipAfterCheckReference() throws Exception { // given referenceCheck.checkReference( new PropertyRecord( 0 ), null ); // when referenceCheck.skip(); } @Test public void shouldAllowSkipAfterCheckDiffReference() throws Exception { // given referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); // when referenceCheck.skip(); } @Test public void shouldNotAllowCheckReferenceAfterSkip() throws Exception { // given referenceCheck.skip(); // when try { referenceCheck.checkReference( new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } @Test public void shouldNotAllowCheckDiffReferenceAfterSkip() throws Exception { // given referenceCheck.skip(); // when try { referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } @Test public void shouldNotAllowCheckReferenceAfterCheckReference() throws Exception { // given referenceCheck.checkReference( new PropertyRecord( 0 ), null ); // when try { referenceCheck.checkReference( new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } @Test public void shouldNotAllowCheckDiffReferenceAfterCheckReference() throws Exception { // given referenceCheck.checkReference( new PropertyRecord( 0 ), null ); // when try { referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } @Test public void shouldNotAllowCheckReferenceAfterCheckDiffReference() throws Exception { // given referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); // when try { referenceCheck.checkReference( new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } @Test public void shouldNotAllowCheckDiffReferenceAfterCheckDiffReference() throws Exception { // given referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); // when try { referenceCheck.checkDiffReference( new PropertyRecord( 0 ), new PropertyRecord( 0 ), null ); fail( "expected exception" ); } // then catch ( IllegalStateException expected ) { assertEquals( "Reference has already been checked.", expected.getMessage() ); } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_PendingReferenceCheckTest.java
3,169
public class PendingReferenceCheck<REFERENCED extends AbstractBaseRecord> { private CheckerEngine engine; private final ComparativeRecordChecker checker; PendingReferenceCheck( CheckerEngine engine, ComparativeRecordChecker checker ) { this.engine = engine; this.checker = checker; } @Override public synchronized String toString() { if ( engine == null ) { return String.format( "CompletedReferenceCheck{%s}", checker ); } else { return ConsistencyReporter.pendingCheckToString( engine, checker ); } } public void checkReference( REFERENCED referenced, RecordAccess records ) { ConsistencyReporter.dispatchReference( engine(), checker, referenced, records ); } public void checkDiffReference( REFERENCED oldReferenced, REFERENCED newReferenced, RecordAccess records ) { ConsistencyReporter.dispatchChangeReference( engine(), checker, oldReferenced, newReferenced, records ); } public synchronized void skip() { if ( engine != null ) { ConsistencyReporter.dispatchSkip( engine ); engine = null; } } private synchronized CheckerEngine engine() { if ( engine == null ) { throw new IllegalStateException( "Reference has already been checked." ); } try { return engine; } finally { engine = null; } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_PendingReferenceCheck.java
3,170
{ @Override public boolean matchesSafely( String item ) { return item.endsWith( suffix ); } @Override public void describeTo( Description description ) { description.appendText( "String ending with " ).appendValue( suffix ); } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_MessageConsistencyLoggerTest.java
3,171
public class MessageConsistencyLoggerTest { // given private final InconsistencyMessageLogger logger; private final StringWriter writer; { writer = new StringWriter(); logger = new InconsistencyMessageLogger( StringLogger.wrap( writer ) ); } @Test public void shouldFormatErrorForRecord() throws Exception { // when logger.error( RecordType.NEO_STORE, new NeoStoreRecord(), "sample message", 1, 2 ); // then assertTextEquals( "ERROR: sample message", "NeoStoreRecord[used=true,nextProp=-1]", "Inconsistent with: 1 2" ); } @Test public void shouldFlattenAMultiLineMessageToASingleLine() throws Exception { // when logger.error( RecordType.NEO_STORE, new NeoStoreRecord(), "multiple\n line\r\n message", 1, 2 ); // then assertTextEquals( "ERROR: multiple line message", "NeoStoreRecord[used=true,nextProp=-1]", "Inconsistent with: 1 2" ); } @Test public void shouldFormatWarningForRecord() throws Exception { // when logger.warning( RecordType.NEO_STORE, new NeoStoreRecord(), "sample message", 1, 2 ); // then assertTextEquals( "WARNING: sample message", "NeoStoreRecord[used=true,nextProp=-1]", "Inconsistent with: 1 2" ); } @Test public void shouldFormatErrorForChangedRecord() throws Exception { // when logger.error( RecordType.NEO_STORE, new NeoStoreRecord(), new NeoStoreRecord(), "sample message", 1, 2 ); // then assertTextEquals( "ERROR: sample message", "- NeoStoreRecord[used=true,nextProp=-1]", "+ NeoStoreRecord[used=true,nextProp=-1]", "Inconsistent with: 1 2" ); } @Test public void shouldFormatWarningForChangedRecord() throws Exception { // when logger.warning( RecordType.NEO_STORE, new NeoStoreRecord(), new NeoStoreRecord(), "sample message", 1, 2 ); // then assertTextEquals( "WARNING: sample message", "- NeoStoreRecord[used=true,nextProp=-1]", "+ NeoStoreRecord[used=true,nextProp=-1]", "Inconsistent with: 1 2" ); } private void assertTextEquals( String firstLine, String... lines ) { StringBuilder expected = new StringBuilder( firstLine ); for ( String line : lines ) { expected.append( LINE_SEPARATOR ).append( TAB ).append( line ); } assertThat( writer.toString(), endsWith( expected.append( LINE_SEPARATOR ).toString() ) ); } private static Matcher<String> endsWith( final String suffix ) { return new TypeSafeMatcher<String>() { @Override public boolean matchesSafely( String item ) { return item.endsWith( suffix ); } @Override public void describeTo( Description description ) { description.appendText( "String ending with " ).appendValue( suffix ); } }; } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_MessageConsistencyLoggerTest.java
3,172
public class InconsistencyReport implements InconsistencyLogger { private final InconsistencyLogger logger; private final ConsistencySummaryStatistics summary; public InconsistencyReport( InconsistencyLogger logger, ConsistencySummaryStatistics summary ) { this.logger = logger; this.summary = summary; } @Override public void error( RecordType recordType, AbstractBaseRecord record, String message, Object[] args ) { logger.error( recordType, record, message, args ); } @Override public void error( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message, Object[] args ) { logger.error( recordType, oldRecord, newRecord, message, args ); } @Override public void warning( RecordType recordType, AbstractBaseRecord record, String message, Object[] args ) { logger.warning( recordType, record, message, args ); } @Override public void warning( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message, Object[] args ) { logger.warning( recordType, oldRecord, newRecord, message, args ); } void updateSummary( RecordType type, int errors, int warnings ) { summary.update( type, errors, warnings ); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_InconsistencyReport.java
3,173
public class InconsistencyMessageLogger implements InconsistencyLogger { private final StringLogger logger; private static final String ERROR = "ERROR:", WARNING = "WARNING:"; public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); public static final String TAB = "\t"; public InconsistencyMessageLogger( StringLogger logger ) { this.logger = logger; } @Override public void error( RecordType recordType, AbstractBaseRecord record, String message, Object... args ) { log( record( entry( ERROR, message ), record ), args ); } @Override public void error( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message, Object... args ) { log( diff( entry( ERROR, message ), oldRecord, newRecord ), args ); } @Override public void warning( RecordType recordType, AbstractBaseRecord record, String message, Object... args ) { log( record( entry( WARNING, message ), record ), args ); } @Override public void warning( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message, Object... args ) { log( diff( entry( WARNING, message ), oldRecord, newRecord ), args ); } private static StringBuilder entry( String type, String message ) { StringBuilder log = new StringBuilder( type ); for ( String line : message.split( "\n" ) ) { log.append( ' ' ).append( line.trim() ); } return log; } private static StringBuilder record( StringBuilder log, AbstractBaseRecord record ) { return log.append( LINE_SEPARATOR ).append( TAB ).append( record ); } private static StringBuilder diff( StringBuilder log, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord ) { return log.append( LINE_SEPARATOR ).append( TAB ).append( "- " ).append( oldRecord ) .append( LINE_SEPARATOR ).append( TAB ).append( "+ " ).append( newRecord ); } private void log( StringBuilder log, Object[] args ) { if ( args != null && args.length > 0 ) { log.append( LINE_SEPARATOR ).append( TAB ).append( "Inconsistent with:" ); for ( Object arg : args ) { log.append( ' ' ).append( arg ); } } logger.logMessage( log.toString(), true ); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_InconsistencyMessageLogger.java
3,174
public class ConsistencySummaryStatistics { private final Map<RecordType, AtomicInteger> inconsistentRecordCount = new EnumMap<RecordType, AtomicInteger>( RecordType.class ); private final AtomicInteger totalInconsistencyCount = new AtomicInteger(); private final AtomicLong errorCount = new AtomicLong(), warningCount = new AtomicLong(); public ConsistencySummaryStatistics() { for ( RecordType recordType : RecordType.values() ) { inconsistentRecordCount.put( recordType, new AtomicInteger() ); } } @Override public String toString() { StringBuilder result = new StringBuilder( getClass().getSimpleName() ).append( '{' ); result.append( "\n\tNumber of errors: " ).append( errorCount ); result.append( "\n\tNumber of warnings: " ).append( warningCount ); for ( Map.Entry<RecordType, AtomicInteger> entry : inconsistentRecordCount.entrySet() ) { if ( entry.getValue().get() != 0 ) { result.append( "\n\tNumber of inconsistent " ) .append( entry.getKey() ).append( " records: " ).append( entry.getValue() ); } } return result.append( "\n}" ).toString(); } public boolean isConsistent() { return totalInconsistencyCount.get() == 0; } public int getInconsistencyCountForRecordType( RecordType recordType ) { return inconsistentRecordCount.get( recordType ).get(); } public int getTotalInconsistencyCount() { return totalInconsistencyCount.get(); } void update( RecordType recordType, int errors, int warnings ) { if ( errors > 0 ) { inconsistentRecordCount.get( recordType ).incrementAndGet(); totalInconsistencyCount.incrementAndGet(); errorCount.addAndGet( errors ); } if ( warnings > 0 ) { warningCount.addAndGet( warnings ); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencySummaryStatistics.java
3,175
public static class TestReportLifecycle { @Test public void shouldSummarizeStatisticsAfterCheck() { // given ConsistencySummaryStatistics summary = mock( ConsistencySummaryStatistics.class ); @SuppressWarnings("unchecked") ConsistencyReporter.ReportHandler handler = new ConsistencyReporter.ReportHandler( new InconsistencyReport( mock( InconsistencyLogger.class ), summary ), mock( ConsistencyReporter.ProxyFactory.class ), RecordType.PROPERTY, new PropertyRecord( 0 ) ); // when handler.updateSummary(); // then verify( summary ).update( RecordType.PROPERTY, 0, 0 ); verifyNoMoreInteractions( summary ); } @Test @SuppressWarnings("unchecked") public void shouldOnlySummarizeStatisticsWhenAllReferencesAreChecked() { // given ConsistencySummaryStatistics summary = mock( ConsistencySummaryStatistics.class ); ConsistencyReporter.ReportHandler handler = new ConsistencyReporter.ReportHandler( new InconsistencyReport( mock( InconsistencyLogger.class ), summary ), mock( ConsistencyReporter.ProxyFactory.class ), RecordType.PROPERTY, new PropertyRecord( 0 ) ); RecordReference<PropertyRecord> reference = mock( RecordReference.class ); ComparativeRecordChecker<PropertyRecord, PropertyRecord, ConsistencyReport.PropertyConsistencyReport> checker = mock( ComparativeRecordChecker.class ); handler.comparativeCheck( reference, checker ); ArgumentCaptor<PendingReferenceCheck<PropertyRecord>> captor = (ArgumentCaptor) ArgumentCaptor.forClass( PendingReferenceCheck.class ); verify( reference ).dispatch( captor.capture() ); PendingReferenceCheck pendingRefCheck = captor.getValue(); // when handler.updateSummary(); // then verifyZeroInteractions( summary ); // when pendingRefCheck.skip(); // then verify( summary ).update( RecordType.PROPERTY, 0, 0 ); verifyNoMoreInteractions( summary ); } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java
3,176
public class FilteringRecordAccess extends DelegatingRecordAccess { private final Set<MultiPassStore> potentiallySkippableStores = new HashSet<>(); private final int iPass; private final long recordsPerPass; private final MultiPassStore currentStore; public FilteringRecordAccess( DiffRecordAccess delegate, final int iPass, final long recordsPerPass, MultiPassStore currentStore, MultiPassStore... potentiallySkippableStores ) { super( delegate ); this.iPass = iPass; this.recordsPerPass = recordsPerPass; this.currentStore = currentStore; this.potentiallySkippableStores.addAll( asList( potentiallySkippableStores ) ); } enum Mode { SKIP, FILTER } @Override public RecordReference<NodeRecord> node( long id ) { if ( shouldSkip( id, MultiPassStore.NODES ) ) { return skipReference(); } return super.node( id ); } @Override public RecordReference<RelationshipRecord> relationship( long id ) { if ( shouldSkip( id, MultiPassStore.RELATIONSHIPS ) ) { return skipReference(); } return super.relationship( id ); } @Override public RecordReference<PropertyRecord> property( long id ) { if ( shouldSkip( id, MultiPassStore.PROPERTIES ) ) { return skipReference(); } return super.property( id ); } @Override public RecordReference<DynamicRecord> string( long id ) { if ( shouldSkip( id, MultiPassStore.STRINGS ) ) { return skipReference(); } return super.string( id ); } @Override public RecordReference<DynamicRecord> array( long id ) { if ( shouldSkip( id, MultiPassStore.ARRAYS ) ) { return skipReference(); } return super.array( id ); } private boolean shouldSkip( long id, MultiPassStore store ) { return potentiallySkippableStores.contains( store ) && (!isCurrentStore( store ) || !recordInCurrentPass( id, iPass, recordsPerPass )); } private boolean isCurrentStore( MultiPassStore store ) { return currentStore == store; } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_FilteringRecordAccess.java
3,177
{ @Override @SuppressWarnings("unchecked") void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ) { checker.checkReference( record, newReference, this, RecordAccessStub.this ); } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,178
{ @Override public Statement apply( final Statement base, org.junit.runner.Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch ( Throwable failure ) { System.err.println( "Failure in " + TestAllReportMessages.this + ": " + failure ); throw failure; } } }; } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java
3,179
{ @Override @SuppressWarnings("unchecked") void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ) { checker.checkReference( newRecord, newReference, this, RecordAccessStub.this ); } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,180
public class IndexEntry extends Abstract64BitRecord { public IndexEntry( long nodeId ) { super( nodeId ); setInUse( true ); } @Override public String toString() { return "IndexEntry[nodeId=" + getId() + "]"; } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_synthetic_IndexEntry.java
3,181
public class StubPageReplacementStrategy implements PageReplacementStrategy { @Override public <PAYLOAD, PAGE extends Page<PAYLOAD>> PAYLOAD acquire( PAGE page, Storage<PAYLOAD, PAGE> storage ) throws PageLoadFailureException { return page.payload = storage.load( page ); } @Override public <PAYLOAD> void forceEvict( Page<PAYLOAD> page ) { page.evict(); } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_StubPageReplacementStrategy.java
3,182
public class PageLoadFailureException extends Exception { public PageLoadFailureException( IOException e ) { super(e); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_paging_PageLoadFailureException.java
3,183
public abstract class Page<T> { boolean referenced = false; TemporalUtility utility = TemporalUtility.UNKNOWN; CachedPageList currentList = null; Page prevPage; Page nextPage; T payload; Page moveToTailOf( CachedPageList targetList ) { if ( currentList != null ) { if ( prevPage != null ) { prevPage.nextPage = nextPage; } if ( nextPage != null ) { nextPage.prevPage = prevPage; } if ( currentList.head == this ) { currentList.head = nextPage; } if ( currentList.tail == this ) { currentList.tail = prevPage; } currentList.decrementSize(); } if ( targetList != null ) { prevPage = targetList.tail; if ( prevPage != null ) { prevPage.nextPage = this; } targetList.tail = this; if ( targetList.head == null ) { targetList.head = this; } targetList.incrementSize(); } nextPage = null; currentList = targetList; return this; } Page setReferenced() { referenced = true; return this; } Page clearReference() { referenced = false; return this; } Page setUtility( TemporalUtilityCounter counter, TemporalUtility utility ) { counter.decrement( this.utility ); counter.increment( this.utility = utility ); return this; } final void evict() { try { if ( payload != null ) { evict( payload ); } } finally { payload = null; } } protected abstract void evict( T payload ); @Override public String toString() { return String.format( "Page{payload=%s, inAList=%b}", payload, currentList != null ); } protected abstract void hit(); }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_paging_Page.java
3,184
class SpyPage extends Page<Integer> { private final int address; public SpyPage( int address ) { this.address = address; } @Override protected void evict( Integer address ) { events.add( "E" + address ); } @Override protected void hit() { hitCount++; if ( linear ) { linHit++; } else { rndHit++; } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_CartTest.java
3,185
private static class StorageSpy implements PageReplacementStrategy.Storage<Integer, StorageSpy.SpyPage> { SpyPage[] pages; StorageSpy( int pageCount ) { pages = new SpyPage[pageCount]; for ( int i = 0; i < pages.length; i++ ) { pages[i] = new SpyPage( i ); } } List<String> events = new ArrayList<String>(); int hitCount, loadCount; boolean linear; int linHit, linMiss; int rndHit, rndMiss; @Override public Integer load( StorageSpy.SpyPage page ) { events.add( "L" + page.address ); loadCount++; if ( linear ) { linMiss++; } else { rndMiss++; } return page.address; } public SpyPage page( int address ) { return pages[address]; } class SpyPage extends Page<Integer> { private final int address; public SpyPage( int address ) { this.address = address; } @Override protected void evict( Integer address ) { events.add( "E" + address ); } @Override protected void hit() { hitCount++; if ( linear ) { linHit++; } else { rndHit++; } } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_CartTest.java
3,186
public class CartTest { @Test public void linearScanWithSingleHitPerWindowLeadsToFifoEviction() throws Exception { // given int capacity = 10; StorageSpy storage = new StorageSpy( capacity * 2 ); Cart cart = new Cart( capacity ); // when for ( int i = 0; i < capacity * 2; i++ ) { cart.acquire( storage.page( i ), storage ); } // then assertArrayEquals( new String[]{ "L0", "L1", "L2", "L3", "L4", "L5", "L6", "L7", "L8", "L9", "E0", "L10", "E1", "L11", "E2", "L12", "E3", "L13", "E4", "L14", "E5", "L15", "E6", "L16", "E7", "L17", "E8", "L18", "E9", "L19" }, storage.events.toArray() ); } @Test public void reverseLinearScanWithSingleHitPerWindowLeadsToFifoEviction() throws Exception { // given int capacity = 10; StorageSpy storage = new StorageSpy( capacity * 2 ); Cart cart = new Cart( capacity ); // when for ( int i = capacity * 2 - 1; i >= 0; i-- ) { cart.acquire( storage.page( i ), storage ); } // then assertArrayEquals( new String[]{ "L19", "L18", "L17", "L16", "L15", "L14", "L13", "L12", "L11", "L10", "E19", "L9", "E18", "L8", "E17", "L7", "E16", "L6", "E15", "L5", "E14", "L4", "E13", "L3", "E12", "L2", "E11", "L1", "E10", "L0", }, storage.events.toArray() ); } @Test public void frequentlyAccessedPagesDoNotGetEvicted() throws Exception { // given int capacity = 10; StorageSpy storage = new StorageSpy( capacity * 2 ); Cart cart = new Cart( capacity ); // when for ( int i = 0; i < capacity * 2; i++ ) { // even number pages accessed more frequently cart.acquire( storage.page( (i / 2) * 2 ), storage ); // background access of even and odd numbered pages cart.acquire( storage.page( i ), storage ); } // then assertThat( storage.events, not( hasItem( "E0" ) ) ); assertThat( storage.events, hasItem( "E1" ) ); assertThat( storage.events, not( hasItem( "E2" ) ) ); assertThat( storage.events, hasItem( "E3" ) ); assertThat( storage.events, not( hasItem( "E4" ) ) ); assertThat( storage.events, hasItem( "E5" ) ); assertThat( storage.events, not( hasItem( "E6" ) ) ); assertThat( storage.events, hasItem( "E7" ) ); assertThat( storage.events, not( hasItem( "E8" ) ) ); assertThat( storage.events, hasItem( "E9" ) ); } @Test public void linearPlusRandom() throws Exception { // given int capacity = 100; StorageSpy storage = new StorageSpy( capacity * 2 ); int randoms = 4; int pageSize = 10; Cart cart = new Cart( capacity ); // when Random random = new Random(); for ( int i = 0; i < capacity * 2; i++ ) { // background access of even and odd numbered pages for ( int j = 0; j < pageSize; j++ ) { storage.linear = true; cart.acquire( storage.page( i ), storage ); storage.linear = false; for ( int k = 0; k < randoms; k++ ) { cart.acquire( storage.page( random.nextInt( capacity * 2 ) ), storage ); } } } // then assertTrue( storage.linMiss * pageSize <= (storage.linMiss + storage.linHit) ); assertTrue( storage.rndMiss * 2 <= (storage.rndMiss + storage.rndHit) * 1.05 ); } @Test public void shouldReloadAfterForcedEviction() throws Exception { // given int capacity = 10; StorageSpy storage = new StorageSpy( capacity * 2 ); Cart cart = new Cart( capacity ); // when cart.acquire( storage.page( 0 ), storage ); cart.forceEvict( storage.page( 0 ) ); cart.acquire( storage.page( 0 ), storage ); // then assertArrayEquals( new String[]{ "L0", "E0", "L0" }, storage.events.toArray() ); } private static class StorageSpy implements PageReplacementStrategy.Storage<Integer, StorageSpy.SpyPage> { SpyPage[] pages; StorageSpy( int pageCount ) { pages = new SpyPage[pageCount]; for ( int i = 0; i < pages.length; i++ ) { pages[i] = new SpyPage( i ); } } List<String> events = new ArrayList<String>(); int hitCount, loadCount; boolean linear; int linHit, linMiss; int rndHit, rndMiss; @Override public Integer load( StorageSpy.SpyPage page ) { events.add( "L" + page.address ); loadCount++; if ( linear ) { linMiss++; } else { rndMiss++; } return page.address; } public SpyPage page( int address ) { return pages[address]; } class SpyPage extends Page<Integer> { private final int address; public SpyPage( int address ) { this.address = address; } @Override protected void evict( Integer address ) { events.add( "E" + address ); } @Override protected void hit() { hitCount++; if ( linear ) { linHit++; } else { rndHit++; } } } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_CartTest.java
3,187
public class Cart implements PageReplacementStrategy, TemporalUtilityCounter { private final int capacity; private int p = 0; private int q = 0; private int shortTermUtilityPageCount = 0; private int longTermUtilityPageCount = 0; private CachedPageList recencyCache = new CachedPageList(); private CachedPageList recencyHistory = new CachedPageList(); private CachedPageList frequencyCache = new CachedPageList(); private CachedPageList frequencyHistory = new CachedPageList(); public Cart( int capacity ) { this.capacity = capacity; } @Override public <PAYLOAD,PAGE extends Page<PAYLOAD>> PAYLOAD acquire( PAGE page, Storage<PAYLOAD,PAGE> storage ) throws PageLoadFailureException { if ( page.currentList == recencyCache || page.currentList == frequencyCache ) { page.setReferenced(); page.hit(); return page.payload; } if ( recencyCache.size() + frequencyCache.size() == capacity ) { // cache full replace(); // history replace if ( page.currentList != recencyHistory && page.currentList != frequencyHistory && recencyHistory.size() + frequencyHistory.size() == capacity + 1 ) { if ( recencyHistory.size() > max( 0, q ) || frequencyHistory.size() == 0 ) { recencyHistory.removeHead().setUtility( this, TemporalUtility.UNKNOWN ); } else { frequencyHistory.removeHead().setUtility( this, TemporalUtility.UNKNOWN ); } } } if ( page.currentList == recencyHistory ) { p = min( p + max( 1, shortTermUtilityPageCount / recencyHistory.size() ), capacity ); page.clearReference().moveToTailOf( recencyCache ).setUtility( this, TemporalUtility.LONG_TERM ); } else if ( page.currentList == frequencyHistory ) { p = max( p - max( 1, longTermUtilityPageCount / frequencyHistory.size() ), 0 ); page.clearReference().moveToTailOf( recencyCache ).setUtility( this, TemporalUtility.LONG_TERM ); if ( frequencyCache.size() + frequencyHistory.size() + recencyCache.size() - shortTermUtilityPageCount >= capacity ) { q = min( q + 1, 2 * capacity - recencyCache.size() ); } } else { page.moveToTailOf( recencyCache ).setUtility( this, TemporalUtility.SHORT_TERM ); } return page.payload = storage.load( page ); } @Override public <PAYLOAD> void forceEvict( Page<PAYLOAD> page ) { page.clearReference().setUtility( this, TemporalUtility.UNKNOWN ).moveToTailOf( null ).evict(); } private void replace() { while ( frequencyCache.size() > 0 && frequencyCache.head.referenced ) { frequencyCache.head.clearReference().moveToTailOf( recencyCache ); if ( frequencyCache.size() + frequencyHistory.size() + recencyHistory.size() - shortTermUtilityPageCount >= capacity ) { q = min( q + 1, 2 * capacity - recencyCache.size() ); } } while ( recencyCache.size() > 0 && (recencyCache.head.utility == TemporalUtility.LONG_TERM || recencyCache.head.referenced) ) { if ( recencyCache.head.referenced ) { Page page = recencyCache.head.clearReference().moveToTailOf( recencyCache ); if ( recencyCache.size() > min( p + 1, recencyHistory.size() ) && page.utility == TemporalUtility.SHORT_TERM ) { page.setUtility( this, TemporalUtility.LONG_TERM ); } } else { recencyCache.head.clearReference().moveToTailOf( frequencyCache ); q = max( q - 1, capacity - recencyCache.size() ); } } if ( recencyCache.size() >= max( 1, p ) ) { recencyCache.head.evict(); recencyCache.head.moveToTailOf( recencyHistory ).setUtility( this, TemporalUtility.LONG_TERM ); } else { frequencyCache.head.evict(); frequencyCache.head.moveToTailOf( frequencyHistory ).setUtility( this, TemporalUtility.SHORT_TERM ); } } private static int min( int i1, int i2 ) { return i1 < i2 ? i1 : i2; } private static int max( int i1, int i2 ) { return i1 > i2 ? i1 : i2; } @Override public void increment( TemporalUtility utility ) { switch ( utility ) { case SHORT_TERM: shortTermUtilityPageCount++; break; case LONG_TERM: longTermUtilityPageCount++; break; } } @Override public void decrement( TemporalUtility utility ) { switch ( utility ) { case SHORT_TERM: shortTermUtilityPageCount--; break; case LONG_TERM: longTermUtilityPageCount--; break; } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_paging_Cart.java
3,188
static class BasicPage extends Page<Integer> { @Override protected void evict( Integer payload ) { } @Override protected void hit() { } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_CachedPageListTest.java
3,189
public class CachedPageListTest { @Test public void insertPagesByMovingThemFromNullListToTailOfARealList() throws Exception { // given CachedPageList list = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); Page page3 = new BasicPage(); Page page4 = new BasicPage(); Page page5 = new BasicPage(); // when page1.moveToTailOf( list ); page2.moveToTailOf( list ); page3.moveToTailOf( list ); page4.moveToTailOf( list ); page5.moveToTailOf( list ); // then assertEquals( 5, list.size() ); assertSame( page1, list.head ); assertSame( page5, list.tail ); assertSame( list, page1.currentList ); assertSame( list, page2.currentList ); assertSame( list, page3.currentList ); assertSame( list, page4.currentList ); assertSame( list, page5.currentList ); assertNull( page1.prevPage ); assertSame( page1, page2.prevPage ); assertSame( page2, page3.prevPage ); assertSame( page3, page4.prevPage ); assertSame( page4, page5.prevPage ); assertSame( page2, page1.nextPage ); assertSame( page3, page2.nextPage ); assertSame( page4, page3.nextPage ); assertSame( page5, page4.nextPage ); assertNull( page5.nextPage ); } @Test public void moveSingletonToEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page = new BasicPage(); page.moveToTailOf( list1 ); // when page.moveToTailOf( list2 ); // then assertEquals( 0, list1.size() ); assertNull( list1.head ); assertNull( list1.tail ); assertEquals( 1, list2.size() ); assertSame( page, list2.head ); assertSame( page, list2.tail ); assertSame( list2, page.currentList ); assertNull( page.prevPage ); assertNull( page.nextPage ); } @Test public void moveHeadOfTwoPageListToEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); page1.moveToTailOf( list1 ); page2.moveToTailOf( list1 ); // when page1.moveToTailOf( list2 ); // then assertEquals( 1, list1.size() ); assertSame( page2, list1.head ); assertSame( page2, list1.tail ); assertSame( list1, page2.currentList ); assertNull( page2.prevPage ); assertNull( page2.nextPage ); assertEquals( 1, list2.size() ); assertSame( page1, list2.head ); assertSame( page1, list2.tail ); assertSame( list2, page1.currentList ); assertNull( page1.prevPage ); assertNull( page1.nextPage ); } @Test public void moveTailOfTwoPageListToEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); page1.moveToTailOf( list1 ); page2.moveToTailOf( list1 ); // when page2.moveToTailOf( list2 ); // then assertEquals( 1, list1.size() ); assertSame( page1, list1.head ); assertSame( page1, list1.tail ); assertSame( list1, page1.currentList ); assertNull( page1.prevPage ); assertNull( page1.nextPage ); assertEquals( 1, list2.size() ); assertSame( page2, list2.head ); assertSame( page2, list2.tail ); assertSame( list2, page2.currentList ); assertNull( page2.prevPage ); assertNull( page2.nextPage ); } @Test public void moveMiddleOfThreePageListToEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); Page page3 = new BasicPage(); page1.moveToTailOf( list1 ); page2.moveToTailOf( list1 ); page3.moveToTailOf( list1 ); // when page2.moveToTailOf( list2 ); // then assertEquals( 2, list1.size() ); assertSame( page1, list1.head ); assertSame( page3, list1.tail ); assertSame( list1, page1.currentList ); assertSame( list1, page3.currentList ); assertNull( page1.prevPage ); assertSame( page1, page3.prevPage ); assertSame( page3, page1.nextPage ); assertNull( page3.nextPage ); assertEquals( 1, list2.size() ); assertSame( page2, list2.head ); assertSame( page2, list2.tail ); assertSame( list2, page2.currentList ); assertNull( page2.prevPage ); assertNull( page2.nextPage ); } @Test public void moveMiddleOfLongListToEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); Page page3 = new BasicPage(); Page page4 = new BasicPage(); Page page5 = new BasicPage(); page1.moveToTailOf( list1 ); page2.moveToTailOf( list1 ); page3.moveToTailOf( list1 ); page4.moveToTailOf( list1 ); page5.moveToTailOf( list1 ); // when page3.moveToTailOf( list2 ); // then assertEquals( 4, list1.size() ); assertSame( page1, list1.head ); assertSame( page5, list1.tail ); assertSame( list1, page1.currentList ); assertSame( list1, page2.currentList ); assertSame( list1, page4.currentList ); assertSame( list1, page5.currentList ); assertNull( page1.prevPage ); assertSame( page1, page2.prevPage ); assertSame( page2, page4.prevPage ); assertSame( page4, page5.prevPage ); assertSame( page2, page1.nextPage ); assertSame( page4, page2.nextPage ); assertSame( page5, page4.nextPage ); assertNull( page5.nextPage ); assertEquals( 1, list2.size() ); assertSame( page3, list2.head ); assertSame( page3, list2.tail ); assertSame( list2, page3.currentList ); assertNull( page3.prevPage ); assertNull( page3.nextPage ); } @Test public void moveMiddleOfLongListToNonEmptyList() throws Exception { // given CachedPageList list1 = new CachedPageList(); CachedPageList list2 = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); Page page3 = new BasicPage(); Page page4 = new BasicPage(); Page page5 = new BasicPage(); page1.moveToTailOf( list1 ); page2.moveToTailOf( list1 ); page3.moveToTailOf( list1 ); page4.moveToTailOf( list1 ); page5.moveToTailOf( list1 ); Page page6 = new BasicPage(); Page page7 = new BasicPage(); page6.moveToTailOf( list2 ); page7.moveToTailOf( list2 ); // when page3.moveToTailOf( list2 ); // then assertEquals( 4, list1.size() ); assertSame( page1, list1.head ); assertSame( page5, list1.tail ); assertSame( list1, page1.currentList ); assertSame( list1, page2.currentList ); assertSame( list1, page4.currentList ); assertSame( list1, page5.currentList ); assertNull( page1.prevPage ); assertSame( page1, page2.prevPage ); assertSame( page2, page4.prevPage ); assertSame( page4, page5.prevPage ); assertSame( page2, page1.nextPage ); assertSame( page4, page2.nextPage ); assertSame( page5, page4.nextPage ); assertNull( page5.nextPage ); assertEquals( 3, list2.size() ); assertSame( page6, list2.head ); assertSame( page3, list2.tail ); assertSame( list2, page6.currentList ); assertSame( list2, page7.currentList ); assertSame( list2, page3.currentList ); assertNull( page6.prevPage ); assertSame( page6, page7.prevPage ); assertSame( page7, page3.prevPage ); assertSame( page7, page6.nextPage ); assertSame( page3, page7.nextPage ); assertNull( page3.nextPage ); } @Test public void shouldRemoveHeadOfSingletonList() throws Exception { // given CachedPageList list = new CachedPageList(); Page page = new BasicPage(); page.moveToTailOf( list ); // when Page removedPage = list.removeHead(); // then assertSame( page, removedPage ); assertEquals( 0, list.size() ); assertNull( list.head ); assertNull( list.tail ); assertNull( page.currentList ); assertNull( page.prevPage ); assertNull( page.nextPage ); } @Test public void shouldRemoveHeadOfTwoPageList() throws Exception { // given CachedPageList list = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); page1.moveToTailOf( list ); page2.moveToTailOf( list ); // when Page removedPage = list.removeHead(); // then assertSame( page1, removedPage ); assertEquals( 1, list.size() ); assertSame( page2, list.head ); assertSame( page2, list.tail ); assertNull( page1.currentList ); assertNull( page1.prevPage ); assertNull( page1.nextPage ); assertSame( list, page2.currentList ); assertNull( page2.prevPage ); assertNull( page2.nextPage ); } @Test public void shouldRemoveHeadOfLongList() throws Exception { // given CachedPageList list = new CachedPageList(); Page page1 = new BasicPage(); Page page2 = new BasicPage(); Page page3 = new BasicPage(); page1.moveToTailOf( list ); page2.moveToTailOf( list ); page3.moveToTailOf( list ); // when Page removedPage = list.removeHead(); // then assertSame( page1, removedPage ); assertEquals( 2, list.size() ); assertSame( page2, list.head ); assertSame( page3, list.tail ); assertNull( page1.currentList ); assertNull( page1.prevPage ); assertNull( page1.nextPage ); assertSame( list, page2.currentList ); assertSame( list, page3.currentList ); assertNull( page2.prevPage ); assertSame( page2, page3.prevPage ); assertSame( page3, page2.nextPage ); assertNull( page3.nextPage ); } static class BasicPage extends Page<Integer> { @Override protected void evict( Integer payload ) { } @Override protected void hit() { } } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_paging_CachedPageListTest.java
3,190
class CachedPageList { Page head, tail; int size = 0; public int size() { return size; } public Page removeHead() { Page removedPage = head; head.moveToTailOf( null ); return removedPage; } public void incrementSize() { size++; } public void decrementSize() { size--; } @Override public String toString() { return String.format( "CachedPageList{head=%s, tail=%s, size=%d}", head, tail, size ); } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_paging_CachedPageList.java
3,191
class SkippingReference<RECORD extends AbstractBaseRecord> implements RecordReference<RECORD> { @SuppressWarnings("unchecked") public static <RECORD extends AbstractBaseRecord> SkippingReference<RECORD> skipReference() { return INSTANCE; } @Override public void dispatch( PendingReferenceCheck<RECORD> reporter ) { reporter.skip(); } @Override public String toString() { return "SkipReference"; } private static final SkippingReference INSTANCE = new SkippingReference(); private SkippingReference() { // singleton } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_RecordReference.java
3,192
NEW { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.oldRecord == null ? null : delta.newRecord; } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,193
LATEST { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.newRecord; } },
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,194
PREV { @Override <R extends AbstractBaseRecord> R get( Delta<R> delta ) { return delta.oldRecord == null ? delta.newRecord : delta.oldRecord; } },
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,195
{ @Override @SuppressWarnings("unchecked") public void run() { PendingReferenceCheck mock = mock( PendingReferenceCheck.class ); DeferredReferenceCheck check = new DeferredReferenceCheck( Engine.this, checker ); doAnswer( check ).when( mock ).checkReference( any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); doAnswer( check ).when( mock ).checkDiffReference( any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); other.dispatch( mock ); } } );
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,196
private abstract class Engine<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport> implements CheckerEngine<RECORD, REPORT> { private final REPORT report; protected Engine( REPORT report ) { this.report = report; } @Override public <REFERRED extends AbstractBaseRecord> void comparativeCheck( final RecordReference<REFERRED> other, final ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker ) { deferredTasks.add( new Runnable() { @Override @SuppressWarnings("unchecked") public void run() { PendingReferenceCheck mock = mock( PendingReferenceCheck.class ); DeferredReferenceCheck check = new DeferredReferenceCheck( Engine.this, checker ); doAnswer( check ).when( mock ).checkReference( any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); doAnswer( check ).when( mock ).checkDiffReference( any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ), any( RecordAccess.class ) ); other.dispatch( mock ); } } ); } @Override public REPORT report() { return report; } abstract void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference ); }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,197
private static class Delta<R extends AbstractBaseRecord> { final R oldRecord, newRecord; Delta( R record ) { this.oldRecord = null; this.newRecord = record; } Delta( R oldRecord, R newRecord ) { this.oldRecord = oldRecord; this.newRecord = newRecord; } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,198
private static class DeferredReferenceCheck implements Answer<Void> { private final Engine dispatch; private final ComparativeRecordChecker checker; DeferredReferenceCheck( Engine dispatch, ComparativeRecordChecker checker ) { this.dispatch = dispatch; this.checker = checker; } @Override public Void answer( InvocationOnMock invocation ) throws Throwable { Object[] arguments = invocation.getArguments(); AbstractBaseRecord oldReference = null, newReference; if ( arguments.length == 3 ) { oldReference = (AbstractBaseRecord) arguments[0]; newReference = (AbstractBaseRecord) arguments[1]; } else { newReference = (AbstractBaseRecord) arguments[0]; } dispatch.checkReference( checker, oldReference, newReference ); return null; } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_RecordAccessStub.java
3,199
{ @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch ( Throwable failure ) { System.err.println( "Failure in " + TestAllReportMessages.this + ": " + failure ); throw failure; } } };
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java