Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
3,200
|
@RunWith(Parameterized.class)
public static class TestAllReportMessages implements Answer
{
@Test
@SuppressWarnings("unchecked")
public void shouldLogInconsistency() throws Exception
{
// given
InconsistencyReport report = mock( InconsistencyReport.class );
ConsistencyReport.Reporter reporter = new ConsistencyReporter(
mock( DiffRecordAccess.class ), report );
// when
reportMethod.invoke( reporter, parameters( reportMethod ) );
// then
if ( method.getAnnotation( ConsistencyReport.Warning.class ) == null )
{
if ( reportMethod.getName().endsWith( "Change" ) )
{
verify( report ).error( any( RecordType.class ),
any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
else
{
verify( report ).error( any( RecordType.class ),
any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
}
else
{
if ( reportMethod.getName().endsWith( "Change" ) )
{
verify( report ).warning( any( RecordType.class ),
any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
else
{
verify( report ).warning( any( RecordType.class ),
any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
}
}
private final Method reportMethod;
private final Method method;
public TestAllReportMessages( Method reportMethod, Method method )
{
this.reportMethod = reportMethod;
this.method = method;
}
@Parameterized.Parameters(name="{1}")
public static List<Object[]> methods()
{
ArrayList<Object[]> methods = new ArrayList<>();
for ( Method reporterMethod : ConsistencyReport.Reporter.class.getMethods() )
{
Type[] parameterTypes = reporterMethod.getGenericParameterTypes();
ParameterizedType checkerParameter = (ParameterizedType) parameterTypes[parameterTypes.length - 1];
Class reportType = (Class) checkerParameter.getActualTypeArguments()[1];
for ( Method method : reportType.getMethods() )
{
methods.add( new Object[]{reporterMethod, method} );
}
}
return methods;
}
@Rule
public final TestRule logFailure = new TestRule()
{
@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;
}
}
};
}
};
@Override
public String toString()
{
return format( "report.%s( %s{ reporter.%s(); } )",
reportMethod.getName(), signatureOf( reportMethod ), method.getName() );
}
private static String signatureOf( Method reportMethod )
{
if ( reportMethod.getParameterTypes().length == 2 )
{
return "record, RecordCheck( reporter )";
}
else
{
return "oldRecord, newRecord, RecordCheck( reporter )";
}
}
private Object[] parameters( Method method )
{
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = new Object[parameterTypes.length];
for ( int i = 0; i < parameters.length; i++ )
{
parameters[i] = parameter( parameterTypes[i] );
}
return parameters;
}
private Object parameter( Class<?> type )
{
if ( type == RecordType.class )
{
return RecordType.STRING_PROPERTY;
}
if ( type == RecordCheck.class )
{
return mockChecker();
}
if ( type == NodeRecord.class )
{
return new NodeRecord( 0, 1, 2 );
}
if ( type == RelationshipRecord.class )
{
return new RelationshipRecord( 0, 1, 2, 3 );
}
if ( type == PropertyRecord.class )
{
return new PropertyRecord( 0 );
}
if ( type == PropertyKeyTokenRecord.class )
{
return new PropertyKeyTokenRecord( 0 );
}
if ( type == PropertyBlock.class )
{
return new PropertyBlock();
}
if ( type == RelationshipTypeTokenRecord.class )
{
return new RelationshipTypeTokenRecord( 0 );
}
if ( type == LabelTokenRecord.class )
{
return new LabelTokenRecord( 0 );
}
if ( type == DynamicRecord.class )
{
return new DynamicRecord( 0 );
}
if ( type == NeoStoreRecord.class )
{
return new NeoStoreRecord();
}
if ( type == LabelScanDocument.class )
{
return new LabelScanDocument( new LuceneNodeLabelRange( 0, new long[] {}, new long[][] {} ) );
}
if ( type == IndexEntry.class )
{
return new IndexEntry( 0 );
}
if ( type == SchemaRule.Kind.class )
{
return SchemaRule.Kind.INDEX_RULE;
}
if ( type == IndexRule.class )
{
return IndexRule.indexRule( 1, 2, 3, new SchemaIndexProvider.Descriptor( "provider", "version" ) );
}
if ( type == long.class )
{
return 12L;
}
if ( type == Object.class )
{
return "object";
}
throw new IllegalArgumentException( format( "Don't know how to provide parameter of type %s", type.getName() ) );
}
@SuppressWarnings("unchecked")
private RecordCheck mockChecker()
{
RecordCheck checker = mock( RecordCheck.class );
doAnswer( this ).when( checker ).check( any( AbstractBaseRecord.class ),
any( CheckerEngine.class ),
any( RecordAccess.class ) );
doAnswer( this ).when( checker ).checkChange( any( AbstractBaseRecord.class ),
any( AbstractBaseRecord.class ),
any( CheckerEngine.class ),
any( DiffRecordAccess.class ) );
return checker;
}
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
Object[] arguments = invocation.getArguments();
ConsistencyReport report = ((CheckerEngine)arguments[arguments.length - 2]).report();
try
{
return method.invoke( report, parameters( method ) );
}
catch ( IllegalArgumentException ex )
{
throw new IllegalArgumentException(
format( "%s.%s#%s(...)", report, method.getDeclaringClass().getSimpleName(), method.getName() ),
ex );
}
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java
|
3,201
|
TEXT
{
@Override
boolean isA( List<String> block )
{
return true;
}
@Override
String process( Block block, State state )
{
return StringUtils.join( block.lines, CypherDoc.EOL ) + CypherDoc.EOL;
}
};
| false
|
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
|
3,202
|
public class IndexRules
{
public static Iterable<IndexRule> loadAllIndexRules( final RecordStore<DynamicRecord> schemaStore )
{
return new Iterable<IndexRule>()
{
@Override
public Iterator<IndexRule> iterator()
{
return new SchemaStorage( schemaStore ).allIndexRules();
}
};
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_schema_IndexRules.java
|
3,203
|
public class LabelScanCheck implements RecordCheck<LabelScanDocument, ConsistencyReport.LabelScanConsistencyReport>
{
@Override
public void check( LabelScanDocument record, CheckerEngine<LabelScanDocument,
ConsistencyReport.LabelScanConsistencyReport> engine, RecordAccess records )
{
NodeLabelRange range = record.getNodeLabelRange();
for ( long nodeId : range.nodes() )
{
engine.comparativeCheck( records.node( nodeId ), new NodeInUseWithCorrectLabelsCheck<LabelScanDocument,ConsistencyReport.LabelScanConsistencyReport>(
record.getNodeLabelRange().labels( nodeId ) ) );
}
}
@Override
public void checkChange( LabelScanDocument oldRecord, LabelScanDocument newRecord,
CheckerEngine<LabelScanDocument,
ConsistencyReport.LabelScanConsistencyReport> engine, DiffRecordAccess records )
{
check( newRecord, engine, records );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_labelscan_LabelScanCheck.java
|
3,204
|
public class IndexIterator implements BoundedIterable<Long>
{
private final IndexAccessor indexAccessor;
private BoundedIterable<Long> indexReader;
public IndexIterator( IndexAccessor indexAccessor )
{
this.indexAccessor = indexAccessor;
}
@Override
public long maxCount()
{
try ( BoundedIterable<Long> reader = indexAccessor.newAllEntriesReader() )
{
return reader.maxCount();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
@Override
public void close() throws IOException
{
if ( indexReader != null )
{
indexReader.close();
}
}
@Override
public Iterator<Long> iterator()
{
if ( indexReader == null )
{
indexReader = indexAccessor.newAllEntriesReader();
}
return indexReader.iterator();
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_index_IndexIterator.java
|
3,205
|
public class IndexEntryProcessor implements RecordProcessor<Long>
{
private final ConsistencyReporter reporter;
private final IndexCheck indexCheck;
public IndexEntryProcessor( ConsistencyReporter reporter, IndexCheck indexCheck )
{
this.reporter = reporter;
this.indexCheck = indexCheck;
}
@Override
public void process( Long nodeId )
{
reporter.forIndexEntry( new IndexEntry( nodeId ), indexCheck );
}
@Override
public void close()
{
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_index_IndexEntryProcessor.java
|
3,206
|
public class IndexAccessors implements Closeable
{
private final Map<Long,IndexAccessor> accessors = new HashMap<>();
private final List<IndexRule> indexRules = new ArrayList<>();
public IndexAccessors( SchemaIndexProvider provider, RecordStore<DynamicRecord> schemaStore )
throws IOException, MalformedSchemaRuleException
{
Iterator<IndexRule> rules = loadAllIndexRules( schemaStore ).iterator();
for (; ; )
{
try
{
if ( rules.hasNext() )
{
// we intentionally only check indexes that are online since
// - populating indexes will be rebuilt on next startup
// - failed indexes have to be dropped by the user anyways
IndexRule indexRule = rules.next();
if ( InternalIndexState.ONLINE == provider.getInitialState( indexRule.getId() ) )
{
indexRules.add( indexRule );
}
}
else
{
break;
}
}
catch ( Exception e )
{
// ignore; inconsistencies of the schema store are specifically handled elsewhere.
}
}
for ( IndexRule indexRule : indexRules )
{
accessors.put(indexRule.getId(), provider.getOnlineAccessor(
indexRule.getId(), new IndexConfiguration( indexRule.isConstraintIndex() ) ) );
}
}
public IndexAccessor accessorFor(IndexRule indexRule)
{
return accessors.get( indexRule.getId() );
}
// TODO: return pair of rules and accessor
public Iterable<IndexRule> rules()
{
return indexRules;
}
@Override
public void close() throws IOException
{
for ( IndexAccessor accessor : accessors.values() )
{
accessor.close();
}
accessors.clear();
indexRules.clear();
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_index_IndexAccessors.java
|
3,207
|
@Service.Implementation(TransactionInterceptorProvider.class)
public class VerifyingTransactionInterceptorProvider extends CheckingTransactionInterceptorProvider
{
public static final String NAME = "verifying";
public VerifyingTransactionInterceptorProvider()
{
super( NAME );
}
@Override
DiffCheck createChecker( String mode, StringLogger logger )
{
if ( "true".equalsIgnoreCase( mode ) )
{
return new IncrementalDiffCheck( logger );
}
return null;
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_VerifyingTransactionInterceptorProvider.java
|
3,208
|
DIFF
{
@Override
DiffCheck createChecker( StringLogger logger )
{
return new IncrementalDiffCheck( logger );
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_InconsistencyLoggingTransactionInterceptorProvider.java
|
3,209
|
FULL
{
@Override
DiffCheck createChecker( StringLogger logger )
{
return new FullDiffCheck( logger );
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_InconsistencyLoggingTransactionInterceptorProvider.java
|
3,210
|
@Service.Implementation(TransactionInterceptorProvider.class)
public class InconsistencyLoggingTransactionInterceptorProvider extends CheckingTransactionInterceptorProvider
{
public static final String NAME = "inconsistency" + "log";
public InconsistencyLoggingTransactionInterceptorProvider()
{
super( NAME );
}
public enum CheckerMode
{
FULL
{
@Override
DiffCheck createChecker( StringLogger logger )
{
return new FullDiffCheck( logger );
}
},
DIFF
{
@Override
DiffCheck createChecker( StringLogger logger )
{
return new IncrementalDiffCheck( logger );
}
};
abstract DiffCheck createChecker( StringLogger logger );
}
@Override
DiffCheck createChecker( String mode, StringLogger logger )
{
final CheckerMode checkerMode;
try
{
checkerMode = CheckerMode.valueOf( mode.toUpperCase() );
}
catch ( Exception e )
{
return null;
}
return new LoggingDiffCheck( checkerMode.createChecker( logger ), logger );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_InconsistencyLoggingTransactionInterceptorProvider.java
|
3,211
|
abstract class CheckingTransactionInterceptorProvider extends TransactionInterceptorProvider
{
public CheckingTransactionInterceptorProvider( String name )
{
super( name );
}
abstract DiffCheck createChecker( String mode, StringLogger logger );
@Override
public CheckingTransactionInterceptor create( XaDataSource ds, String options,
DependencyResolver dependencyResolver )
{
if ( !(ds instanceof NeoStoreXaDataSource) || !(options != null) )
{
return null;
}
String[] config = options.split( ";" );
String mode = config[0];
Map<String, String> parameters = new HashMap<>();
for ( int i = 1; i < config.length; i++ )
{
String[] parts = config[i].split( "=" );
parameters.put( parts[0].toLowerCase(), parts.length == 1 ? "true" : parts[1] );
}
StringLogger logger = dependencyResolver.resolveDependency( StringLogger.class );
DiffCheck check = createChecker( mode, logger );
if ( check == null )
{
return null;
}
else
{
String log = parameters.get( "log" );
return new CheckingTransactionInterceptor( check, (NeoStoreXaDataSource) ds );
}
}
@Override
public CheckingTransactionInterceptor create( TransactionInterceptor next, XaDataSource ds, String options,
DependencyResolver dependencyResolver )
{
CheckingTransactionInterceptor interceptor = create( ds, options, dependencyResolver );
if ( interceptor != null )
{
interceptor.setNext( next );
}
return interceptor;
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_CheckingTransactionInterceptorProvider.java
|
3,212
|
class CheckingTransactionInterceptor implements TransactionInterceptor
{
private TransactionInterceptor next;
private LogEntry.Start startEntry;
private LogEntry.Commit commitEntry;
private final DiffStore diffs;
private final DiffCheck checker;
CheckingTransactionInterceptor( DiffCheck checker, NeoStoreXaDataSource dataSource )
{
this.checker = checker;
this.diffs = new DiffStore( dataSource.getNeoStore() );
}
void setNext( TransactionInterceptor next )
{
this.next = next;
}
@Override
public void setStartEntry( LogEntry.Start startEntry )
{
this.startEntry = startEntry;
if ( next != null )
{
next.setStartEntry( startEntry );
}
}
@Override
public void setCommitEntry( LogEntry.Commit commitEntry )
{
this.commitEntry = commitEntry;
if ( next != null )
{
next.setCommitEntry( commitEntry );
}
}
@Override
public void visitNode( NodeRecord record )
{
diffs.visitNode( record );
if ( next != null )
{
next.visitNode( record );
}
}
@Override
public void visitRelationship( RelationshipRecord record )
{
diffs.visitRelationship( record );
if ( next != null )
{
next.visitRelationship( record );
}
}
@Override
public void visitProperty( PropertyRecord record )
{
diffs.visitProperty( record );
if ( next != null )
{
next.visitProperty( record );
}
}
@Override
public void visitRelationshipTypeToken( RelationshipTypeTokenRecord record )
{
diffs.visitRelationshipTypeToken( record );
if ( next != null )
{
next.visitRelationshipTypeToken( record );
}
}
@Override
public void visitLabelToken( LabelTokenRecord record )
{
diffs.visitLabelToken( record );
if ( next != null )
{
next.visitLabelToken( record );
}
}
@Override
public void visitPropertyKeyToken( PropertyKeyTokenRecord record )
{
diffs.visitPropertyKeyToken( record );
if ( next != null )
{
next.visitPropertyKeyToken( record );
}
}
@Override
public void visitNeoStore( NeoStoreRecord record )
{
diffs.visitNeoStore( record );
if ( next != null )
{
next.visitNeoStore( record );
}
}
@Override
public void visitSchemaRule( Collection<DynamicRecord> records )
{
diffs.visitSchemaRule( records );
if ( next != null )
{
next.visitSchemaRule( records );
}
}
@Override
public void complete() throws ConsistencyCheckingError
{
// TODO: move the logging code from VerifyingTransactionInterceptor to this class, then remove that class
try
{
checker.check( diffs );
}
catch ( InconsistentStoreException inconsistency )
{
throw new ConsistencyCheckingError( startEntry, commitEntry, inconsistency.summary() );
}
catch ( ConsistencyCheckIncompleteException e )
{
// TODO: is this sufficient handling? -- probably add it to messages.log
e.printStackTrace();
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_intercept_CheckingTransactionInterceptor.java
|
3,213
|
class StoreProcessor extends AbstractStoreProcessor
{
private final ConsistencyReport.Reporter report;
StoreProcessor( ConsistencyReport.Reporter report )
{
this.report = report;
}
@Override
protected void checkNode( RecordStore<NodeRecord> store, NodeRecord node,
RecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> checker )
{
report.forNodeChange( store.forceGetRaw( node ), node, checker );
}
@Override
protected void checkRelationship( RecordStore<RelationshipRecord> store, RelationshipRecord rel,
RecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> checker )
{
report.forRelationshipChange( store.forceGetRaw( rel ), rel, checker );
}
@Override
protected void checkProperty( RecordStore<PropertyRecord> store, PropertyRecord property,
RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> checker )
{
report.forPropertyChange( store.forceGetRaw( property ), property, checker );
}
@Override
protected void checkRelationshipTypeToken( RecordStore<RelationshipTypeTokenRecord> store,
RelationshipTypeTokenRecord record,
RecordCheck<RelationshipTypeTokenRecord,
ConsistencyReport.RelationshipTypeConsistencyReport> checker )
{
report.forRelationshipTypeNameChange( store.forceGetRaw( record ), record, checker );
}
@Override
protected void checkLabelToken( RecordStore<LabelTokenRecord> store, LabelTokenRecord record,
RecordCheck<LabelTokenRecord,
ConsistencyReport.LabelTokenConsistencyReport> checker )
{
report.forLabelNameChange( store.forceGetRaw( record ), record, checker );
}
@Override
protected void checkPropertyKeyToken( RecordStore<PropertyKeyTokenRecord> store, PropertyKeyTokenRecord record,
RecordCheck<PropertyKeyTokenRecord,
ConsistencyReport.PropertyKeyTokenConsistencyReport> checker )
{
report.forPropertyKeyChange( store.forceGetRaw( record ), record, checker );
}
@Override
protected void checkDynamic( RecordType type, RecordStore<DynamicRecord> store, DynamicRecord string,
RecordCheck<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> checker )
{
report.forDynamicBlockChange( type, store.forceGetRaw( string ), string, checker );
}
@Override
protected void checkDynamicLabel( RecordType type, RecordStore<DynamicRecord> store, DynamicRecord string,
RecordCheck<DynamicRecord, DynamicLabelConsistencyReport> checker )
{
report.forDynamicLabelBlockChange( type, store.forceGetRaw( string ), string, checker );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_StoreProcessor.java
|
3,214
|
public class LoggingDiffCheck extends DiffCheck
{
private final DiffCheck checker;
public LoggingDiffCheck( DiffCheck checker, StringLogger logger )
{
super( logger );
this.checker = checker;
}
@Override
public ConsistencySummaryStatistics execute( DiffStore diffs ) throws ConsistencyCheckIncompleteException
{
return checker.execute( diffs );
}
@Override
protected void verify( final DiffStore diffs, ConsistencySummaryStatistics summary )
{
if ( !summary.isConsistent() )
{
logger.logMessage( "Inconsistencies found: " + summary );
// TODO: log all changes by the transaction
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_LoggingDiffCheck.java
|
3,215
|
private static class RuleReader implements SchemaRuleAccess
{
private final RecordStore<DynamicRecord> schemaStore;
private RuleReader( RecordStore<DynamicRecord> schemaStore )
{
this.schemaStore = schemaStore;
}
@Override
public SchemaRule loadSingleSchemaRule( long ruleId ) throws MalformedSchemaRuleException
{
return SchemaStore.readSchemaRule( ruleId, schemaStore.getRecords( ruleId ) );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_IncrementalDiffCheck.java
|
3,216
|
public class IncrementalDiffCheck extends DiffCheck
{
public IncrementalDiffCheck( StringLogger logger )
{
super( logger );
}
@Override
public ConsistencySummaryStatistics execute( DiffStore diffs )
{
ConsistencySummaryStatistics summary = new ConsistencySummaryStatistics();
ConsistencyReporter reporter = new ConsistencyReporter( new DirectDiffRecordAccess( diffs ),
new InconsistencyReport( new InconsistencyMessageLogger( logger ), summary ) );
StoreProcessor processor = new StoreProcessor( reporter );
diffs.applyToAll( processor );
if ( diffs.getSchemaStore().hasChanges() )
{
if ( 0 == summary.getInconsistencyCountForRecordType( RecordType.SCHEMA ) )
{
performFullCheckOfSchemaStore( diffs, reporter, processor );
}
}
return summary;
}
@SuppressWarnings("unchecked")
private void performFullCheckOfSchemaStore( DiffStore diffs, ConsistencyReporter reporter,
StoreProcessor processor )
{
SchemaRecordCheck schemaChecker = new SchemaRecordCheck( new RuleReader( diffs.getSchemaStore() ) );
for ( DynamicRecord record : processor.scan( diffs.getSchemaStore() ) )
{
reporter.forSchema( record, schemaChecker );
}
schemaChecker = schemaChecker.forObligationChecking();
for ( DynamicRecord record : processor.scan( diffs.getSchemaStore() ) )
{
reporter.forSchema( record, schemaChecker );
}
}
private static class RuleReader implements SchemaRuleAccess
{
private final RecordStore<DynamicRecord> schemaStore;
private RuleReader( RecordStore<DynamicRecord> schemaStore )
{
this.schemaStore = schemaStore;
}
@Override
public SchemaRule loadSingleSchemaRule( long ruleId ) throws MalformedSchemaRuleException
{
return SchemaStore.readSchemaRule( ruleId, schemaStore.getRecords( ruleId ) );
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_incremental_IncrementalDiffCheck.java
|
3,217
|
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
DynamicRecord array = new DynamicRecord( next.arrayProperty() );
array.setInUse( true );
array.setCreated();
array.setType( PropertyType.ARRAY.intValue() );
array.setNextBlock( next.arrayProperty() );
array.setData( UTF8.encode( "hello world" ) );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( (((long) PropertyType.ARRAY.intValue()) << 24) | (array.getId() << 28) );
block.addValueRecord( array );
PropertyRecord property = new PropertyRecord( next.property() );
property.addPropertyBlock( block );
NodeRecord node = new NodeRecord( next.node(), -1, property.getId() );
property.setNodeId( node.getId() );
tx.create( node );
tx.create( property );
}
} );
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
3,218
|
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
DynamicRecord string = new DynamicRecord( next.stringProperty() );
string.setInUse( true );
string.setCreated();
string.setType( PropertyType.STRING.intValue() );
string.setNextBlock( next.stringProperty() );
string.setData( UTF8.encode( "hello world" ) );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( (((long) PropertyType.STRING.intValue()) << 24) | (string.getId() << 28) );
block.addValueRecord( string );
PropertyRecord property = new PropertyRecord( next.property() );
property.addPropertyBlock( block );
NodeRecord node = new NodeRecord( next.node(), -1, property.getId() );
property.setNodeId( node.getId() );
tx.create( node );
tx.create( property );
}
} );
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
3,219
|
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
PropertyRecord property = new PropertyRecord( next.property() );
property.setPrevProp( next.property() );
property.setNodeId( 1 );
PropertyBlock block = new PropertyBlock();
block.setSingleBlock( (((long) PropertyType.INT.intValue()) << 24) | (666 << 28) );
property.addPropertyBlock( block );
tx.create( property );
}
} );
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
3,220
|
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
long node = next.node();
tx.create( new RelationshipRecord( next.relationship(), node, node, 0 ) );
}
} );
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
3,221
|
{
@Override
protected void transactionData( GraphStoreFixture.TransactionDataBuilder tx,
GraphStoreFixture.IdGenerator next )
{
tx.create( new NodeRecord( next.node(), next.relationship(), -1 ) );
}
} );
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_checking_incremental_IncrementalCheckIntegrationTest.java
|
3,222
|
public class LabelScanDocumentProcessor implements RecordProcessor<NodeLabelRange>
{
private final ConsistencyReporter reporter;
private final LabelScanCheck labelScanCheck;
public LabelScanDocumentProcessor( ConsistencyReporter reporter, LabelScanCheck labelScanCheck )
{
this.reporter = reporter;
this.labelScanCheck = labelScanCheck;
}
@Override
public void process( NodeLabelRange nodeLabelRange )
{
reporter.forNodeLabelScan( new LabelScanDocument( nodeLabelRange ), labelScanCheck );
}
@Override
public void close()
{
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_labelscan_LabelScanDocumentProcessor.java
|
3,223
|
{
@Override
public Iterator<IndexRule> iterator()
{
return new SchemaStorage( schemaStore ).allIndexRules();
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_checking_schema_IndexRules.java
|
3,224
|
{
@Override
public boolean matchesSafely( String item )
{
return item.trim().split( " " ).length > 1;
}
@Override
public void describeTo( Description description )
{
description.appendText( "message of valid format" );
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java
|
3,225
|
public class NodePropertiesReporter
{
private final GraphDatabaseService database;
public NodePropertiesReporter( GraphDatabaseService database )
{
this.database = database;
}
public void reportNodeProperties( PrintWriter writer, RecordSet<RelationshipRecord> relationshipRecords )
{
Set<Long> nodeIds = new HashSet<Long>();
for ( RelationshipRecord relationshipRecord : relationshipRecords )
{
nodeIds.add( relationshipRecord.getFirstNode() );
nodeIds.add( relationshipRecord.getSecondNode() );
}
for ( Long nodeId : nodeIds )
{
reportNodeProperties( writer, nodeId );
}
}
private void reportNodeProperties( PrintWriter writer, Long nodeId )
{
try
{
Node node = database.getNodeById( nodeId );
writer.println( String.format( "Properties for node %d", nodeId ) );
for ( String propertyKey : node.getPropertyKeys() )
{
writer.println( String.format( " %s = %s", propertyKey, node.getProperty( propertyKey ) ) );
}
}
catch ( Exception e )
{
writer.println( format( "Failed to report properties for node %d:", nodeId ) );
e.printStackTrace( writer );
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_NodePropertiesReporter.java
|
3,226
|
@RunWith(Suite.class)
@Suite.SuiteClasses({ConsistencyReporterTest.TestAllReportMessages.class,
ConsistencyReporterTest.TestReportLifecycle.class})
public class ConsistencyReporterTest
{
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 );
}
}
@RunWith(Parameterized.class)
public static class TestAllReportMessages implements Answer
{
@Test
@SuppressWarnings("unchecked")
public void shouldLogInconsistency() throws Exception
{
// given
InconsistencyReport report = mock( InconsistencyReport.class );
ConsistencyReport.Reporter reporter = new ConsistencyReporter(
mock( DiffRecordAccess.class ), report );
// when
reportMethod.invoke( reporter, parameters( reportMethod ) );
// then
if ( method.getAnnotation( ConsistencyReport.Warning.class ) == null )
{
if ( reportMethod.getName().endsWith( "Change" ) )
{
verify( report ).error( any( RecordType.class ),
any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
else
{
verify( report ).error( any( RecordType.class ),
any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
}
else
{
if ( reportMethod.getName().endsWith( "Change" ) )
{
verify( report ).warning( any( RecordType.class ),
any( AbstractBaseRecord.class ), any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
else
{
verify( report ).warning( any( RecordType.class ),
any( AbstractBaseRecord.class ),
argThat( hasExpectedFormat() ), any( Object[].class ) );
}
}
}
private final Method reportMethod;
private final Method method;
public TestAllReportMessages( Method reportMethod, Method method )
{
this.reportMethod = reportMethod;
this.method = method;
}
@Parameterized.Parameters(name="{1}")
public static List<Object[]> methods()
{
ArrayList<Object[]> methods = new ArrayList<>();
for ( Method reporterMethod : ConsistencyReport.Reporter.class.getMethods() )
{
Type[] parameterTypes = reporterMethod.getGenericParameterTypes();
ParameterizedType checkerParameter = (ParameterizedType) parameterTypes[parameterTypes.length - 1];
Class reportType = (Class) checkerParameter.getActualTypeArguments()[1];
for ( Method method : reportType.getMethods() )
{
methods.add( new Object[]{reporterMethod, method} );
}
}
return methods;
}
@Rule
public final TestRule logFailure = new TestRule()
{
@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;
}
}
};
}
};
@Override
public String toString()
{
return format( "report.%s( %s{ reporter.%s(); } )",
reportMethod.getName(), signatureOf( reportMethod ), method.getName() );
}
private static String signatureOf( Method reportMethod )
{
if ( reportMethod.getParameterTypes().length == 2 )
{
return "record, RecordCheck( reporter )";
}
else
{
return "oldRecord, newRecord, RecordCheck( reporter )";
}
}
private Object[] parameters( Method method )
{
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = new Object[parameterTypes.length];
for ( int i = 0; i < parameters.length; i++ )
{
parameters[i] = parameter( parameterTypes[i] );
}
return parameters;
}
private Object parameter( Class<?> type )
{
if ( type == RecordType.class )
{
return RecordType.STRING_PROPERTY;
}
if ( type == RecordCheck.class )
{
return mockChecker();
}
if ( type == NodeRecord.class )
{
return new NodeRecord( 0, 1, 2 );
}
if ( type == RelationshipRecord.class )
{
return new RelationshipRecord( 0, 1, 2, 3 );
}
if ( type == PropertyRecord.class )
{
return new PropertyRecord( 0 );
}
if ( type == PropertyKeyTokenRecord.class )
{
return new PropertyKeyTokenRecord( 0 );
}
if ( type == PropertyBlock.class )
{
return new PropertyBlock();
}
if ( type == RelationshipTypeTokenRecord.class )
{
return new RelationshipTypeTokenRecord( 0 );
}
if ( type == LabelTokenRecord.class )
{
return new LabelTokenRecord( 0 );
}
if ( type == DynamicRecord.class )
{
return new DynamicRecord( 0 );
}
if ( type == NeoStoreRecord.class )
{
return new NeoStoreRecord();
}
if ( type == LabelScanDocument.class )
{
return new LabelScanDocument( new LuceneNodeLabelRange( 0, new long[] {}, new long[][] {} ) );
}
if ( type == IndexEntry.class )
{
return new IndexEntry( 0 );
}
if ( type == SchemaRule.Kind.class )
{
return SchemaRule.Kind.INDEX_RULE;
}
if ( type == IndexRule.class )
{
return IndexRule.indexRule( 1, 2, 3, new SchemaIndexProvider.Descriptor( "provider", "version" ) );
}
if ( type == long.class )
{
return 12L;
}
if ( type == Object.class )
{
return "object";
}
throw new IllegalArgumentException( format( "Don't know how to provide parameter of type %s", type.getName() ) );
}
@SuppressWarnings("unchecked")
private RecordCheck mockChecker()
{
RecordCheck checker = mock( RecordCheck.class );
doAnswer( this ).when( checker ).check( any( AbstractBaseRecord.class ),
any( CheckerEngine.class ),
any( RecordAccess.class ) );
doAnswer( this ).when( checker ).checkChange( any( AbstractBaseRecord.class ),
any( AbstractBaseRecord.class ),
any( CheckerEngine.class ),
any( DiffRecordAccess.class ) );
return checker;
}
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
Object[] arguments = invocation.getArguments();
ConsistencyReport report = ((CheckerEngine)arguments[arguments.length - 2]).report();
try
{
return method.invoke( report, parameters( method ) );
}
catch ( IllegalArgumentException ex )
{
throw new IllegalArgumentException(
format( "%s.%s#%s(...)", report, method.getDeclaringClass().getSimpleName(), method.getName() ),
ex );
}
}
}
private static Matcher<String> hasExpectedFormat()
{
return new TypeSafeMatcher<String>()
{
@Override
public boolean matchesSafely( String item )
{
return item.trim().split( " " ).length > 1;
}
@Override
public void describeTo( Description description )
{
description.appendText( "message of valid format" );
}
};
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_report_ConsistencyReporterTest.java
|
3,227
|
private static abstract class ReportInvocationHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
implements CheckerEngine<RECORD, REPORT>, InvocationHandler
{
final InconsistencyReport report;
private final ProxyFactory<REPORT> factory;
final RecordType type;
private short errors = 0, warnings = 0, references = 1/*this*/;
private ReportInvocationHandler( InconsistencyReport report, ProxyFactory<REPORT> factory, RecordType type )
{
this.report = report;
this.factory = factory;
this.type = type;
}
synchronized void updateSummary()
{
if ( --references == 0 )
{
report.updateSummary( type, errors, warnings );
}
}
String pendingCheckToString( ComparativeRecordChecker checker )
{
String checkName;
try
{
if ( checker.getClass().getMethod( "toString" ).getDeclaringClass() == Object.class )
{
checkName = checker.getClass().getSimpleName();
if ( checkName.length() == 0 )
{
checkName = checker.getClass().getName();
}
}
else
{
checkName = checker.toString();
}
}
catch ( NoSuchMethodException e )
{
checkName = checker.toString();
}
return String.format( "ReferenceCheck{%s[%s]/%s}", type, recordId(), checkName );
}
abstract long recordId();
@Override
public <REFERRED extends AbstractBaseRecord> void comparativeCheck(
RecordReference<REFERRED> reference, ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker )
{
references++;
reference.dispatch( new PendingReferenceCheck<REFERRED>( this, checker ) );
}
@Override
public REPORT report()
{
return factory.create( this );
}
/**
* Invoked when an inconsistency is encountered.
*
* @param args array of the items referenced from this record with which it is inconsistent.
*/
@Override
public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
String message;
Documented annotation = method.getAnnotation( Documented.class );
if ( annotation != null && !"".equals( annotation.value() ) )
{
message = annotation.value();
}
else
{
message = method.getName();
}
if ( method.getAnnotation( ConsistencyReport.Warning.class ) == null )
{
errors++;
logError( message, args );
}
else
{
warnings++;
logWarning( message, args );
}
return null;
}
protected abstract void logError( String message, Object[] args );
protected abstract void logWarning( String message, Object[] args );
abstract void checkReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord referenced, RecordAccess records );
abstract void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records );
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencyReporter.java
|
3,228
|
static class ReportHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
extends ReportInvocationHandler<RECORD,REPORT>
{
private final AbstractBaseRecord record;
ReportHandler( InconsistencyReport report, ProxyFactory<REPORT> factory, RecordType type,
AbstractBaseRecord record )
{
super( report, factory, type );
this.record = record;
}
@Override
long recordId()
{
return record.getLongId();
}
@Override
protected void logError( String message, Object[] args )
{
report.error( type, record, message, args );
}
@Override
protected void logWarning( String message, Object[] args )
{
report.warning( type, record, message, args );
}
@Override
@SuppressWarnings("unchecked")
void checkReference( CheckerEngine engine, ComparativeRecordChecker checker, AbstractBaseRecord referenced,
RecordAccess records )
{
checker.checkReference( record, referenced, this, records );
}
@Override
@SuppressWarnings("unchecked")
void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records )
{
checker.checkReference( record, newReferenced, this, records );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencyReporter.java
|
3,229
|
static class ProxyFactory<T>
{
private Constructor<? extends T> constructor;
@SuppressWarnings("unchecked")
ProxyFactory( Class<T> type ) throws LinkageError
{
try
{
this.constructor = (Constructor<? extends T>) Proxy
.getProxyClass( ConsistencyReporter.class.getClassLoader(), type )
.getConstructor( InvocationHandler.class );
}
catch ( NoSuchMethodException e )
{
throw withCause( new LinkageError( "Cannot access Proxy constructor for " + type.getName() ), e );
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + asList( constructor.getDeclaringClass().getInterfaces() );
}
public T create( InvocationHandler handler )
{
try
{
return constructor.newInstance( handler );
}
catch ( InvocationTargetException e )
{
throw launderedException( e );
}
catch ( Exception e )
{
throw new LinkageError( "Failed to create proxy instance" );
}
}
public static <T> ProxyFactory<T> create( Class<T> type )
{
return new ProxyFactory<>( type );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencyReporter.java
|
3,230
|
private static class DiffReportHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
extends ReportInvocationHandler<RECORD,REPORT>
{
private final AbstractBaseRecord oldRecord;
private final AbstractBaseRecord newRecord;
private DiffReportHandler( InconsistencyReport report, ProxyFactory<REPORT> factory,
RecordType type,
AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord )
{
super( report, factory, type );
this.oldRecord = oldRecord;
this.newRecord = newRecord;
}
@Override
long recordId()
{
return newRecord.getLongId();
}
@Override
protected void logError( String message, Object[] args )
{
report.error( type, oldRecord, newRecord, message, args );
}
@Override
protected void logWarning( String message, Object[] args )
{
report.warning( type, oldRecord, newRecord, message, args );
}
@Override
@SuppressWarnings("unchecked")
void checkReference( CheckerEngine engine, ComparativeRecordChecker checker, AbstractBaseRecord referenced,
RecordAccess records )
{
checker.checkReference( newRecord, referenced, this, records );
}
@Override
@SuppressWarnings("unchecked")
void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records )
{
checker.checkReference( newRecord, newReferenced, this, records );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencyReporter.java
|
3,231
|
public class ConsistencyReporter implements ConsistencyReport.Reporter
{
private static final ProxyFactory<ConsistencyReport.SchemaConsistencyReport> SCHEMA_REPORT =
ProxyFactory.create( ConsistencyReport.SchemaConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.NodeConsistencyReport> NODE_REPORT =
ProxyFactory.create( ConsistencyReport.NodeConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.LabelsMatchReport> LABEL_MATCH_REPORT =
ProxyFactory.create( ConsistencyReport.LabelsMatchReport.class );
private static final ProxyFactory<ConsistencyReport.RelationshipConsistencyReport> RELATIONSHIP_REPORT =
ProxyFactory.create( ConsistencyReport.RelationshipConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.PropertyConsistencyReport> PROPERTY_REPORT =
ProxyFactory.create( ConsistencyReport.PropertyConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.RelationshipTypeConsistencyReport> RELATIONSHIP_TYPE_REPORT =
ProxyFactory.create( ConsistencyReport.RelationshipTypeConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.LabelTokenConsistencyReport> LABEL_KEY_REPORT =
ProxyFactory.create( ConsistencyReport.LabelTokenConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.PropertyKeyTokenConsistencyReport> PROPERTY_KEY_REPORT =
ProxyFactory.create( ConsistencyReport.PropertyKeyTokenConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.DynamicConsistencyReport> DYNAMIC_REPORT =
ProxyFactory.create( ConsistencyReport.DynamicConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.DynamicLabelConsistencyReport> DYNAMIC_LABEL_REPORT =
ProxyFactory.create( ConsistencyReport.DynamicLabelConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.LabelScanConsistencyReport> LABEL_SCAN_REPORT =
ProxyFactory.create( ConsistencyReport.LabelScanConsistencyReport.class );
private static final ProxyFactory<ConsistencyReport.IndexConsistencyReport> INDEX =
ProxyFactory.create( ConsistencyReport.IndexConsistencyReport.class );
private final DiffRecordAccess records;
private final InconsistencyReport report;
public ConsistencyReporter( DiffRecordAccess records, InconsistencyReport report )
{
this.records = records;
this.report = report;
}
private <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
void dispatch( RecordType type, ProxyFactory<REPORT> factory, RECORD record, RecordCheck<RECORD, REPORT> checker )
{
ReportInvocationHandler<RECORD,REPORT> handler = new ReportHandler<>( report, factory, type, record );
checker.check( record, handler, records );
handler.updateSummary();
}
private <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
void dispatchChange( RecordType type, ProxyFactory<REPORT> factory, RECORD oldRecord, RECORD newRecord,
RecordCheck<RECORD, REPORT> checker )
{
ReportInvocationHandler<RECORD,REPORT> handler = new DiffReportHandler<>( report, factory, type, oldRecord, newRecord );
checker.checkChange( oldRecord, newRecord, handler, records );
handler.updateSummary();
}
static void dispatchReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord referenced, RecordAccess records )
{
ReportInvocationHandler handler = (ReportInvocationHandler) engine;
handler.checkReference( engine, checker, referenced, records );
handler.updateSummary();
}
static String pendingCheckToString( CheckerEngine engine, ComparativeRecordChecker checker )
{
ReportInvocationHandler handler = (ReportInvocationHandler) engine;
return handler.pendingCheckToString(checker);
}
static void dispatchChangeReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records )
{
ReportInvocationHandler handler = (ReportInvocationHandler) engine;
handler.checkDiffReference( engine, checker, oldReferenced, newReferenced, records );
handler.updateSummary();
}
static void dispatchSkip( CheckerEngine engine )
{
((ReportInvocationHandler) engine ).updateSummary();
}
private static abstract class ReportInvocationHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
implements CheckerEngine<RECORD, REPORT>, InvocationHandler
{
final InconsistencyReport report;
private final ProxyFactory<REPORT> factory;
final RecordType type;
private short errors = 0, warnings = 0, references = 1/*this*/;
private ReportInvocationHandler( InconsistencyReport report, ProxyFactory<REPORT> factory, RecordType type )
{
this.report = report;
this.factory = factory;
this.type = type;
}
synchronized void updateSummary()
{
if ( --references == 0 )
{
report.updateSummary( type, errors, warnings );
}
}
String pendingCheckToString( ComparativeRecordChecker checker )
{
String checkName;
try
{
if ( checker.getClass().getMethod( "toString" ).getDeclaringClass() == Object.class )
{
checkName = checker.getClass().getSimpleName();
if ( checkName.length() == 0 )
{
checkName = checker.getClass().getName();
}
}
else
{
checkName = checker.toString();
}
}
catch ( NoSuchMethodException e )
{
checkName = checker.toString();
}
return String.format( "ReferenceCheck{%s[%s]/%s}", type, recordId(), checkName );
}
abstract long recordId();
@Override
public <REFERRED extends AbstractBaseRecord> void comparativeCheck(
RecordReference<REFERRED> reference, ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker )
{
references++;
reference.dispatch( new PendingReferenceCheck<REFERRED>( this, checker ) );
}
@Override
public REPORT report()
{
return factory.create( this );
}
/**
* Invoked when an inconsistency is encountered.
*
* @param args array of the items referenced from this record with which it is inconsistent.
*/
@Override
public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
String message;
Documented annotation = method.getAnnotation( Documented.class );
if ( annotation != null && !"".equals( annotation.value() ) )
{
message = annotation.value();
}
else
{
message = method.getName();
}
if ( method.getAnnotation( ConsistencyReport.Warning.class ) == null )
{
errors++;
logError( message, args );
}
else
{
warnings++;
logWarning( message, args );
}
return null;
}
protected abstract void logError( String message, Object[] args );
protected abstract void logWarning( String message, Object[] args );
abstract void checkReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord referenced, RecordAccess records );
abstract void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records );
}
static class ReportHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
extends ReportInvocationHandler<RECORD,REPORT>
{
private final AbstractBaseRecord record;
ReportHandler( InconsistencyReport report, ProxyFactory<REPORT> factory, RecordType type,
AbstractBaseRecord record )
{
super( report, factory, type );
this.record = record;
}
@Override
long recordId()
{
return record.getLongId();
}
@Override
protected void logError( String message, Object[] args )
{
report.error( type, record, message, args );
}
@Override
protected void logWarning( String message, Object[] args )
{
report.warning( type, record, message, args );
}
@Override
@SuppressWarnings("unchecked")
void checkReference( CheckerEngine engine, ComparativeRecordChecker checker, AbstractBaseRecord referenced,
RecordAccess records )
{
checker.checkReference( record, referenced, this, records );
}
@Override
@SuppressWarnings("unchecked")
void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records )
{
checker.checkReference( record, newReferenced, this, records );
}
}
private static class DiffReportHandler
<RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
extends ReportInvocationHandler<RECORD,REPORT>
{
private final AbstractBaseRecord oldRecord;
private final AbstractBaseRecord newRecord;
private DiffReportHandler( InconsistencyReport report, ProxyFactory<REPORT> factory,
RecordType type,
AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord )
{
super( report, factory, type );
this.oldRecord = oldRecord;
this.newRecord = newRecord;
}
@Override
long recordId()
{
return newRecord.getLongId();
}
@Override
protected void logError( String message, Object[] args )
{
report.error( type, oldRecord, newRecord, message, args );
}
@Override
protected void logWarning( String message, Object[] args )
{
report.warning( type, oldRecord, newRecord, message, args );
}
@Override
@SuppressWarnings("unchecked")
void checkReference( CheckerEngine engine, ComparativeRecordChecker checker, AbstractBaseRecord referenced,
RecordAccess records )
{
checker.checkReference( newRecord, referenced, this, records );
}
@Override
@SuppressWarnings("unchecked")
void checkDiffReference( CheckerEngine engine, ComparativeRecordChecker checker,
AbstractBaseRecord oldReferenced, AbstractBaseRecord newReferenced,
RecordAccess records )
{
checker.checkReference( newRecord, newReferenced, this, records );
}
}
@Override
public void forSchema( DynamicRecord schema,
RecordCheck<DynamicRecord, ConsistencyReport.SchemaConsistencyReport> checker )
{
dispatch( RecordType.SCHEMA, SCHEMA_REPORT, schema, checker );
}
@Override
public void forSchemaChange( DynamicRecord oldSchema, DynamicRecord newSchema, RecordCheck<DynamicRecord,
ConsistencyReport.SchemaConsistencyReport> checker )
{
dispatchChange( RecordType.SCHEMA, SCHEMA_REPORT, oldSchema, newSchema, checker );
}
@Override
public void forNode( NodeRecord node,
RecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> checker )
{
dispatch( RecordType.NODE, NODE_REPORT, node, checker );
}
@Override
public void forNodeChange( NodeRecord oldNode, NodeRecord newNode,
RecordCheck<NodeRecord, ConsistencyReport.NodeConsistencyReport> checker )
{
dispatchChange( RecordType.NODE, NODE_REPORT, oldNode, newNode, checker );
}
@Override
public void forRelationship( RelationshipRecord relationship,
RecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> checker )
{
dispatch( RecordType.RELATIONSHIP, RELATIONSHIP_REPORT, relationship, checker );
}
@Override
public void forRelationshipChange( RelationshipRecord oldRelationship, RelationshipRecord newRelationship,
RecordCheck<RelationshipRecord, ConsistencyReport.RelationshipConsistencyReport> checker )
{
dispatchChange( RecordType.RELATIONSHIP, RELATIONSHIP_REPORT, oldRelationship, newRelationship, checker );
}
@Override
public void forProperty( PropertyRecord property,
RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> checker )
{
dispatch( RecordType.PROPERTY, PROPERTY_REPORT, property, checker );
}
@Override
public void forPropertyChange( PropertyRecord oldProperty, PropertyRecord newProperty,
RecordCheck<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> checker )
{
dispatchChange( RecordType.PROPERTY, PROPERTY_REPORT, oldProperty, newProperty, checker );
}
@Override
public void forRelationshipTypeName( RelationshipTypeTokenRecord relationshipTypeTokenRecord,
RecordCheck<RelationshipTypeTokenRecord,
ConsistencyReport.RelationshipTypeConsistencyReport> checker )
{
dispatch( RecordType.RELATIONSHIP_TYPE, RELATIONSHIP_TYPE_REPORT, relationshipTypeTokenRecord, checker );
}
@Override
public void forRelationshipTypeNameChange( RelationshipTypeTokenRecord oldType, RelationshipTypeTokenRecord newType,
RecordCheck<RelationshipTypeTokenRecord,
ConsistencyReport.RelationshipTypeConsistencyReport> checker )
{
dispatchChange( RecordType.RELATIONSHIP_TYPE, RELATIONSHIP_TYPE_REPORT, oldType, newType, checker );
}
@Override
public void forLabelName( LabelTokenRecord label,
RecordCheck<LabelTokenRecord, ConsistencyReport.LabelTokenConsistencyReport> checker )
{
dispatch( RecordType.LABEL, LABEL_KEY_REPORT, label, checker );
}
@Override
public void forNodeLabelScan( LabelScanDocument document,
RecordCheck<LabelScanDocument, ConsistencyReport.LabelScanConsistencyReport> checker )
{
dispatch( RecordType.LABEL_SCAN_DOCUMENT, LABEL_SCAN_REPORT, document, checker );
}
@Override
public void forIndexEntry( IndexEntry entry,
RecordCheck<IndexEntry, ConsistencyReport.IndexConsistencyReport> checker )
{
dispatch( RecordType.INDEX, INDEX, entry, checker );
}
@Override
public void forNodeLabelMatch( NodeRecord nodeRecord, RecordCheck<NodeRecord, ConsistencyReport.LabelsMatchReport> nodeLabelCheck )
{
dispatch( RecordType.NODE, LABEL_MATCH_REPORT, nodeRecord, nodeLabelCheck );
}
@Override
public void forLabelNameChange( LabelTokenRecord oldLabel, LabelTokenRecord newLabel, RecordCheck<LabelTokenRecord,
ConsistencyReport.LabelTokenConsistencyReport> checker )
{
dispatchChange( RecordType.LABEL, LABEL_KEY_REPORT, oldLabel, newLabel, checker );
}
@Override
public void forPropertyKey( PropertyKeyTokenRecord key,
RecordCheck<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> checker )
{
dispatch( RecordType.PROPERTY_KEY, PROPERTY_KEY_REPORT, key, checker );
}
@Override
public void forPropertyKeyChange( PropertyKeyTokenRecord oldKey, PropertyKeyTokenRecord newKey,
RecordCheck<PropertyKeyTokenRecord, ConsistencyReport.PropertyKeyTokenConsistencyReport> checker )
{
dispatchChange( RecordType.PROPERTY_KEY, PROPERTY_KEY_REPORT, oldKey, newKey, checker );
}
@Override
public void forDynamicBlock( RecordType type, DynamicRecord record,
RecordCheck<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> checker )
{
dispatch( type, DYNAMIC_REPORT, record, checker );
}
@Override
public void forDynamicBlockChange( RecordType type, DynamicRecord oldRecord, DynamicRecord newRecord,
RecordCheck<DynamicRecord, ConsistencyReport.DynamicConsistencyReport> checker )
{
dispatchChange( type, DYNAMIC_REPORT, oldRecord, newRecord, checker );
}
@Override
public void forDynamicLabelBlock( RecordType type, DynamicRecord record,
RecordCheck<DynamicRecord, DynamicLabelConsistencyReport> checker )
{
dispatch( type, DYNAMIC_LABEL_REPORT, record, checker );
}
@Override
public void forDynamicLabelBlockChange( RecordType type, DynamicRecord oldRecord, DynamicRecord newRecord,
RecordCheck<DynamicRecord, DynamicLabelConsistencyReport> checker )
{
dispatchChange( type, DYNAMIC_LABEL_REPORT, oldRecord, newRecord, checker );
}
static class ProxyFactory<T>
{
private Constructor<? extends T> constructor;
@SuppressWarnings("unchecked")
ProxyFactory( Class<T> type ) throws LinkageError
{
try
{
this.constructor = (Constructor<? extends T>) Proxy
.getProxyClass( ConsistencyReporter.class.getClassLoader(), type )
.getConstructor( InvocationHandler.class );
}
catch ( NoSuchMethodException e )
{
throw withCause( new LinkageError( "Cannot access Proxy constructor for " + type.getName() ), e );
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + asList( constructor.getDeclaringClass().getInterfaces() );
}
public T create( InvocationHandler handler )
{
try
{
return constructor.newInstance( handler );
}
catch ( InvocationTargetException e )
{
throw launderedException( e );
}
catch ( Exception e )
{
throw new LinkageError( "Failed to create proxy instance" );
}
}
public static <T> ProxyFactory<T> create( Class<T> type )
{
return new ProxyFactory<>( type );
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_report_ConsistencyReporter.java
|
3,232
|
SECOND
{
@Override
public long get( RelationshipRecord rel )
{
return rel.getSecondNode();
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipNodeField.java
|
3,233
|
FIRST
{
@Override
public long get( RelationshipRecord rel )
{
return rel.getFirstNode();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipNodeField.java
|
3,234
|
SECOND_PREV( Record.NO_PREV_RELATIONSHIP )
{
@Override
public long relOf( RelationshipRecord rel )
{
return rel.getSecondPrevRel();
}
};
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipChainField.java
|
3,235
|
SECOND_NEXT( Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long relOf( RelationshipRecord rel )
{
return rel.getSecondNextRel();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipChainField.java
|
3,236
|
FIRST_PREV( Record.NO_PREV_RELATIONSHIP )
{
@Override
public long relOf( RelationshipRecord rel )
{
return rel.getFirstPrevRel();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipChainField.java
|
3,237
|
FIRST_NEXT( Record.NO_NEXT_RELATIONSHIP )
{
@Override
public long relOf( RelationshipRecord rel )
{
return rel.getFirstNextRel();
}
},
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipChainField.java
|
3,238
|
public class RelationshipChainExplorerTest
{
private static final TargetDirectory target = TargetDirectory.forTest( RelationshipChainExplorerTest.class );
private static final int NDegreeTwoNodes = 10;
@Rule
public TargetDirectory.TestDirectory storeLocation = target.testDirectory();
private StoreAccess store;
@Before
public void setupStoreAccess()
{
store = createStoreWithOneHighDegreeNodeAndSeveralDegreeTwoNodes( NDegreeTwoNodes );
}
@After
public void tearDownStoreAccess()
{
store.close();
}
@Test
public void shouldLoadAllConnectedRelationshipRecordsAndTheirFullChainsOfRelationshipRecords() throws Exception
{
// given
RecordStore<RelationshipRecord> relationshipStore = store.getRelationshipStore();
// when
int relationshipIdInMiddleOfChain = 10;
RecordSet<RelationshipRecord> records = new RelationshipChainExplorer( relationshipStore )
.exploreRelationshipRecordChainsToDepthTwo(
relationshipStore.getRecord( relationshipIdInMiddleOfChain ) );
// then
assertEquals( NDegreeTwoNodes * 2, records.size() );
}
@Test
public void shouldCopeWithAChainThatReferencesNotInUseZeroValueRecords() throws Exception
{
// given
RecordStore<RelationshipRecord> relationshipStore = store.getRelationshipStore();
breakTheChain( relationshipStore );
// when
int relationshipIdInMiddleOfChain = 10;
RecordSet<RelationshipRecord> records = new RelationshipChainExplorer( relationshipStore )
.exploreRelationshipRecordChainsToDepthTwo(
relationshipStore.getRecord( relationshipIdInMiddleOfChain ) );
// then
int recordsInaccessibleBecauseOfBrokenChain = 3;
assertEquals( NDegreeTwoNodes * 2 - recordsInaccessibleBecauseOfBrokenChain, records.size() );
}
private void breakTheChain( RecordStore<RelationshipRecord> relationshipStore )
{
int relationshipTowardsEndOfChain = 16;
relationshipStore.updateRecord( new RelationshipRecord( relationshipTowardsEndOfChain, 0, 0, 0 ) );
}
enum TestRelationshipType implements RelationshipType
{
CONNECTED
}
private StoreAccess createStoreWithOneHighDegreeNodeAndSeveralDegreeTwoNodes( int nDegreeTwoNodes )
{
File storeDirectory = storeLocation.directory();
GraphDatabaseService database = new GraphDatabaseFactory().newEmbeddedDatabase( storeDirectory.getPath() );
Transaction transaction = database.beginTx();
try
{
Node denseNode = database.createNode();
for ( int i = 0; i < nDegreeTwoNodes; i++ )
{
Node degreeTwoNode = database.createNode();
Node leafNode = database.createNode();
if ( i % 2 == 0 )
{
denseNode.createRelationshipTo( degreeTwoNode, TestRelationshipType.CONNECTED );
}
else
{
degreeTwoNode.createRelationshipTo( denseNode, TestRelationshipType.CONNECTED );
}
degreeTwoNode.createRelationshipTo( leafNode, TestRelationshipType.CONNECTED );
}
transaction.success();
}
finally
{
transaction.finish();
}
database.shutdown();
return new StoreAccess( storeDirectory.getPath() );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_repair_RelationshipChainExplorerTest.java
|
3,239
|
public class RelationshipChainExplorer
{
public static final int none = Record.NO_NEXT_RELATIONSHIP.intValue();
private final RecordStore<RelationshipRecord> recordStore;
public RelationshipChainExplorer( RecordStore<RelationshipRecord> recordStore )
{
this.recordStore = recordStore;
}
public RecordSet<RelationshipRecord> exploreRelationshipRecordChainsToDepthTwo( RelationshipRecord record )
{
RecordSet<RelationshipRecord> records = new RecordSet<RelationshipRecord>();
for ( RelationshipNodeField nodeField : RelationshipNodeField.values() )
{
long nodeId = nodeField.get( record );
records.addAll( expandChains( expandChainInBothDirections( record, nodeId ), nodeId ) );
}
return records;
}
private RecordSet<RelationshipRecord> expandChains( RecordSet<RelationshipRecord> records, long otherNodeId )
{
RecordSet<RelationshipRecord> chains = new RecordSet<RelationshipRecord>();
for ( RelationshipRecord record : records )
{
chains.addAll( expandChainInBothDirections( record,
record.getFirstNode() == otherNodeId ? record.getSecondNode() : record.getFirstNode() ) );
}
return chains;
}
private RecordSet<RelationshipRecord> expandChainInBothDirections( RelationshipRecord record, long nodeId )
{
return expandChain( record, nodeId, PREV ).union( expandChain( record, nodeId, NEXT ) );
}
protected RecordSet<RelationshipRecord> followChainFromNode(long nodeId, long relationshipId )
{
RelationshipRecord record = recordStore.getRecord( relationshipId );
return expandChain( record, nodeId, NEXT );
}
private RecordSet<RelationshipRecord> expandChain( RelationshipRecord record, long nodeId,
RelationshipChainDirection direction )
{
RecordSet<RelationshipRecord> chain = new RecordSet<RelationshipRecord>();
chain.add( record );
RelationshipRecord currentRecord = record;
long nextRelId;
while ( currentRecord.inUse() &&
(nextRelId = direction.fieldFor( nodeId, currentRecord ).relOf( currentRecord )) != none ) {
currentRecord = recordStore.forceGetRecord( nextRelId );
chain.add( currentRecord );
}
return chain;
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RelationshipChainExplorer.java
|
3,240
|
public class RecordSetTest
{
@Test
public void toStringShouldPlaceEachRecordOnItsOwnLine() throws Exception
{
// given
NodeRecord record1 = new NodeRecord( 1, 1, 1 );
NodeRecord record2 = new NodeRecord( 2, 2, 2 );
RecordSet<NodeRecord> set = new RecordSet<NodeRecord>();
set.add( record1 );
set.add( record2 );
// when
String string = set.toString();
// then
String[] lines = string.split( "\n" );
assertEquals(4, lines.length);
assertEquals( "[", lines[0] );
assertEquals( record1.toString() + ",", lines[1] );
assertEquals( record2.toString() + ",", lines[2] );
assertEquals( "]", lines[3] );
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_repair_RecordSetTest.java
|
3,241
|
class RecordSet<R extends Abstract64BitRecord> implements Iterable<R>
{
private Map<Long, R> map = new HashMap<Long, R>();
void add( R record )
{
map.put( record.getId(), record );
}
RecordSet<R> union( RecordSet<R> other )
{
RecordSet<R> set = new RecordSet<R>();
set.addAll( this );
set.addAll( other );
return set;
}
int size()
{
return map.size();
}
@Override
public Iterator<R> iterator()
{
return map.values().iterator();
}
public void addAll( RecordSet<R> other )
{
for ( R record : other.map.values() )
{
add( record );
}
}
public boolean containsAll( RecordSet<R> other )
{
for ( Long id : other.map.keySet() )
{
if ( !map.containsKey( id ) )
{
return false;
}
}
return true;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder( "[\n" );
for ( R r : map.values() )
{
builder.append( r.toString() ).append( ",\n" );
}
return builder.append( "]\n" ).toString();
}
public static <R extends Abstract64BitRecord> RecordSet<R> asSet( R... records )
{
RecordSet<R> set = new RecordSet<R>();
for ( R record : records )
{
set.add( record );
}
return set;
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_RecordSet.java
|
3,242
|
{
@Override
public boolean matchesSafely( RecordSet<RelationshipRecord> actualSet )
{
return actualSet.containsAll( expectedSet );
}
@Override
public void describeTo( Description description )
{
description.appendText( "RecordSet containing " ).appendValueList( "[", ",", "]", expectedSet );
}
};
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_repair_OwningNodeRelationshipChainTest.java
|
3,243
|
public class OwningNodeRelationshipChainTest
{
@Test
public void shouldFindBothChainsThatTheRelationshipRecordShouldBelongTo() throws Exception
{
// given
int node1 = 101, node1Rel = 1001;
int node2 = 201, node2Rel = 2001;
int sharedRel = 1000;
int relType = 0;
RecordSet<RelationshipRecord> node1RelChain = RecordSet.asSet(
new RelationshipRecord( node1Rel, node1, node1 - 1, relType ),
new RelationshipRecord( sharedRel, node1, node2, relType ),
new RelationshipRecord( node1Rel + 1, node1 + 1, node1, relType ) );
RecordSet<RelationshipRecord> node2RelChain = RecordSet.asSet(
new RelationshipRecord( node2Rel, node2 - 1, node2, relType ),
new RelationshipRecord( sharedRel, node1, node2, relType ),
new RelationshipRecord( node2Rel + 1, node2, node2 + 1, relType ) );
@SuppressWarnings("unchecked")
RecordStore<NodeRecord> recordStore = mock( RecordStore.class );
when( recordStore.forceGetRecord( node1 ) ).thenReturn(
new NodeRecord( node1, node1Rel, NO_NEXT_PROPERTY.intValue() ) );
when( recordStore.forceGetRecord( node2 ) ).thenReturn(
new NodeRecord( node2, node2Rel, NO_NEXT_PROPERTY.intValue() ) );
RelationshipChainExplorer relationshipChainExplorer = mock( RelationshipChainExplorer.class );
when( relationshipChainExplorer.followChainFromNode( node1, node1Rel ) ).thenReturn( node1RelChain );
when( relationshipChainExplorer.followChainFromNode( node2, node2Rel ) ).thenReturn( node2RelChain );
OwningNodeRelationshipChain owningChainFinder =
new OwningNodeRelationshipChain( relationshipChainExplorer, recordStore );
// when
RecordSet<RelationshipRecord> recordsInChains = owningChainFinder
.findRelationshipChainsThatThisRecordShouldBelongTo( new RelationshipRecord( sharedRel, node1, node2,
relType ) );
// then
assertThat( recordsInChains, containsAllRecords( node1RelChain ) );
assertThat( recordsInChains, containsAllRecords( node2RelChain ) );
}
private Matcher<RecordSet<RelationshipRecord>> containsAllRecords( final RecordSet<RelationshipRecord> expectedSet )
{
return new TypeSafeMatcher<RecordSet<RelationshipRecord>>()
{
@Override
public boolean matchesSafely( RecordSet<RelationshipRecord> actualSet )
{
return actualSet.containsAll( expectedSet );
}
@Override
public void describeTo( Description description )
{
description.appendText( "RecordSet containing " ).appendValueList( "[", ",", "]", expectedSet );
}
};
}
}
| false
|
enterprise_consistency-check_src_test_java_org_neo4j_consistency_repair_OwningNodeRelationshipChainTest.java
|
3,244
|
public class OwningNodeRelationshipChain
{
private final RelationshipChainExplorer relationshipChainExplorer;
private final RecordStore<NodeRecord> nodeStore;
public OwningNodeRelationshipChain( RelationshipChainExplorer relationshipChainExplorer,
RecordStore<NodeRecord> nodeStore )
{
this.relationshipChainExplorer = relationshipChainExplorer;
this.nodeStore = nodeStore;
}
public RecordSet<RelationshipRecord> findRelationshipChainsThatThisRecordShouldBelongTo(
RelationshipRecord relationship )
{
RecordSet<RelationshipRecord> records = new RecordSet<RelationshipRecord>();
for ( RelationshipNodeField field : RelationshipNodeField.values() )
{
long nodeId = field.get( relationship );
NodeRecord nodeRecord = nodeStore.forceGetRecord( nodeId );
records.addAll( relationshipChainExplorer.followChainFromNode( nodeId, nodeRecord.getNextRel() ) );
}
return records;
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_repair_OwningNodeRelationshipChain.java
|
3,245
|
public class LabelScanDocument extends Abstract64BitRecord
{
private final NodeLabelRange nodeLabelRange;
public LabelScanDocument( NodeLabelRange nodeLabelRange )
{
super( nodeLabelRange.id() );
this.nodeLabelRange = nodeLabelRange;
setInUse( true );
}
public NodeLabelRange getNodeLabelRange()
{
return nodeLabelRange;
}
@Override
public String toString()
{
return nodeLabelRange.toString();
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_synthetic_LabelScanDocument.java
|
3,246
|
public class FileMapper
{
private final StoreChannel fileChannel;
public FileMapper( StoreChannel fileChannel )
{
this.fileChannel = fileChannel;
}
public long fileSizeInBytes() throws IOException
{
return fileChannel.size();
}
public MappedWindow mapWindow( long firstRecord, int recordsPerPage, int bytesPerRecord ) throws IOException
{
return new MappedWindow( recordsPerPage, bytesPerRecord, firstRecord,
fileChannel.map( READ_ONLY, firstRecord * bytesPerRecord, recordsPerPage * bytesPerRecord ) );
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_FileMapper.java
|
3,247
|
public class LoggingStatisticsListener implements MappingStatisticsListener
{
private final PrintWriter logWriter;
public LoggingStatisticsListener( File fileName ) throws FileNotFoundException
{
this.logWriter = FileUtils.newFilePrintWriter( fileName, Charsets.UTF_8 );
}
@Override
public void onStatistics( File storeFileName, int acquiredPages, int mappedPages, long
samplePeriod )
{
logWriter.printf( "%s: In %s: %d pages acquired, %d pages mapped (%.2f%%) in %d ms%n",
Format.date(), storeFileName.getName(), acquiredPages, mappedPages,
(100.0 * mappedPages) / acquiredPages, samplePeriod );
logWriter.flush();
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_LoggingStatisticsListener.java
|
3,248
|
@SuppressWarnings("MagicConstant")
public class ScrollableOptionPane
{
public static void showWrappedMessageDialog( Component parentComponent, String message, String title,
int messageType )
{
showMessageDialog( parentComponent, createWrappingScrollPane( message ), title, messageType );
}
public static int showWrappedConfirmDialog( Component parentComponent, String message, String title,
int optionType, int messageType )
{
return showConfirmDialog( parentComponent, createWrappingScrollPane( message ), title, optionType, messageType );
}
private static JScrollPane createWrappingScrollPane( String message )
{
JTextArea view = new JTextArea( message, 10, 80 );
view.setLineWrap( true );
view.setWrapStyleWord( true );
return new JScrollPane( view );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_ScrollableOptionPane.java
|
3,249
|
public class OpenDirectoryActionListener implements ActionListener
{
private final Component parent;
private final File directory;
private final DesktopModel model;
public OpenDirectoryActionListener( Component parent, File directory, DesktopModel model )
{
this.parent = parent;
this.directory = directory;
this.model = model;
}
@Override
public void actionPerformed( ActionEvent e )
{
if ( isExistingDirectory( directory ) || directory.mkdirs() )
{
try
{
model.openDirectory( directory );
}
catch ( IOException exception )
{
String message =
"Could not open directory or create directory: " + directory + "\n\n" + exception.getMessage();
showError( message );
}
}
else
{
String message = "Could not open directory or create directory: " + directory;
showError( message );
}
}
private void showError( String message )
{
showWrappedMessageDialog( parent, message, "Error", ERROR_MESSAGE );
}
private boolean isExistingDirectory( File directory )
{
return directory.exists() && directory.isDirectory();
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_OpenDirectoryActionListener.java
|
3,250
|
public class OpenBrowserMouseListener extends MouseAdapter
{
private final JLabel link;
private final DesktopModel model;
public OpenBrowserMouseListener( JLabel link, DesktopModel model )
{
this.link = link;
this.model = model;
}
@Override
public void mouseClicked( MouseEvent event )
{
try
{
model.openBrowser( link.getText() );
}
catch ( IOException | URISyntaxException e )
{
e.printStackTrace( System.out );
showError( e );
}
}
private void showError( Exception e )
{
showWrappedMessageDialog( link,
format( "Couldn't open the browser: %s", e.getMessage() ),
"Error",
ERROR_MESSAGE );
}
@Override
public void mouseEntered( MouseEvent e )
{
link.setCursor( getPredefinedCursor( HAND_CURSOR ) );
}
@Override
public void mouseExited( MouseEvent e )
{
link.setCursor( getPredefinedCursor( DEFAULT_CURSOR ) );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_OpenBrowserMouseListener.java
|
3,251
|
private class SysTrayActions implements SysTray.Actions
{
@Override
public void closeForReal()
{
shutdown();
}
@Override
public void clickSysTray()
{
frame.setVisible( true );
}
@Override
public void clickCloseButton()
{
if ( databaseStatus == STOPPED )
{
shutdown();
}
else
{
frame.setVisible( false );
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,252
|
{
@Override
public void run()
{
databaseActions.stop();
updateStatus( STOPPED );
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,253
|
{
@Override
public void actionPerformed( ActionEvent e )
{
updateStatus( DatabaseStatus.STOPPING );
invokeLater( new Runnable()
{
@Override
public void run()
{
databaseActions.stop();
updateStatus( STOPPED );
}
} );
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,254
|
{
@Override
public void mouseClicked( MouseEvent e )
{
if ( MouseEvent.BUTTON1 == e.getButton() && e.isAltDown() )
{
debugWindow.show();
}
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,255
|
{
@Override
public void actionPerformed( ActionEvent e )
{
JDialog settingsDialog = new SettingsDialog( frame, model );
settingsDialog.setLocationRelativeTo( null );
settingsDialog.setVisible( true );
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,256
|
public class MainWindow
{
private final DesktopModel model;
private final JFrame frame;
private final DatabaseActions databaseActions;
private final JButton browseButton;
private final JButton settingsButton;
private final JButton startButton;
private final JButton stopButton;
private final CardLayout statusPanelLayout;
private final JPanel statusPanel;
private final JTextField directoryDisplay;
private final SystemOutDebugWindow debugWindow;
private final SysTray sysTray;
private DatabaseStatus databaseStatus;
public MainWindow( final DatabaseActions databaseActions, DesktopModel model )
{
this.model = model;
this.debugWindow = new SystemOutDebugWindow();
this.databaseActions = databaseActions;
this.frame = new JFrame( "Neo4j Community" );
this.frame.setIconImages( Graphics.loadIcons() );
this.sysTray = SysTray.install( new SysTrayActions(), frame );
this.directoryDisplay = createUnmodifiableTextField( model.getDatabaseDirectory().getAbsolutePath() );
this.browseButton = createBrowseButton();
this.statusPanelLayout = new CardLayout();
this.statusPanel = createStatusPanel( statusPanelLayout );
this.startButton = createStartButton();
this.stopButton = createStopButton();
this.settingsButton = createSettingsButton();
JPanel root =
createRootPanel( directoryDisplay, browseButton, statusPanel, startButton, stopButton, settingsButton );
frame.add( root );
frame.pack();
frame.setResizable( false );
updateStatus( STOPPED );
}
private JPanel createRootPanel( JTextField directoryDisplay, JButton browseButton, Component statusPanel,
JButton startButton, JButton stopButton, JButton settingsButton )
{
return withSpacingBorder( withBoxLayout( BoxLayout.Y_AXIS,
createPanel( createLogoPanel(), createSelectionPanel( directoryDisplay, browseButton ), statusPanel,
createVerticalSpacing(), createActionPanel( startButton, stopButton, settingsButton ) ) ) );
}
public void display()
{
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
private JPanel createLogoPanel()
{
return withFlowLayout( FlowLayout.LEFT, createPanel(
new JLabel( new ImageIcon( loadImage( Graphics.LOGO_32 ) ) ),
new JLabel( format( "Neo4j %s", model.getNeo4jVersion() ) ) ) );
}
private JPanel createActionPanel( JButton startButton, JButton stopButton, JButton settingsButton )
{
return withBoxLayout( BoxLayout.LINE_AXIS,
createPanel( settingsButton, Box.createHorizontalGlue(), stopButton, startButton ) );
}
private JButton createSettingsButton()
{
return Components.createTextButton( ellipsis( "Settings" ), new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
JDialog settingsDialog = new SettingsDialog( frame, model );
settingsDialog.setLocationRelativeTo( null );
settingsDialog.setVisible( true );
}
} );
}
private JPanel createSelectionPanel( JTextField directoryDisplay, JButton selectButton )
{
return withTitledBorder( "Database location", withBoxLayout( BoxLayout.LINE_AXIS,
createPanel( directoryDisplay, selectButton ) ) );
}
protected void shutdown()
{
databaseActions.shutdown();
if ( debugWindow != null )
{
debugWindow.dispose();
}
frame.dispose();
System.exit( 0 );
}
private JPanel createStatusPanel( CardLayout statusPanelLayout )
{
JPanel panel = withLayout( statusPanelLayout, withTitledBorder( "Status", createPanel() ) );
for ( DatabaseStatus status : DatabaseStatus.values() )
{
panel.add( status.name(), status.display( model ) );
}
panel.addMouseListener( new MouseAdapter()
{
@Override
public void mouseClicked( MouseEvent e )
{
if ( MouseEvent.BUTTON1 == e.getButton() && e.isAltDown() )
{
debugWindow.show();
}
}
} );
return panel;
}
private JButton createBrowseButton()
{
ActionListener actionListener = new BrowseForDatabaseActionListener( frame, directoryDisplay, model );
return Components.createTextButton( ellipsis( "Browse" ), actionListener );
}
private JButton createStartButton()
{
return Components.createTextButton( "Start", new StartDatabaseActionListener( this, model, databaseActions ) );
}
private JButton createStopButton()
{
return Components.createTextButton( "Stop", new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
updateStatus( DatabaseStatus.STOPPING );
invokeLater( new Runnable()
{
@Override
public void run()
{
databaseActions.stop();
updateStatus( STOPPED );
}
} );
}
} );
}
public void updateStatus( DatabaseStatus status )
{
browseButton.setEnabled( STOPPED == status );
settingsButton.setEnabled( STOPPED == status );
startButton.setEnabled( STOPPED == status );
stopButton.setEnabled( STARTED == status );
statusPanelLayout.show( statusPanel, status.name() );
databaseStatus = status;
sysTray.changeStatus( status );
}
private class SysTrayActions implements SysTray.Actions
{
@Override
public void closeForReal()
{
shutdown();
}
@Override
public void clickSysTray()
{
frame.setVisible( true );
}
@Override
public void clickCloseButton()
{
if ( databaseStatus == STOPPED )
{
shutdown();
}
else
{
frame.setVisible( false );
}
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_MainWindow.java
|
3,257
|
public final class Graphics
{
public static final String LOGO_32 = "/neo4j-icon_32x32.png";
public static final String SYSTEM_TRAY_ICON = "/neo4j-systray-16.png";
private static final String LOGO_PATTERN = "/neo4j-icon_%1$dx%1$d.png";
private static final int MIN_SIZE = 16;
private static final int MAX_SIZE = 512;
private Graphics()
{
throw new UnsupportedOperationException();
}
static List<Image> loadIcons()
{
List<Image> icons = new ArrayList<>();
for ( int i = MIN_SIZE; i <= MAX_SIZE; i *= 2 )
{
Image image = loadImage( format( LOGO_PATTERN, i ) );
if ( null != image )
{
icons.add( image );
}
}
return icons;
}
static Image loadImage( String resource )
{
try
{
return ImageIO.read( Components.class.getResource( resource ) );
}
catch ( IOException e )
{
throw new IllegalStateException( e );
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_Graphics.java
|
3,258
|
public abstract class EditFileActionListener implements ActionListener
{
private final Component parentComponent;
private final DesktopModel model;
EditFileActionListener( Component parentComponent, DesktopModel model )
{
this.parentComponent = parentComponent;
this.model = model;
}
protected abstract File getFile();
@Override
public void actionPerformed( ActionEvent event )
{
File file = getFile();
if ( null == file )
{
showMessageDialog( parentComponent,
"Did not find location of .vmoptions file",
"Error",
ERROR_MESSAGE );
return;
}
try
{
ensureFileAndParentDirectoriesExists( file );
model.editFile( file );
}
catch ( IOException e )
{
e.printStackTrace( System.out );
showWrappedMessageDialog( parentComponent,
format( "Couldn't open %s, please open the file manually",
file.getAbsolutePath() ),
"Error",
ERROR_MESSAGE );
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
protected void ensureFileAndParentDirectoriesExists( File file ) throws IOException
{
file.getParentFile().mkdirs();
if ( !file.exists() )
{
file.createNewFile();
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_EditFileActionListener.java
|
3,259
|
{
@Override public boolean accept( File dir, String name )
{
return ! name.startsWith( "." );
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_DesktopModel.java
|
3,260
|
public class DesktopModel
{
private final DesktopConfigurator serverConfigurator;
private final List<DesktopModelListener> listeners = new ArrayList<>();
private final Installation installation;
public DesktopModel( Installation installation )
{
this.installation = installation;
this.serverConfigurator = new DesktopConfigurator( installation );
serverConfigurator.setDatabaseDirectory( installation.getDatabaseDirectory() );
}
public Configurator getServerConfigurator() {
serverConfigurator.refresh();
for(DesktopModelListener listener : listeners) {
listener.desktopModelChanged(this);
}
return serverConfigurator;
}
public String getNeo4jVersion()
{
return format( "%s", Version.getKernel().getReleaseVersion() );
}
public int getServerPort()
{
return serverConfigurator.getServerPort();
}
public File getDatabaseDirectory()
{
return new File( serverConfigurator.getDatabaseDirectory() );
}
public void setDatabaseDirectory( File databaseDirectory ) throws UnsuitableDirectoryException
{
verifyGraphDirectory(databaseDirectory);
serverConfigurator.setDatabaseDirectory( databaseDirectory );
}
public File getVmOptionsFile()
{
return installation.getVmOptionsFile();
}
public File getDatabaseConfigurationFile()
{
return serverConfigurator.getDatabaseConfigurationFile();
}
public File getServerConfigurationFile()
{
return installation.getServerConfigurationsFile();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void prepareGraphDirectoryForStart() throws UnsuitableDirectoryException
{
File databaseDirectory = new File( serverConfigurator.getDatabaseDirectory() );
verifyGraphDirectory( databaseDirectory );
if ( !databaseDirectory.exists() )
{
databaseDirectory.mkdirs();
}
File configurationFile = serverConfigurator.getDatabaseConfigurationFile();
if ( !configurationFile.exists() )
{
try
{
writeDefaultDatabaseConfiguration( configurationFile );
}
catch ( IOException e )
{
throw new UnsuitableDirectoryException( "Unable to write default configuration to %s",
databaseDirectory );
}
}
}
private static void verifyGraphDirectory( File dir ) throws UnsuitableDirectoryException
{
if ( !dir.isDirectory() )
{
throw new UnsuitableDirectoryException( "%s is not a directory", dir );
}
if ( !dir.canWrite() )
{
throw new UnsuitableDirectoryException( "%s is not writeable", dir );
}
String[] fileNames = dir.list( new FilenameFilter()
{
@Override public boolean accept( File dir, String name )
{
return ! name.startsWith( "." );
}
} );
if ( 0 == fileNames.length )
{
return;
}
for ( String fileName : fileNames )
{
if ( fileName.startsWith( "neostore" ) || fileName.equals( "neo4j.properties" ) )
{
return;
}
}
throw new UnsuitableDirectoryException(
"%s is neither empty nor does it contain a neo4j graph database", dir );
}
public void register( DesktopModelListener desktopModelListener )
{
listeners.add( desktopModelListener );
}
public void editFile( File file ) throws IOException
{
installation.getEnvironment().editFile( file );
}
public void openBrowser( String url ) throws IOException, URISyntaxException
{
installation.getEnvironment().openBrowser( url );
}
public void writeDefaultDatabaseConfiguration( File file ) throws IOException
{
InputStream defaults = installation.getDefaultDatabaseConfiguration();
writeInto( file, defaults );
}
public void writeDefaultServerConfiguration( File file ) throws IOException
{
InputStream defaults = installation.getDefaultServerConfiguration();
writeInto( file, defaults );
}
private void writeInto( File file, InputStream data ) throws IOException
{
if ( data == null )
{
// Don't bother writing any files if we somehow don't have any default data for them
return;
}
try ( BufferedReader reader = new BufferedReader( new InputStreamReader( data ) );
PrintWriter writer = new PrintWriter( file ) )
{
String input = reader.readLine();
while ( input != null )
{
writer.println( input );
input = reader.readLine();
}
}
}
public File getPluginsDirectory()
{
return installation.getPluginsDirectory();
}
public void openDirectory( File directory ) throws IOException
{
installation.getEnvironment().openDirectory( directory );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_DesktopModel.java
|
3,261
|
model.register( new DesktopModelListener() {
@Override
public void desktopModelChanged(DesktopModel model) {
link.setText("http://localhost:" + model.getServerPort() + "/");
}
});
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_DatabaseStatus.java
|
3,262
|
@SuppressWarnings("MagicConstant")
public final class Components
{
public static final int BASE_SPACING_SIZE = 5;
public static final int DEFAULT_TEXT_COLUMNS = 35;
private Components()
{
throw new UnsupportedOperationException();
}
static JPanel createPanel( Component... components )
{
JPanel panel = new JPanel();
for ( Component component : components )
{
panel.add( component );
}
return panel;
}
static JPanel withBackground( Color color, JPanel panel )
{
panel.setBackground( color );
return panel;
}
static JPanel withLayout( LayoutManager layout, JPanel panel )
{
panel.setLayout( layout );
return panel;
}
static JPanel withBoxLayout( int axis, JPanel panel )
{
return withLayout( new BoxLayout( panel, axis ), panel );
}
static JPanel withFlowLayout( int alignment, JPanel panel )
{
return withLayout( new FlowLayout( alignment ), panel );
}
static JPanel withFlowLayout( JPanel panel )
{
return withLayout( new FlowLayout(), panel );
}
static JPanel withSpacingBorder( JPanel panel )
{
return withBorder( createSpacingBorder( 1 ), panel );
}
static JPanel withBorder( Border border, JPanel panel )
{
panel.setBorder( border );
return panel;
}
static Border createSpacingBorder( int size )
{
int inset = BASE_SPACING_SIZE * size;
return BorderFactory.createEmptyBorder( inset, inset, inset, inset );
}
static JPanel withTitledBorder( String title, JPanel panel )
{
panel.setBorder( BorderFactory.createTitledBorder( title ) );
return panel;
}
static Component createVerticalSpacing()
{
return Box.createVerticalStrut( BASE_SPACING_SIZE );
}
static JTextField createUnmodifiableTextField( String text )
{
JTextField textField = new JTextField( text, DEFAULT_TEXT_COLUMNS );
textField.setEditable( false );
textField.setForeground( Color.GRAY );
return textField;
}
static JButton createTextButton( String text, ActionListener actionListener )
{
JButton button = new JButton( text );
button.addActionListener( actionListener );
return button;
}
static String ellipsis( String input )
{
return format( "%s\u2026", input );
}
@SuppressWarnings( { "unchecked", "rawtypes" } )
static Font underlined( Font font )
{
Map attributes = font.getAttributes();
attributes.put( UNDERLINE, UNDERLINE_ON );
return font.deriveFont( attributes );
}
public static void alert( String message )
{
showWrappedMessageDialog( null, message, "Alert", WARNING_MESSAGE );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_Components.java
|
3,263
|
class BrowseForDatabaseActionListener implements ActionListener
{
private final JFrame frame;
private final JTextField directoryDisplay;
private final DesktopModel model;
public BrowseForDatabaseActionListener( JFrame frame, JTextField directoryDisplay, DesktopModel model )
{
this.frame = frame;
this.directoryDisplay = directoryDisplay;
this.model = model;
}
@Override
public void actionPerformed( ActionEvent e )
{
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileSelectionMode( DIRECTORIES_ONLY );
jFileChooser.setCurrentDirectory( new File( directoryDisplay.getText() ) );
jFileChooser.setDialogTitle( "Select database" );
jFileChooser.setDialogType( CUSTOM_DIALOG );
while ( true )
{
int choice = jFileChooser.showOpenDialog( frame );
if ( choice != APPROVE_OPTION )
{
return;
}
File selectedFile = jFileChooser.getSelectedFile();
try
{
model.setDatabaseDirectory( selectedFile );
directoryDisplay.setText( model.getDatabaseDirectory().getAbsolutePath() );
return;
}
catch ( UnsuitableDirectoryException error )
{
int result = showWrappedConfirmDialog(
frame, error.getMessage() + "\nPlease choose a different folder.",
"Invalid folder selected", OK_CANCEL_OPTION, ERROR_MESSAGE );
if ( result == CANCEL_OPTION )
{
return;
}
}
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_BrowseForDatabaseActionListener.java
|
3,264
|
public class DesktopConfigurator implements Configurator
{
private final CompositeConfiguration compositeConfig = new CompositeConfiguration();
private final Map<String, String> map = new HashMap<>();
private final Installation installation;
private Configurator propertyFileConfig;
public DesktopConfigurator( Installation installation )
{
this.installation = installation;
refresh();
}
public void refresh() {
compositeConfig.clear();
compositeConfig.addConfiguration(new MapConfiguration( map ));
// re-read server properties, then add to config
propertyFileConfig = new PropertyFileConfigurator( installation.getServerConfigurationsFile() );
compositeConfig.addConfiguration( propertyFileConfig.configuration() );
}
@Override
public Configuration configuration()
{
return compositeConfig;
}
@Override
public Map<String, String> getDatabaseTuningProperties()
{
try
{
return load( getDatabaseConfigurationFile() );
}
catch ( IOException e )
{
return stringMap();
}
}
@Override
public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsClasses()
{
return propertyFileConfig.getThirdpartyJaxRsClasses();
}
@Override
public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsPackages()
{
return propertyFileConfig.getThirdpartyJaxRsPackages();
}
public void setDatabaseDirectory( File directory ) {
File neo4jProperties = new File( directory, Installation.NEO4J_PROPERTIES_FILENAME );
map.put( Configurator.DATABASE_LOCATION_PROPERTY_KEY, directory.getAbsolutePath() );
map.put( Configurator.DB_TUNING_PROPERTY_FILE_KEY, neo4jProperties.getAbsolutePath() );
}
public String getDatabaseDirectory() {
return map.get( Configurator.DATABASE_LOCATION_PROPERTY_KEY );
}
public int getServerPort() {
return configuration().getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT );
}
public File getDatabaseConfigurationFile() {
return new File( map.get( Configurator.DB_TUNING_PROPERTY_FILE_KEY ) );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_runtime_DesktopConfigurator.java
|
3,265
|
public class DatabaseActions
{
private final DesktopModel model;
private AbstractNeoServer server;
private Logging logging;
private LifeSupport life;
public DatabaseActions( DesktopModel model )
{
this.model = model;
}
public void start() throws UnableToStartServerException
{
if ( isRunning() )
{
throw new UnableToStartServerException( "Already started" );
}
Configurator configurator = model.getServerConfigurator();
logging = life.add( createDefaultLogging( configurator.getDatabaseTuningProperties() ) );
life.start();
server = new CommunityNeoServer( configurator, logging );
try
{
server.start();
}
catch ( ServerStartupException e )
{
server = null;
Set<Class> causes = extractCauseTypes( e );
if ( causes.contains( StoreLockException.class ) )
{
throw new UnableToStartServerException(
"Unable to lock store. Are you running another Neo4j process against this database?" );
}
if ( causes.contains( BindException.class ) )
{
throw new UnableToStartServerException(
"Unable to bind to port. Are you running another Neo4j process on this computer?" );
}
throw new UnableToStartServerException( e.getMessage() );
}
}
private Set<Class> extractCauseTypes( Throwable e )
{
Set<Class> types = new HashSet<>();
types.add( e.getClass() );
if ( e.getCause() != null )
{
types.addAll( extractCauseTypes( e.getCause() ) );
}
return types;
}
public void stop()
{
if ( isRunning() )
{
server.stop();
server = null;
life.shutdown();
}
}
public void shutdown()
{
if ( isRunning() )
{
stop();
}
}
public boolean isRunning()
{
return server != null;
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_runtime_DatabaseActions.java
|
3,266
|
public class WindowsInstallation extends PortableInstallation
{
private final WindowsEnvironment environment;
private final Properties installProperties;
public WindowsInstallation() throws Exception
{
environment = new WindowsEnvironment();
installProperties = new Properties();
File installPropertiesFile = new File( getInstallationBinDirectory(), INSTALL_PROPERTIES_FILENAME );
installProperties.load( new FileInputStream( installPropertiesFile ) );
}
@Override
public Environment getEnvironment()
{
return environment;
}
@Override
protected File getDefaultDirectory()
{
// cf. http://stackoverflow.com/questions/1503555/how-to-find-my-documents-folder
return getFileSystemView().getDefaultDirectory();
}
@Override
public File getConfigurationDirectory()
{
File appData = new File( System.getenv( "APPDATA" ) );
return new File( appData, installProperties.getProperty( "win.appdata.subdir" ) );
}
@Override
public File getVmOptionsFile()
{
return new File( getConfigurationDirectory(), NEO4J_VMOPTIONS_FILENAME );
}
@Override
public File getServerConfigurationsFile()
{
return new File( getConfigurationDirectory(), NEO4J_SERVER_PROPERTIES_FILENAME );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_windows_WindowsInstallation.java
|
3,267
|
class WindowsEnvironment extends PortableEnvironment
{
@Override
public void openBrowser( String link ) throws IOException, URISyntaxException
{
if ( isPortableBrowseSupported() )
{
portableBrowse( link );
return;
}
throw new UnsupportedOperationException();
}
@Override
public void editFile( File file ) throws IOException
{
if ( isPortableEditFileSupported() )
{
try
{
portableEditFile( file );
return;
}
catch ( IOException e )
{
e.printStackTrace( System.out );
}
}
windowsEditFile( file );
}
private void windowsEditFile( File file ) throws IOException
{
String[] cmdarray = { "notepad", file.getAbsolutePath() };
getRuntime().exec( cmdarray );
}
@Override
public void openDirectory( File directory ) throws IOException
{
if ( isPortableOpenSupported() )
{
try
{
portableOpen( directory );
return;
}
catch ( IOException e )
{
e.printStackTrace( System.out );
}
}
windowsOpenDirectory( directory );
}
private void windowsOpenDirectory( File directory ) throws IOException
{
getRuntime().exec( new String[] { "explorer", directory.getAbsolutePath() } );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_windows_WindowsEnvironment.java
|
3,268
|
public class PlatformUI
{
public static void selectPlatformUI()
{
try
{
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
}
catch ( ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e)
{
// don't care
e.printStackTrace( System.out );
}
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_PlatformUI.java
|
3,269
|
class SettingsDialog extends JDialog
{
private final DesktopModel model;
SettingsDialog( Frame owner, DesktopModel model )
{
super( owner, "Neo4j Settings", true );
this.model = model;
getContentPane().add( withSpacingBorder( withBoxLayout( BoxLayout.Y_AXIS, createPanel(
createEditDatabaseConfigPanel(createEditDatabaseConfigurationButton()),
createEditServerConfigPanel( createEditServerConfigurationButton() ),
createEditVmOptionsPanel( createEditVmOptionsButton() ),
createExtensionsPanel( createOpenPluginsDirectoryButton() ),
createVerticalSpacing(),
withFlowLayout( FlowLayout.RIGHT, createPanel(
createTextButton( "Close", new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
close();
}
} ) ) )
) ) ) );
pack();
}
private void close()
{
setVisible( false );
}
private Component createEditDatabaseConfigPanel(JButton configurationButton)
{
String configFilePath = model.getDatabaseConfigurationFile().getAbsolutePath();
return withFlowLayout( withTitledBorder( "Database Configuration",
createPanel( createUnmodifiableTextField( configFilePath ), configurationButton ) ) );
}
private Component createEditServerConfigPanel(JButton configurationButton) {
String configFilePath = model.getServerConfigurationFile().getAbsolutePath();
return withFlowLayout( withTitledBorder( "Server Configuration",
createPanel( createUnmodifiableTextField( configFilePath ), configurationButton ) ) );
}
private Component createEditVmOptionsPanel( JButton editVmOptionsButton )
{
File vmOptionsFile = model.getVmOptionsFile();
String vmOptionsPath = vmOptionsFile.getAbsolutePath();
return withFlowLayout( withTitledBorder( "Java VM Options (effective on restart)",
createPanel( createUnmodifiableTextField( vmOptionsPath ), editVmOptionsButton ) ) );
}
private Component createExtensionsPanel( JButton openPluginsDirectoryButton )
{
String pluginsDirectory = model.getPluginsDirectory().getAbsolutePath();
return withFlowLayout( withTitledBorder( "Plugins and Extensions",
createPanel( createUnmodifiableTextField( pluginsDirectory ), openPluginsDirectoryButton ) ) );
}
private JButton createEditDatabaseConfigurationButton()
{
return Components.createTextButton( ellipsis( "Edit" ), new EditFileActionListener( this, model )
{
@Override
protected File getFile()
{
return model.getDatabaseConfigurationFile();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void ensureFileAndParentDirectoriesExists( File file ) throws IOException
{
file.getParentFile().mkdirs();
if (!file.exists())
{
model.writeDefaultDatabaseConfiguration( file );
}
}
} );
}
private JButton createEditServerConfigurationButton()
{
return Components.createTextButton( ellipsis( "Edit" ), new EditFileActionListener( this, model )
{
@Override
protected File getFile()
{
return model.getServerConfigurationFile();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void ensureFileAndParentDirectoriesExists( File file ) throws IOException
{
file.getParentFile().mkdirs();
if (!file.exists())
{
model.writeDefaultServerConfiguration( file );
}
}
} );
}
private JButton createEditVmOptionsButton()
{
return Components.createTextButton( ellipsis( "Edit" ), new EditFileActionListener( this, model )
{
@Override
protected File getFile()
{
return model.getVmOptionsFile();
}
} );
}
private JButton createOpenPluginsDirectoryButton()
{
return Components.createTextButton( "Open",
new OpenDirectoryActionListener( this, model.getPluginsDirectory(), model ) );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SettingsDialog.java
|
3,270
|
class MappedWindow implements PersistenceWindow
{
private final long startRecordId;
private final Buffer buffer;
private final int recordsPerPage;
private final int recordSize;
private static final boolean I_AM_SURE_THERE_ARE_NO_REFERENCES_TO_HERE = false;
public MappedWindow( int recordsPerPage, int recordSize, long startRecordId, MappedByteBuffer mappedBuffer )
{
this.recordsPerPage = recordsPerPage;
this.recordSize = recordSize;
this.startRecordId = startRecordId;
this.buffer = new Buffer( this, mappedBuffer );
}
@Override
public Buffer getBuffer()
{
return buffer;
}
@Override
public Buffer getOffsettedBuffer( long id )
{
int offset = (int) (id - buffer.position()) * recordSize;
buffer.setOffset( offset );
return buffer;
}
@Override
public int getRecordSize()
{
return recordSize;
}
@Override
public long position()
{
return startRecordId;
}
@Override
public int size()
{
return recordsPerPage;
}
@Override
public void force()
{
}
@Override
public void close()
{
if ( I_AM_SURE_THERE_ARE_NO_REFERENCES_TO_HERE )
{
sun.nio.ch.DirectBuffer directBuffer = (sun.nio.ch.DirectBuffer) buffer.getBuffer();
directBuffer.cleaner().clean();
}
}
}
| false
|
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_MappedWindow.java
|
3,271
|
{
@Override
public void actionPerformed( ActionEvent e )
{
close();
}
} ) ) )
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SettingsDialog.java
|
3,272
|
TITLE
{
@Override
boolean isA( List<String> block )
{
int size = block.size();
return size > 0 && ( ( block.get( 0 )
.startsWith( "=" ) && !block.get( 0 )
.startsWith( "==" ) ) || size > 1 && block.get( 1 )
.startsWith( "=" ) );
}
@Override
String process( Block block, State state )
{
String title = block.lines.get( 0 )
.replace( "=", "" )
.trim();
String id = "cypherdoc-" + title.toLowerCase().replace( ' ', '-' );
return "[[" + id + "]]" + CypherDoc.EOL + "= " + title + " ="
+ CypherDoc.EOL;
}
},
| false
|
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
|
3,273
|
public class BlockTest
{
private GraphDatabaseService database;
private ExecutionEngine engine;
private State state;
@Rule
public ExpectedException expectedException = ExpectedException.none();
private static final String COMMENT_BLOCK = "////";
private static final List<String> ADAM_QUERY = Arrays.asList( "[source, cypher]", "----",
"CREATE (n:Person {name:\"Ad\" + \"am\"})", "RETURN n;", "----" );
@Before
public void setup()
{
database = new TestGraphDatabaseFactory().newImpermanentDatabase();
engine = new ExecutionEngine( database );
state = new State( engine, database );
}
@After
public void tearDown()
{
database.shutdown();
}
@Test
public void oneLineTitle()
{
Block block = Block.getBlock( Arrays.asList( "= Title here =" ) );
assertThat( block.type, sameInstance( BlockType.TITLE ) );
String output = block.process( state );
assertThat( output, containsString( "[[cypherdoc-title-here]]" ) );
assertThat( output, containsString( "= Title here =" ) );
}
@Test
public void twoLineTitle()
{
Block block = Block.getBlock( Arrays.asList( "Title here", "==========" ) );
assertThat( block.type, sameInstance( BlockType.TITLE ) );
String output = block.process( state );
assertThat( output, containsString( "[[cypherdoc-title-here]]" ) );
assertThat( output, containsString( "= Title here =" ) );
}
@Test
public void queryWithResultAndTest()
{
Block block = Block.getBlock( ADAM_QUERY );
block.process( state );
assertThat( state.latestResult.text, containsString( "Adam" ) );
block = Block.getBlock( Arrays.asList( COMMENT_BLOCK, "Adam", COMMENT_BLOCK ) );
assertThat( block.type, sameInstance( BlockType.TEST ) );
block.process( state );
block = Block.getBlock( Arrays.asList( "// table" ) );
assertThat( block.type, sameInstance( BlockType.TABLE ) );
String output = block.process( state );
assertThat(
output,
allOf( containsString( "Adam" ), containsString( "[queryresult]" ), containsString( "Node" ),
containsString( "created" ) ) );
}
@Test
public void queryWithTestFailure()
{
Block block = Block.getBlock( ADAM_QUERY );
assertThat( block.type, sameInstance( BlockType.QUERY ) );
block.process( state );
block = Block.getBlock( Arrays.asList( COMMENT_BLOCK, "Nobody", COMMENT_BLOCK ) );
expectedException.expect( TestFailureException.class );
expectedException.expectMessage( containsString( "Query result doesn't contain the string" ) );
block.process( state );
}
@Test
public void graph()
{
engine.execute( "CREATE (n:Person {name:\"Adam\"});" );
Block block = Block.getBlock( Arrays.asList( "// graph:xyz" ) );
assertThat( block.type, sameInstance( BlockType.GRAPH ) );
String output;
try (Transaction transaction = database.beginTx())
{
output = block.process( state );
transaction.success();
}
assertThat(
output,
allOf( startsWith( "[\"dot\"" ), containsString( "Adam" ),
containsString( "cypherdoc-xyz" ),
containsString( ".svg" ), containsString( "neoviz" ) ) );
}
@Test
public void graphWithoutId()
{
engine.execute( "CREATE (n:Person {name:\"Adam\"});" );
Block block = Block.getBlock( Arrays.asList( "//graph" ) );
assertThat( block.type, sameInstance( BlockType.GRAPH ) );
String output;
try (Transaction transaction = database.beginTx())
{
output = block.process( state );
transaction.success();
}
assertThat(
output,
allOf( startsWith( "[\"dot\"" ), containsString( "Adam" ), containsString( "cypherdoc--" ),
containsString( ".svg" ), containsString( "neoviz" ) ) );
}
@Test
public void console()
{
Block block = Block.getBlock( Arrays.asList( "// console" ) );
assertThat( block.type, sameInstance( BlockType.CONSOLE ) );
String output = block.process( state );
assertThat(
output,
allOf( startsWith( "ifdef::" ), endsWith( "endif::[]"
+ CypherDoc.EOL ),
containsString( "cypherdoc-console" ),
containsString( "<p" ), containsString( "<simpara" ),
containsString( "html" ) ) );
}
@Test
public void text()
{
Block block = Block.getBlock( Arrays.asList( "NOTE: just random asciidoc." ) );
assertThat( block.type, sameInstance( BlockType.TEXT ) );
String output = block.process( state );
assertThat( output, equalTo( "NOTE: just random asciidoc."
+ CypherDoc.EOL ) );
}
}
| false
|
manual_cypherdoc_src_test_java_org_neo4j_doc_cypherdoc_BlockTest.java
|
3,274
|
final class Block
{
public final List<String> lines;
public final BlockType type;
private Block( List<String> lines, BlockType type )
{
this.lines = lines;
this.type = type;
}
String process( State state )
{
return type.process( this, state );
}
@Override
public String toString()
{
return "Block [[" + type.name() + "]]:" + CypherDoc.EOL
+ StringUtils.join( lines, CypherDoc.EOL ) + CypherDoc.EOL;
}
static Block getBlock( List<String> lines )
{
for ( BlockType type : BlockType.values() )
{
if ( type.isA( lines ) )
{
return new Block( lines, type );
}
}
throw new IllegalArgumentException( "Unidentifiable block, starting with:\n" + lines.get( 0 ) );
}
}
| false
|
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_Block.java
|
3,275
|
class UnsuitableDirectoryException extends Exception
{
UnsuitableDirectoryException(String message, File dir)
{
super( format( message, dir.getAbsolutePath() ) );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_UnsuitableDirectoryException.java
|
3,276
|
public class UnableToStartServerException extends Exception
{
public UnableToStartServerException( String message )
{
super( message );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_UnableToStartServerException.java
|
3,277
|
public class TeeOutputStream extends OutputStream
{
private final OutputStream a;
private final OutputStream b;
public TeeOutputStream(OutputStream a, OutputStream b)
{
this.a = a;
this.b = b;
}
@Override
public void write( int data ) throws IOException
{
a.write( data );
b.write( data );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_TeeOutputStream.java
|
3,278
|
public class SystemOutDebugWindow
{
private static final int START_X = 100;
private static final int START_Y = 100;
private static final int START_WIDTH = 600;
private static final int START_HEIGHT = 800;
private final ByteArrayOutputStream sysStreamCapture = new ByteArrayOutputStream();
private PrintStream sysStreamPrinter;
private JFrame frame;
private JTextArea text;
public SystemOutDebugWindow()
{
stealSystemOut();
init();
}
private void stealSystemOut()
{
sysStreamPrinter = new PrintStream( new TeeOutputStream( System.out, sysStreamCapture ) );
System.setOut( sysStreamPrinter );
System.setErr( sysStreamPrinter );
}
private void init()
{
frame = new JFrame( "Debug" );
JPanel panel = new JPanel();
panel.setLayout( new CardLayout() );
sysStreamPrinter.flush();
text = new JTextArea();
panel.add( "status", text );
frame.add( new JScrollPane( panel ) );
frame.pack();
frame.setBounds( START_X, START_Y, START_WIDTH, START_HEIGHT );
frame.setVisible( false );
frame.setDefaultCloseOperation( HIDE_ON_CLOSE );
}
public void show()
{
sysStreamPrinter.flush();
text.setText( sysStreamCapture.toString() );
frame.setVisible( true );
}
public void dispose()
{
frame.dispose();
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SystemOutDebugWindow.java
|
3,279
|
{
@Override
public void windowClosing( WindowEvent e )
{
actions.clickCloseButton();
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,280
|
{
@Override
public void mouseClicked( MouseEvent e )
{
actions.clickSysTray();
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,281
|
{
@Override
public void actionPerformed( ActionEvent e )
{
actions.clickSysTray();
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,282
|
private static class Enabled extends SysTray
{
private final TrayIcon trayIcon;
private final String iconResourceBaseName;
Enabled( String iconResourceBaseName, Actions actions, JFrame mainWindow ) throws AWTException
{
this.iconResourceBaseName = iconResourceBaseName;
this.trayIcon = init( actions, mainWindow );
}
@Override
public void changeStatus( DatabaseStatus status )
{
trayIcon.setImage( loadImage( tryStatusSpecific( status ) ) );
trayIcon.setToolTip( title( status ) );
}
private String tryStatusSpecific( DatabaseStatus status )
{
String iconResource = status.name() + "-" + iconResourceBaseName;
return SysTray.class.getResource( iconResource ) != null ? iconResource : iconResourceBaseName;
}
private TrayIcon init( final Actions actions, JFrame mainWindow )
throws AWTException
{
TrayIcon trayIcon = new TrayIcon( loadImage( tryStatusSpecific( STOPPED ) ), title( STOPPED ) );
trayIcon.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
actions.clickSysTray();
}
} );
trayIcon.addMouseListener( new MouseAdapter()
{
@Override
public void mouseClicked( MouseEvent e )
{
actions.clickSysTray();
}
} );
mainWindow.setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
mainWindow.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing( WindowEvent e )
{
actions.clickCloseButton();
}
} );
SystemTray.getSystemTray().add( trayIcon );
return trayIcon;
}
private String title( DatabaseStatus status )
{
return "Neo4j Community (" + status.name() + ")";
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,283
|
{
@Override
public void windowClosing( WindowEvent e )
{
actions.closeForReal();
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,284
|
private static class Disabled extends SysTray
{
Disabled( final Actions actions, JFrame mainWindow )
{
mainWindow.setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
mainWindow.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing( WindowEvent e )
{
actions.closeForReal();
}
} );
}
@Override
public void changeStatus( DatabaseStatus status )
{
// Don't do anything.
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,285
|
public abstract class SysTray
{
public static SysTray install( Actions actions, JFrame mainWindow )
{
try
{
if ( SystemTray.isSupported() )
{
return new SysTray.Enabled( Graphics.SYSTEM_TRAY_ICON, actions, mainWindow );
}
}
catch ( AWTException e )
{
// What to do here?
e.printStackTrace( System.out );
}
// Fall back to still being able to function, but without the systray support.
return new SysTray.Disabled( actions, mainWindow );
}
public abstract void changeStatus( DatabaseStatus status );
private static class Enabled extends SysTray
{
private final TrayIcon trayIcon;
private final String iconResourceBaseName;
Enabled( String iconResourceBaseName, Actions actions, JFrame mainWindow ) throws AWTException
{
this.iconResourceBaseName = iconResourceBaseName;
this.trayIcon = init( actions, mainWindow );
}
@Override
public void changeStatus( DatabaseStatus status )
{
trayIcon.setImage( loadImage( tryStatusSpecific( status ) ) );
trayIcon.setToolTip( title( status ) );
}
private String tryStatusSpecific( DatabaseStatus status )
{
String iconResource = status.name() + "-" + iconResourceBaseName;
return SysTray.class.getResource( iconResource ) != null ? iconResource : iconResourceBaseName;
}
private TrayIcon init( final Actions actions, JFrame mainWindow )
throws AWTException
{
TrayIcon trayIcon = new TrayIcon( loadImage( tryStatusSpecific( STOPPED ) ), title( STOPPED ) );
trayIcon.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
actions.clickSysTray();
}
} );
trayIcon.addMouseListener( new MouseAdapter()
{
@Override
public void mouseClicked( MouseEvent e )
{
actions.clickSysTray();
}
} );
mainWindow.setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
mainWindow.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing( WindowEvent e )
{
actions.clickCloseButton();
}
} );
SystemTray.getSystemTray().add( trayIcon );
return trayIcon;
}
private String title( DatabaseStatus status )
{
return "Neo4j Community (" + status.name() + ")";
}
}
private static class Disabled extends SysTray
{
Disabled( final Actions actions, JFrame mainWindow )
{
mainWindow.setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
mainWindow.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing( WindowEvent e )
{
actions.closeForReal();
}
} );
}
@Override
public void changeStatus( DatabaseStatus status )
{
// Don't do anything.
}
}
public interface Actions
{
void clickCloseButton();
void clickSysTray();
void closeForReal();
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SysTray.java
|
3,286
|
{
@Override
public void run()
{
try
{
model.prepareGraphDirectoryForStart();
databaseActions.start();
mainWindow.updateStatus( STARTED );
}
catch ( UnsuitableDirectoryException | UnableToStartServerException e )
{
updateUserWithErrorMessageAndStatus( e );
}
}
private void updateUserWithErrorMessageAndStatus( Exception e )
{
alert( e.getMessage() );
mainWindow.updateStatus( STOPPED );
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_StartDatabaseActionListener.java
|
3,287
|
class StartDatabaseActionListener implements ActionListener
{
private MainWindow mainWindow;
private final DesktopModel model;
private final DatabaseActions databaseActions;
public StartDatabaseActionListener( MainWindow mainWindow, DesktopModel model, DatabaseActions databaseActions )
{
this.mainWindow = mainWindow;
this.model = model;
this.databaseActions = databaseActions;
}
@Override
public void actionPerformed( ActionEvent event )
{
mainWindow.updateStatus( STARTING );
invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
model.prepareGraphDirectoryForStart();
databaseActions.start();
mainWindow.updateStatus( STARTED );
}
catch ( UnsuitableDirectoryException | UnableToStartServerException e )
{
updateUserWithErrorMessageAndStatus( e );
}
}
private void updateUserWithErrorMessageAndStatus( Exception e )
{
alert( e.getMessage() );
mainWindow.updateStatus( STOPPED );
}
} );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_StartDatabaseActionListener.java
|
3,288
|
{
@Override
protected File getFile()
{
return model.getVmOptionsFile();
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SettingsDialog.java
|
3,289
|
{
@Override
protected File getFile()
{
return model.getServerConfigurationFile();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void ensureFileAndParentDirectoriesExists( File file ) throws IOException
{
file.getParentFile().mkdirs();
if (!file.exists())
{
model.writeDefaultServerConfiguration( file );
}
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SettingsDialog.java
|
3,290
|
{
@Override
protected File getFile()
{
return model.getDatabaseConfigurationFile();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void ensureFileAndParentDirectoriesExists( File file ) throws IOException
{
file.getParentFile().mkdirs();
if (!file.exists())
{
model.writeDefaultDatabaseConfiguration( file );
}
}
} );
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_ui_SettingsDialog.java
|
3,291
|
public class UnixInstallation extends PortableInstallation
{
@Override
public Environment getEnvironment()
{
return new UnixEnvironment();
}
@Override
public File getConfigurationDirectory()
{
// On UNIX derived systems it makes sense to put the configurations in the parent directory of
// the default.graphdb directory
File databaseDirectory = getDatabaseDirectory();
return databaseDirectory.getParentFile();
}
@Override
public File getVmOptionsFile()
{
return new File( getConfigurationDirectory(), "." + NEO4J_VMOPTIONS_FILENAME );
}
@Override
public File getServerConfigurationsFile()
{
return new File( getConfigurationDirectory(), "." + NEO4J_SERVER_PROPERTIES_FILENAME );
}
@Override
protected File getDefaultDirectory()
{
return new File( System.getProperty( "user.home" ) );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_unix_UnixInstallation.java
|
3,292
|
class UnixEnvironment extends PortableEnvironment
{
@Override
public void openBrowser( String url ) throws IOException, URISyntaxException
{
if ( isPortableBrowseSupported() )
{
portableBrowse( url );
return;
}
throw new UnsupportedOperationException( "Cannot browse to URL: " + url );
}
@Override
public void editFile( File file ) throws IOException
{
if ( isPortableEditFileSupported() )
{
portableEditFile( file );
return;
}
throw new UnsupportedOperationException( "Cannot edit file: " + file );
}
@Override
public void openDirectory( File directory ) throws IOException
{
if ( isPortableOpenSupported() )
{
portableOpen( directory );
return;
}
throw new UnsupportedOperationException( "Cannot open directory: " + directory );
}
}
| false
|
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_unix_UnixEnvironment.java
|
3,293
|
{
@Override
public String apply( String s )
{
return s.toUpperCase();
}
};
| false
|
packaging_neo4j-desktop_src_test_java_org_neo4j_desktop_config_portable_VariableSubstitutorTest.java
|
3,294
|
public class VariableSubstitutorTest
{
private static final Function<String, String> TO_UPPER_CASE = new Function<String, String>()
{
@Override
public String apply( String s )
{
return s.toUpperCase();
}
};
private final VariableSubstitutor substitutor = new VariableSubstitutor( );
@Test
public void shouldAcceptEmptyInput()
{
assertEquals( "", substitutor.substitute( "", null ) );
}
@Test
public void shouldAcceptInputWithoutVariables()
{
String expected = "Hello/Kitty/{TEST}";
assertEquals( expected, substitutor.substitute( expected, null ) );
}
@Test
public void shouldSubstituteVariable()
{
assertEquals( "TEST", substitutor.substitute( "${test}", TO_UPPER_CASE ) );
}
@Test
public void shouldSubstituteMultipleVariables()
{
assertEquals( "TESTTEXT", substitutor.substitute( "${test}${text}", TO_UPPER_CASE ) );
}
@Test
public void shouldSubstituteMultipleVariablesInText()
{
assertEquals(
"APPDATA/neo4j-desktop.vmoptions",
substitutor.substitute( "${APPDATA}/neo4j-desktop.vmoptions", TO_UPPER_CASE ) );
}
@Test
public void shouldSubstituteMultipleVariablesInMiddleOfText()
{
assertEquals( "do/TEST/and/VERIFY", substitutor.substitute( "do/${test}/and/${verify}", TO_UPPER_CASE ) );
}
}
| false
|
packaging_neo4j-desktop_src_test_java_org_neo4j_desktop_config_portable_VariableSubstitutorTest.java
|
3,295
|
public class ExecutionEngineTests
{
@Rule
public DatabaseRule database = new ImpermanentDatabaseRule();
@Test
public void shouldConvertListsAndMapsWhenPassingFromScalaToJava() throws Exception
{
ExecutionEngine executionEngine = new ExecutionEngine( database.getGraphDatabaseService() );
ExecutionResult result = executionEngine.execute( "RETURN { key : 'Value' , " +
"collectionKey: [{ inner: 'Map1' }, { inner: 'Map2' }]}" );
Map firstRowValue = (Map) result.iterator().next().values().iterator().next();
assertThat( (String) firstRowValue.get( "key" ), is( "Value" ) );
List theList = (List) firstRowValue.get( "collectionKey" );
assertThat( (String) ((Map) theList.get( 0 )).get( "inner" ), is( "Map1" ) );
assertThat( (String) ((Map) theList.get( 1 )).get( "inner" ), is( "Map2" ) );
}
}
| false
|
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_ExecutionEngineTests.java
|
3,296
|
public class ExecutionEngine
{
private org.neo4j.cypher.ExecutionEngine inner;
/**
* Creates an execution engine around the give graph database
* @param database The database to wrap
*/
public ExecutionEngine( GraphDatabaseService database )
{
this( database, DEV_NULL );
}
/**
* Creates an execution engine around the give graph database
* @param database The database to wrap
* @param logger A logger for cypher-statements
*/
public ExecutionEngine( GraphDatabaseService database, StringLogger logger )
{
inner = new org.neo4j.cypher.ExecutionEngine( database, logger );
}
/**
* Executes a query and returns an iterable that contains the result set
* @param query The query to execute
* @return A ExecutionResult that contains the result set
* @throws org.neo4j.cypher.SyntaxException If the Query contains errors,
* a SyntaxException exception might be thrown
*/
public ExecutionResult execute( String query ) throws CypherException
{
return new ExecutionResult(inner.execute( query ));
}
/**
* Executes a query and returns an iterable that contains the result set
* @param query The query to execute
* @param params Parameters for the query
* @return A ExecutionResult that contains the result set
* @throws org.neo4j.cypher.SyntaxException If the Query contains errors,
* a SyntaxException exception might be thrown
*/
public ExecutionResult execute( String query, Map<String, Object> params) throws CypherException
{
return new ExecutionResult(inner.execute(query, params));
}
/**
* Profiles a query and returns an iterable that contains the result set.
* Note that in order to gather profiling information, this actually executes
* the query as well. You can wrap a call to this in a transaction that you
* roll back if you don't want the query to have an actual effect on the data.
*
* @param query The query to profile
* @return A ExecutionResult that contains the result set
* @throws org.neo4j.cypher.SyntaxException If the Query contains errors,
* a SyntaxException exception might be thrown
*/
public ExecutionResult profile( String query ) throws CypherException
{
return new ExecutionResult(inner.profile(query));
}
/**
* Profiles a query and returns an iterable that contains the result set.
* Note that in order to gather profiling information, this actually executes
* the query as well. You can wrap a call to this in a transaction that you
* roll back if you don't want the query to have an actual effect on the data.
*
* @param query The query to profile
* @param params Parameters for the query
* @return A ExecutionResult that contains the result set
* @throws org.neo4j.cypher.SyntaxException If the Query contains errors,
* a SyntaxException exception might be thrown
*/
public ExecutionResult profile( String query, Map<String, Object> params) throws CypherException
{
return new ExecutionResult(inner.profile(query, params));
}
/**
* Turns a valid Cypher query and returns it with keywords in uppercase,
* and new-lines in the appropriate places.
*
* @param query The query to make pretty
* @return The same query, but prettier
*/
public String prettify( String query )
{
return inner.prettify(query);
}
}
| false
|
community_cypher_cypher_src_main_java_org_neo4j_cypher_javacompat_ExecutionEngine.java
|
3,297
|
public class CypherUpdateMapTest
{
private ExecutionEngine engine;
private GraphDatabaseService gdb;
@Test
public void updateNodeByMapParameter()
{
engine.execute(
"CREATE (n:Reference) SET n = {data} RETURN n" ,
map( "data",
map("key1", "value1", "key2", 1234)
)
);
Node node1 = getNodeByIdInTx( 0 );
assertThat( node1, inTx( gdb, hasProperty( "key1" ).withValue( "value1" ) ) );
assertThat( node1, inTx( gdb, hasProperty( "key2" ).withValue( 1234 ) ) );
engine.execute(
"MATCH (n:Reference) SET n = {data} RETURN n",
map( "data",
map("key1", null, "key3", 5678)
)
);
Node node2 = getNodeByIdInTx( 0 );
assertThat( node2, inTx( gdb, not( hasProperty( "key1" ) ) ) );
assertThat( node2, inTx( gdb, not( hasProperty( "key2" ) ) ) );
assertThat( node2, inTx( gdb, hasProperty( "key3" ).withValue(5678) ) );
}
private Node getNodeByIdInTx( int nodeId )
{
try ( Transaction ignored = gdb.beginTx(); )
{
return gdb.getNodeById( nodeId );
}
}
@Before
public void setup()
{
gdb = new TestGraphDatabaseFactory().newImpermanentDatabase();
engine = new ExecutionEngine(gdb);
}
@After
public void cleanup()
{
gdb.shutdown();
}
}
| false
|
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_CypherUpdateMapTest.java
|
3,298
|
{
@Override
public boolean isDebugEnabled()
{
return debugEnabled;
}
};
| false
|
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_CypherLoggingTest.java
|
3,299
|
public class CypherLoggingTest
{
private ExecutionEngine engine;
private boolean debugEnabled;
private BufferingLogger logger = new BufferingLogger()
{
@Override
public boolean isDebugEnabled()
{
return debugEnabled;
}
};
private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
@Test
public void shouldLogQueriesWhenDebugLoggingIsEnabled() throws Exception
{
// given
debugEnabled = true;
// when
engine.execute( "CREATE (n:Reference) CREATE (foo {test:'me'}) RETURN n" );
engine.execute( "START n=node(*) RETURN n" );
// then
assertEquals(
"CREATE (n:Reference) CREATE (foo {test:'me'}) RETURN n" + LINE_SEPARATOR +
"START n=node(*) RETURN n" + LINE_SEPARATOR,
logger.toString() );
}
@Test
public void shouldNotLogQueriesWhenDebugLoggingIsDisabled() throws Exception
{
// given
debugEnabled = false;
// when
engine.execute( "CREATE (n:Reference) CREATE (foo {test:'me'}) RETURN n" );
engine.execute( "START n=node(*) RETURN n" );
// then
assertEquals("", logger.toString() );
}
@Before
public void setup() throws IOException
{
engine = new ExecutionEngine( new TestGraphDatabaseFactory().newImpermanentDatabase(), logger );
}
}
| false
|
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_CypherLoggingTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.