Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
2,400
|
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).doubleValue() );
}
}, BOOL_RESULT = new ValueResult( RepresentationType.BOOLEAN )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,401
|
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).longValue() );
}
}, DOUBLE_RESULT = new ValueResult( RepresentationType.DOUBLE )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,402
|
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.string( (String) obj );
}
}, LONG_RESULT = new ValueResult( RepresentationType.LONG )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,403
|
{
@Override
Representation convert( Object obj )
{
return new PathRepresentation<Path>( (Path) obj );
}
}, STRING_RESULT = new ValueResult( RepresentationType.STRING )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,404
|
{
@Override
Representation convert( Object obj )
{
return new RelationshipRepresentation( (Relationship) obj );
}
}, PATH_RESULT = new ValueResult( RepresentationType.PATH )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,405
|
{
@Override
Representation convert( Object obj )
{
return new NodeRepresentation( (Node) obj );
}
}, RELATIONSHIP_RESULT = new ValueResult( RepresentationType.RELATIONSHIP )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,406
|
{
@Override
Representation convert( Object obj )
{
return Representation.emptyRepresentation();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,407
|
{
@Override
@SuppressWarnings( "boxing" )
Representation convert( Object obj )
{
return ValueRepresentation.number( (Character) obj );
}
}, VOID_RESULT = new ValueResult( RepresentationType.NOTHING )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,408
|
{
@Override
Representation convert( Object obj )
{
return (Representation) obj;
}
@Override
RepresentationType type()
{
return null;
}
},
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,409
|
abstract class ResultConverter
{
static ResultConverter get( Type type )
{
return get( type, true );
}
private static ResultConverter get( Type type, boolean allowComplex )
{
if ( type instanceof Class<?> )
{
Class<?> cls = (Class<?>) type;
if ( allowComplex && Representation.class.isAssignableFrom( cls ) )
{
return IDENTITY_RESULT;
}
else if ( cls == Node.class )
{
return NODE_RESULT;
}
else if ( cls == Relationship.class )
{
return RELATIONSHIP_RESULT;
}
else if ( cls == Path.class )
{
return PATH_RESULT;
}
else if ( cls == String.class )
{
return STRING_RESULT;
}
else if ( cls == void.class || cls == Void.class )
{
return VOID_RESULT;
}
else if ( cls == long.class || cls == Long.class )
{
return LONG_RESULT;
}
else if ( cls == double.class || cls == float.class || //
cls == Double.class || cls == Float.class )
{
return DOUBLE_RESULT;
}
else if ( cls == boolean.class || cls == Boolean.class )
{
return BOOL_RESULT;
}
else if ( cls == char.class || cls == Character.class )
{
return CHAR_RESULT;
}
else if ( cls.isPrimitive() || ( Number.class.isAssignableFrom( cls ) && //
cls.getPackage()
.getName()
.equals( "java.lang" ) ) )
{
return INT_RESULT;
}
}
else if ( allowComplex && type instanceof ParameterizedType )
{
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> raw = (Class<?>) parameterizedType.getRawType();
Type paramType = parameterizedType.getActualTypeArguments()[0];
if ( !( paramType instanceof Class<?> ) )
{
throw new IllegalStateException( "Parameterized result types must have a concrete type parameter." );
}
Class<?> param = (Class<?>) paramType;
if ( Iterable.class.isAssignableFrom( raw ) )
{
return new ListResult( get( param, false ) );
}
}
throw new IllegalStateException( "Illegal result type: " + type );
}
abstract Representation convert( Object obj );
abstract RepresentationType type();
private static abstract class ValueResult extends ResultConverter
{
private final RepresentationType type;
ValueResult( RepresentationType type )
{
this.type = type;
}
@Override
final RepresentationType type()
{
return type;
}
}
private static final ResultConverter//
IDENTITY_RESULT = new ResultConverter()
{
@Override
Representation convert( Object obj )
{
return (Representation) obj;
}
@Override
RepresentationType type()
{
return null;
}
},
NODE_RESULT = new ValueResult( RepresentationType.NODE )
{
@Override
Representation convert( Object obj )
{
return new NodeRepresentation( (Node) obj );
}
}, RELATIONSHIP_RESULT = new ValueResult( RepresentationType.RELATIONSHIP )
{
@Override
Representation convert( Object obj )
{
return new RelationshipRepresentation( (Relationship) obj );
}
}, PATH_RESULT = new ValueResult( RepresentationType.PATH )
{
@Override
Representation convert( Object obj )
{
return new PathRepresentation<Path>( (Path) obj );
}
}, STRING_RESULT = new ValueResult( RepresentationType.STRING )
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.string( (String) obj );
}
}, LONG_RESULT = new ValueResult( RepresentationType.LONG )
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).longValue() );
}
}, DOUBLE_RESULT = new ValueResult( RepresentationType.DOUBLE )
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).doubleValue() );
}
}, BOOL_RESULT = new ValueResult( RepresentationType.BOOLEAN )
{
@Override
@SuppressWarnings( "boxing" )
Representation convert( Object obj )
{
return ValueRepresentation.bool( (Boolean) obj );
}
}, INT_RESULT = new ValueResult( RepresentationType.INTEGER )
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).intValue() );
}
}, CHAR_RESULT = new ValueResult( RepresentationType.CHAR )
{
@Override
@SuppressWarnings( "boxing" )
Representation convert( Object obj )
{
return ValueRepresentation.number( (Character) obj );
}
}, VOID_RESULT = new ValueResult( RepresentationType.NOTHING )
{
@Override
Representation convert( Object obj )
{
return Representation.emptyRepresentation();
}
};
private static class ListResult extends ResultConverter
{
private final ResultConverter itemConverter;
ListResult( ResultConverter itemConverter )
{
this.itemConverter = itemConverter;
}
@Override
@SuppressWarnings( "unchecked" )
Representation convert( Object obj )
{
return new ListRepresentation( itemConverter.type(), new IterableWrapper<Representation, Object>(
(Iterable<Object>) obj )
{
@Override
protected Representation underlyingObjectToObject( Object object )
{
return itemConverter.convert( object );
}
} );
}
@Override
RepresentationType type()
{
return null;
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,410
|
class RelationshipTypeTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
String typeName = parameters.getString( name );
if ( typeName == null ) return null;
return DynamicRelationshipType.withName( typeName );
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
String[] strings = parameters.getStringList( name );
if ( strings == null ) return null;
RelationshipType[] result = new RelationshipType[strings.length];
for ( int i = 0; i < result.length; i++ )
{
result[i] = DynamicRelationshipType.withName( strings[i] );
}
return result;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_RelationshipTypeTypeCaster.java
|
2,411
|
class RelationshipTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getRelationship( graphDb, name );
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getRelationshipList( graphDb, name );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_RelationshipTypeCaster.java
|
2,412
|
{
@Override
Object convert( Object[] result )
{
return result;
}
};
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginPointFactoryImpl.java
|
2,413
|
{
@Override
Object convert( Object[] result )
{
return result;
}
};
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginPointFactoryImpl.java
|
2,414
|
{
@Override
Object convert( Object[] result )
{
return Arrays.asList( result );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginPointFactoryImpl.java
|
2,415
|
{
@Override
Object convert( Object[] result )
{
return new HashSet<Object>( Arrays.asList( result ) );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginPointFactoryImpl.java
|
2,416
|
class PluginPointFactoryImpl implements PluginPointFactory
{
public PluginPoint createFrom( ServerPlugin plugin, Method method, Class<?> discovery )
{
ResultConverter result = ResultConverter.get( method.getGenericReturnType() );
Type[] types = method.getGenericParameterTypes();
Annotation[][] annotations = method.getParameterAnnotations();
SourceExtractor sourceExtractor = null;
DataExtractor[] extractors = new DataExtractor[types.length];
for ( int i = 0; i < types.length; i++ )
{
Description description = null;
Parameter param = null;
Source source = null;
for ( Annotation annotation : annotations[i] )
{
if ( annotation instanceof Description )
{
description = (Description) annotation;
}
else if ( annotation instanceof Parameter )
{
param = (Parameter) annotation;
}
else if ( annotation instanceof Source )
{
source = (Source) annotation;
}
}
if ( param != null && source != null )
{
throw new IllegalStateException( String.format(
"Method parameter %d of %s cannot be retrieved as both Parameter and Source",
Integer.valueOf( i ), method ) );
}
else if ( source != null )
{
if ( types[i] != discovery )
{
throw new IllegalStateException( "Source parameter type (" + types[i]
+ ") must equal the discovery type (" + discovery.getName() + ")." );
}
if ( sourceExtractor != null )
{
throw new IllegalStateException( "Server Extension methods may have at most one Source parameter." );
}
extractors[i] = sourceExtractor = new SourceExtractor( source, description );
}
else if ( param != null )
{
extractors[i] = parameterExtractor( types[i], param, description );
}
else
{
throw new IllegalStateException(
"Parameters of Server Extension methods must be annotated as either Source or Parameter." );
}
}
return new PluginMethod( nameOf( method ), discovery, plugin, result, method, extractors,
method.getAnnotation( Description.class ) );
}
private static ParameterExtractor parameterExtractor( Type type, Parameter parameter, Description description )
{
if ( type instanceof ParameterizedType )
{
ParameterizedType paramType = (ParameterizedType) type;
Class<?> raw = (Class<?>) paramType.getRawType();
Type componentType = paramType.getActualTypeArguments()[0];
Class<?> component = null;
if ( componentType instanceof Class<?> )
{
component = (Class<?>) componentType;
}
if ( Set.class == raw )
{
TypeCaster caster = TYPES.get( component );
if ( caster != null )
{
return new ListParameterExtractor( caster, component, parameter, description )
{
@Override
Object convert( Object[] result )
{
return new HashSet<Object>( Arrays.asList( result ) );
}
};
}
}
else if ( List.class == raw || Collection.class == raw || Iterable.class == raw )
{
TypeCaster caster = TYPES.get( component );
if ( caster != null )
{
return new ListParameterExtractor( caster, component, parameter, description )
{
@Override
Object convert( Object[] result )
{
return Arrays.asList( result );
}
};
}
}
}
else if ( type instanceof Class<?> )
{
Class<?> raw = (Class<?>) type;
if ( raw.isArray() )
{
TypeCaster caster = TYPES.get( raw.getComponentType() );
if ( caster != null )
{
return new ListParameterExtractor( caster, raw.getComponentType(), parameter, description )
{
@Override
Object convert( Object[] result )
{
return result;
}
};
}
}
else
{
TypeCaster caster = TYPES.get( raw );
if ( caster != null )
{
return new ParameterExtractor( caster, raw, parameter, description );
}
}
}
else if ( type instanceof GenericArrayType )
{
GenericArrayType array = (GenericArrayType) type;
Type component = array.getGenericComponentType();
if ( component instanceof Class<?> )
{
TypeCaster caster = TYPES.get( component );
if ( caster != null )
{
return new ListParameterExtractor( caster, (Class<?>) component, parameter, description )
{
@Override
Object convert( Object[] result )
{
return result;
}
};
}
}
}
throw new IllegalStateException( "Unsupported parameter type: " + type );
}
private static void put( Map<Class<?>, TypeCaster> types, TypeCaster caster, Class<?>... keys )
{
for ( Class<?> key : keys )
{
types.put( key, caster );
}
}
private static final Map<Class<?>, TypeCaster> TYPES = new HashMap<Class<?>, TypeCaster>();
static
{
put( TYPES, new StringTypeCaster(), String.class );
put( TYPES, new ByteTypeCaster(), byte.class, Byte.class );
put( TYPES, new ShortTypeCaster(), short.class, Short.class );
put( TYPES, new IntegerTypeCaster(), int.class, Integer.class );
put( TYPES, new LongTypeCaster(), long.class, Long.class );
put( TYPES, new CharacterTypeCaster(), char.class, Character.class );
put( TYPES, new BooleanTypeCaster(), boolean.class, Boolean.class );
put( TYPES, new FloatTypeCaster(), float.class, Float.class );
put( TYPES, new DoubleTypeCaster(), double.class, Double.class );
put( TYPES, new MapTypeCaster(), Map.class );
put( TYPES, new NodeTypeCaster(), Node.class );
put( TYPES, new RelationshipTypeCaster(), Relationship.class );
put( TYPES, new RelationshipTypeTypeCaster(), RelationshipType.class );
put( TYPES, new UriTypeCaster(), URI.class );
put( TYPES, new URLTypeCaster(), URL.class );
}
private static String nameOf( Method method )
{
Name name = method.getAnnotation( Name.class );
if ( name != null )
{
return name.value();
}
return method.getName();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginPointFactoryImpl.java
|
2,417
|
public abstract class PluginPoint
{
private final String name;
private final Class<?> extendsType;
private final String description;
protected PluginPoint( Class<?> type, String name, String description )
{
this.extendsType = type;
this.description = description == null ? "" : description;
this.name = ServerPlugin.verifyName( name );
}
protected PluginPoint( Class<?> type, String name )
{
this( type, name, null );
}
public final String name()
{
return name;
}
public final Class<?> forType()
{
return extendsType;
}
public String getDescription()
{
return description;
}
public abstract Representation invoke( GraphDatabaseAPI graphDb, Object context,
ParameterList params ) throws BadInputException, BadPluginInvocationException,
PluginInvocationFailureException;
protected void describeParameters( ParameterDescriptionConsumer consumer )
{
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_PluginPoint.java
|
2,418
|
class PluginMethod extends PluginPoint
{
private final ServerPlugin plugin;
private final Method method;
private final DataExtractor[] extractors;
private final ResultConverter result;
PluginMethod( String name, Class<?> discovery, ServerPlugin plugin, ResultConverter result, Method method,
DataExtractor[] extractors, Description description )
{
super( discovery, name, description == null ? "" : description.value() );
this.plugin = plugin;
this.result = result;
this.method = method;
this.extractors = extractors;
}
@Override
public Representation invoke( GraphDatabaseAPI graphDb, Object source, ParameterList params )
throws BadPluginInvocationException, PluginInvocationFailureException, BadInputException
{
Object[] arguments = new Object[extractors.length];
try ( Transaction tx = graphDb.beginTx() )
{
for ( int i = 0; i < arguments.length; i++ )
{
arguments[i] = extractors[i].extract( graphDb, source, params );
}
}
try
{
Object returned = method.invoke( plugin, arguments );
if ( returned == null )
{
return Representation.emptyRepresentation();
}
return result.convert( returned );
}
catch ( InvocationTargetException exc )
{
Throwable targetExc = exc.getTargetException();
for ( Class<?> excType : method.getExceptionTypes() )
{
if ( excType.isInstance( targetExc ) )
{
throw new BadPluginInvocationException( targetExc );
}
}
throw new PluginInvocationFailureException( targetExc );
}
catch ( IllegalArgumentException | IllegalAccessException e )
{
throw new PluginInvocationFailureException( e );
}
}
@Override
protected void describeParameters( ParameterDescriptionConsumer consumer )
{
for ( DataExtractor extractor : extractors )
{
extractor.describe( consumer );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginMethod.java
|
2,419
|
public class ServerClassNameTest
{
@Test
public void shouldMaintainNamingOfCommunityNeoServerSoThatTheNeo4jEditionIsCorrectlyShownToRESTAPICallers()
throws Exception
{
assertEquals( getErrorMessage( CommunityNeoServer.class ), "communityneoserver",
CommunityNeoServer.class.getSimpleName().toLowerCase() );
}
@Test
public void shouldMaintainNamingOfAdvancedNeoServerSoThatTheNeo4jEditionIsCorrectlyShownToRESTAPICallers()
throws Exception
{
assertEquals( getErrorMessage( AdvancedNeoServer.class ), "advancedneoserver",
AdvancedNeoServer.class.getSimpleName().toLowerCase() );
}
@Test
public void shouldMaintainNamingOfEnterpriseNeoServerSoThatTheNeo4jEditionIsCorrectlyShownToRESTAPICallers()
throws Exception
{
assertEquals( getErrorMessage( EnterpriseNeoServer.class ), "enterpriseneoserver",
EnterpriseNeoServer.class.getSimpleName().toLowerCase() );
}
private String getErrorMessage( Class<? extends AbstractNeoServer> neoServerClass )
{
return "The " + neoServerClass.getSimpleName() + " class appears to have been renamed. There is a strict " +
"dependency from the REST API VersionAndEditionService on the name of that class. If you want " +
"to change the name of that class, then remember to change VersionAndEditionService, " +
"VersionAndEditionServiceTest and, of course, this test. ";
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_ServerClassNameTest.java
|
2,420
|
public class Neo4jHAPropertiesMustExistRuleTest
{
@Rule
public TemporaryFolder folder = new TemporaryFolder( );
public static final String CONFIG_KEY_OLD_SERVER_ID = "ha.machine_id";
public static final String CONFIG_KEY_OLD_COORDINATORS = "ha.zoo_keeper_servers";
// TODO: write more tests
@Test
public void shouldPassIfHaModeNotSpecified() throws Exception
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( "touch", "me", serverPropertyFile );
assertRulePass( serverPropertyFile );
}
@Test
public void shouldFailIfInvalidModeSpecified() throws Exception
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "faulty", serverPropertyFile );
assertRuleFail( serverPropertyFile );
}
@Test
public void shouldPassIfHAModeIsSetAndTheDbTuningFileHasBeenSpecifiedAndExists() throws IOException
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
File dbTuningFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_TUNING_PROPERTY_FILE_KEY,
dbTuningFile.getAbsolutePath(), serverPropertyFile );
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "ha", serverPropertyFile );
ServerTestUtils.writePropertyToFile( ClusterSettings.server_id.name(), "1", dbTuningFile );
assertRulePass( serverPropertyFile );
serverPropertyFile.delete();
dbTuningFile.delete();
}
@Test
public void shouldPassIfHAModeIsSetAndTheDbTuningFileHasBeenSpecifiedAndExistsWithOldConfig() throws IOException
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
File dbTuningFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_TUNING_PROPERTY_FILE_KEY,
dbTuningFile.getAbsolutePath(), serverPropertyFile );
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "ha", serverPropertyFile );
ServerTestUtils.writePropertyToFile( CONFIG_KEY_OLD_SERVER_ID, "1", dbTuningFile );
ServerTestUtils.writePropertyToFile( CONFIG_KEY_OLD_COORDINATORS,
"localhost:0000", dbTuningFile );
assertRulePass( serverPropertyFile );
serverPropertyFile.delete();
dbTuningFile.delete();
}
@Test
public void shouldFailIfHAModeIsSetAndTheDbTuningFileHasBeenSpecifiedAndExistsWithDuplicateIdConfig() throws
IOException
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
File dbTuningFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_TUNING_PROPERTY_FILE_KEY,
dbTuningFile.getAbsolutePath(), serverPropertyFile );
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "ha", serverPropertyFile );
ServerTestUtils.writePropertyToFile( CONFIG_KEY_OLD_SERVER_ID, "1", dbTuningFile );
ServerTestUtils.writePropertyToFile( ClusterSettings.server_id.name(), "1", dbTuningFile );
assertRuleFail( serverPropertyFile );
serverPropertyFile.delete();
dbTuningFile.delete();
}
@Test
public void shouldFailIfHAModeIsSetAndTheDbTuningFileHasBeenSpecifiedButDoesNotExist() throws IOException
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
File dbTuningFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_TUNING_PROPERTY_FILE_KEY,
dbTuningFile.getAbsolutePath(), serverPropertyFile );
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "ha", serverPropertyFile );
assertRuleFail( serverPropertyFile );
serverPropertyFile.delete();
dbTuningFile.delete();
}
@Test
public void shouldFailIfHAModeIsSetAndTheDbTuningFileHasNotBeenSpecified() throws IOException
{
File serverPropertyFile = ServerTestUtils.createTempPropertyFile(folder.getRoot());
ServerTestUtils.writePropertyToFile( Configurator.DB_MODE_KEY, "ha", serverPropertyFile );
assertRuleFail( serverPropertyFile );
serverPropertyFile.delete();
}
private void assertRulePass( File file )
{
EnsureEnterpriseNeo4jPropertiesExist rule = new EnsureEnterpriseNeo4jPropertiesExist(
propertiesWithConfigFileLocation( file ) );
if ( !rule.run() )
{
fail( rule.getFailureMessage() );
}
}
private void assertRuleFail( File file )
{
EnsureEnterpriseNeo4jPropertiesExist rule = new EnsureEnterpriseNeo4jPropertiesExist(
propertiesWithConfigFileLocation( file ) );
if ( rule.run() )
{
fail( rule + " should have failed" );
}
}
private Configuration propertiesWithConfigFileLocation( File propertyFile )
{
PropertyFileConfigurator config = new PropertyFileConfigurator( NO_VALIDATION, propertyFile, DEV_NULL );
config.configuration().setProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY, propertyFile.getAbsolutePath() );
return config.configuration();
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_Neo4jHAPropertiesMustExistRuleTest.java
|
2,421
|
public class EnterpriseNeoServerBootstrapperTest
{
@Test
public void bootstrapperLoadsEnterpriseServerBootstrapper() throws Exception
{
assertThat( Bootstrapper.loadMostDerivedBootstrapper(), is( instanceOf( EnterpriseBootstrapper.class ) ));
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_EnterpriseNeoServerBootstrapperTest.java
|
2,422
|
new Runnable() {
@Override
public void run()
{
stopModules();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,423
|
{
@Override
public void run()
{
module.stop();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,424
|
{
@Override
public Runnable apply( final ServerModule module )
{
return new Runnable()
{
@Override
public void run()
{
module.stop();
}
};
}
}, serverModules ) )
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,425
|
{
@Override
public void run()
{
long maxAge = clock.currentTimeMillis() - timeoutMillis;
transactionRegistry.rollbackSuspendedTransactionsIdleSince( maxAge );
}
}, runEvery, MILLISECONDS );
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,426
|
public abstract class AbstractNeoServer implements NeoServer
{
private static final long MINIMUM_TIMEOUT = 1000L;
/**
* We add a second to the timeout if the user configures a 1-second timeout.
*
* This ensures the expiry time displayed to the user is always at least 1 second, even after it is rounded down.
*/
private static final long ROUNDING_SECOND = 1000L;
protected final Logging logging;
protected Database database;
protected CypherExecutor cypherExecutor;
protected Configurator configurator;
protected WebServer webServer;
protected final StatisticCollector statisticsCollector = new StatisticCollector();
private PreFlightTasks preflight;
private final List<ServerModule> serverModules = new ArrayList<>();
private final SimpleUriBuilder uriBuilder = new SimpleUriBuilder();
private InterruptThreadTimer interruptStartupTimer;
private DatabaseActions databaseActions;
protected final ConsoleLogger log;
private RoundRobinJobScheduler rrdDbScheduler;
private RrdDbWrapper rrdDbWrapper;
private TransactionFacade transactionFacade;
private TransactionHandleRegistry transactionRegistry;
public AbstractNeoServer( Logging logging )
{
this.logging = logging;
this.log = logging.getConsoleLog( getClass() );
}
protected abstract PreFlightTasks createPreflightTasks();
protected abstract Iterable<ServerModule> createServerModules();
protected abstract Database createDatabase();
protected abstract WebServer createWebServer();
public void init()
{
this.preflight = createPreflightTasks();
this.database = createDatabase();
this.webServer = createWebServer();
for ( ServerModule moduleClass : createServerModules() )
{
registerModule( moduleClass );
}
}
@Override
public void start() throws ServerStartupException
{
interruptStartupTimer = createInterruptStartupTimer();
try
{
// Pre-flight tasks run outside the boot timeout limit
runPreflightTasks();
interruptStartupTimer.startCountdown();
try
{
database.start();
DiagnosticsManager diagnosticsManager = resolveDependency(DiagnosticsManager.class);
StringLogger diagnosticsLog = diagnosticsManager.getTargetLog();
diagnosticsLog.info( "--- SERVER STARTED START ---" );
databaseActions = createDatabaseActions();
// TODO: RrdDb is not needed once we remove the old webadmin
rrdDbScheduler = new RoundRobinJobScheduler( logging );
rrdDbWrapper = new RrdFactory( configurator.configuration(), logging )
.createRrdDbAndSampler( database, rrdDbScheduler );
transactionFacade = createTransactionalActions();
cypherExecutor = new CypherExecutor( database, logging.getMessagesLog( CypherExecutor.class ) );
configureWebServer();
cypherExecutor.start();
diagnosticsManager.register( Configurator.DIAGNOSTICS, configurator );
startModules();
startWebServer();
diagnosticsLog.info( "--- SERVER STARTED END ---" );
}
finally
{
interruptStartupTimer.stopCountdown();
}
}
catch ( Throwable t )
{
// Guard against poor operating systems that don't clear interrupt flags
// after having handled interrupts (looking at you, Bill).
Thread.interrupted();
if ( interruptStartupTimer.wasTriggered() )
{
// Make sure we don't leak rrd db files
stopRrdDb();
// If the database has been started, attempt to cleanly shut it down to avoid unclean shutdowns.
if(database.isRunning())
{
stopDatabase();
}
throw new ServerStartupException(
"Startup took longer than " + interruptStartupTimer.getTimeoutMillis() + "ms, " +
"and was stopped. You can disable this behavior by setting '" + Configurator
.STARTUP_TIMEOUT + "' to 0.",
1 );
}
throw new ServerStartupException( format( "Starting Neo4j Server failed: %s", t.getMessage() ), t );
}
}
public DependencyResolver getDependencyResolver()
{
return dependencyResolver;
}
protected DatabaseActions createDatabaseActions()
{
return new DatabaseActions(
new LeaseManager( SYSTEM_CLOCK ),
ForceMode.forced,
configurator.configuration().getBoolean(
SCRIPT_SANDBOXING_ENABLED_KEY,
DEFAULT_SCRIPT_SANDBOXING_ENABLED ), database.getGraph() );
}
private TransactionFacade createTransactionalActions()
{
final long timeoutMillis = getTransactionTimeoutMillis();
final Clock clock = SYSTEM_CLOCK;
transactionRegistry =
new TransactionHandleRegistry( clock, timeoutMillis, logging.getMessagesLog(TransactionRegistry.class) );
// ensure that this is > 0
long runEvery = round( timeoutMillis / 2.0 );
resolveDependency( JobScheduler.class ).scheduleRecurring( serverTransactionTimeout, new Runnable()
{
@Override
public void run()
{
long maxAge = clock.currentTimeMillis() - timeoutMillis;
transactionRegistry.rollbackSuspendedTransactionsIdleSince( maxAge );
}
}, runEvery, MILLISECONDS );
return new TransactionFacade(
new TransitionalPeriodTransactionMessContainer( database.getGraph() ),
new ExecutionEngine( database.getGraph(), logging.getMessagesLog( ExecutionEngine.class ) ),
transactionRegistry,
baseUri(), logging.getMessagesLog( TransactionFacade.class )
);
}
/**
* We are going to ensure the minimum timeout is 2 seconds. The timeout value is communicated to the user in
* seconds rounded down, meaning if a user set a 1 second timeout, he would be told there was less than 1 second
* remaining before he would need to renew the timeout.
*/
private long getTransactionTimeoutMillis()
{
final int timeout = configurator.configuration().getInt( TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT );
return Math.max( SECONDS.toMillis( timeout ), MINIMUM_TIMEOUT + ROUNDING_SECOND);
}
protected InterruptThreadTimer createInterruptStartupTimer()
{
long startupTimeout = SECONDS.toMillis(
getConfiguration().getInt( Configurator.STARTUP_TIMEOUT, Configurator.DEFAULT_STARTUP_TIMEOUT ) );
InterruptThreadTimer stopStartupTimer;
if ( startupTimeout > 0 )
{
log.log( "Setting startup timeout to: " + startupTimeout + "ms based on " + getConfiguration().getInt(
Configurator.STARTUP_TIMEOUT, -1 ) );
stopStartupTimer = InterruptThreadTimer.createTimer(
startupTimeout,
Thread.currentThread() );
}
else
{
stopStartupTimer = InterruptThreadTimer.createNoOpTimer();
}
return stopStartupTimer;
}
/**
* Use this method to register server modules from subclasses
*/
protected final void registerModule( ServerModule module )
{
serverModules.add( module );
}
private void startModules()
{
for ( ServerModule module : serverModules )
{
module.start();
}
}
private void stopModules()
{
new RunCarefully( map( new Function<ServerModule, Runnable>()
{
@Override
public Runnable apply( final ServerModule module )
{
return new Runnable()
{
@Override
public void run()
{
module.stop();
}
};
}
}, serverModules ) )
.run();
}
private void runPreflightTasks()
{
if ( !preflight.run() )
{
throw new PreflightFailedException( preflight.failedTask() );
}
}
@Override
public Configuration getConfiguration()
{
return configurator.configuration();
}
protected Logging getLogging()
{
return logging;
}
// TODO: Once WebServer is fully implementing LifeCycle,
// it should manage all but static (eg. unchangeable during runtime)
// configuration itself.
private void configureWebServer()
{
int webServerPort = getWebServerPort();
String webServerAddr = getWebServerAddress();
int maxThreads = getMaxThreads();
int sslPort = getHttpsPort();
boolean sslEnabled = getHttpsEnabled();
log.log( "Starting HTTP on port :%s with %d threads available", webServerPort, maxThreads );
webServer.setPort( webServerPort );
webServer.setAddress( webServerAddr );
webServer.setMaxThreads( maxThreads );
webServer.setEnableHttps( sslEnabled );
webServer.setHttpsPort( sslPort );
webServer.setWadlEnabled(
Boolean.valueOf( String.valueOf( getConfiguration().getProperty( Configurator.WADL_ENABLED ) ) ) );
webServer.setDefaultInjectables( createDefaultInjectables() );
if ( sslEnabled )
{
log.log( "Enabling HTTPS on port :%s", sslPort );
webServer.setHttpsCertificateInformation( initHttpsKeyStore() );
}
}
private int getMaxThreads()
{
return configurator.configuration()
.containsKey( Configurator.WEBSERVER_MAX_THREADS_PROPERTY_KEY ) ? configurator.configuration()
.getInt( Configurator.WEBSERVER_MAX_THREADS_PROPERTY_KEY ) : defaultMaxWebServerThreads();
}
private int defaultMaxWebServerThreads()
{
return 10 * Runtime.getRuntime()
.availableProcessors();
}
private void startWebServer()
{
try
{
setUpHttpLogging();
setUpTimeoutFilter();
webServer.start();
//noinspection deprecation
log.log( format( "Remote interface ready and available at [%s]", baseUri() ) );
}
catch ( RuntimeException e )
{
//noinspection deprecation
log.error( format( "Failed to start Neo Server on port [%d], reason [%s]",
getWebServerPort(), e.getMessage() ) );
throw e;
}
}
private void setUpHttpLogging()
{
if ( !httpLoggingProperlyConfigured() )
{
return;
}
String logLocation = getConfiguration().getString( Configurator.HTTP_LOG_CONFIG_LOCATION );
webServer.setHttpLoggingConfiguration( new File( logLocation ) );
}
private void setUpTimeoutFilter()
{
if ( !getConfiguration().containsKey( Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY ) )
{
return;
}
//noinspection deprecation
Guard guard = resolveDependency( Guard.class );
if ( guard == null )
{
throw new RuntimeException( format("Inconsistent configuration. In order to use %s, you must set %s.",
Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY,
GraphDatabaseSettings.execution_guard_enabled.name()) );
}
Filter filter = new GuardingRequestFilter( guard,
getConfiguration().getInt( Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY ) );
webServer.addFilter( filter, "/*" );
}
private boolean httpLoggingProperlyConfigured()
{
return loggingEnabled() && configLocated();
}
private boolean configLocated()
{
final Object property = getConfiguration().getProperty( Configurator.HTTP_LOG_CONFIG_LOCATION );
return property != null && new File( String.valueOf( property ) ).exists();
}
private boolean loggingEnabled()
{
return "true".equals( String.valueOf( getConfiguration().getProperty( Configurator.HTTP_LOGGING ) ) );
}
protected int getWebServerPort()
{
return configurator.configuration()
.getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT );
}
protected boolean getHttpsEnabled()
{
return configurator.configuration()
.getBoolean( Configurator.WEBSERVER_HTTPS_ENABLED_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_ENABLED );
}
protected int getHttpsPort()
{
return configurator.configuration()
.getInt( Configurator.WEBSERVER_HTTPS_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_HTTPS_PORT );
}
protected String getWebServerAddress()
{
return configurator.configuration()
.getString( Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_ADDRESS );
}
// TODO: This is jetty-specific, move to Jetty9WebServer
/**
* Jetty wants certificates stored in a key store, which is nice, but
* to make it easier for non-java savvy users, we let them put
* their certificates directly on the file system (advising appropriate
* permissions etc), like you do with Apache Web Server. On each startup
* we set up a key store for them with their certificate in it.
*/
protected KeyStoreInformation initHttpsKeyStore()
{
File keystorePath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_KEYSTORE_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_KEYSTORE_PATH ) );
File privateKeyPath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_HTTPS_KEY_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_KEY_PATH ) );
File certificatePath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_HTTPS_CERT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_CERT_PATH ) );
if ( !certificatePath.exists() )
{
//noinspection deprecation
log.log( "No SSL certificate found, generating a self-signed certificate.." );
SslCertificateFactory certFactory = new SslCertificateFactory();
certFactory.createSelfSignedCertificate( certificatePath, privateKeyPath, getWebServerAddress() );
}
KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
return keyStoreFactory.createKeyStore( keystorePath, privateKeyPath, certificatePath );
}
@Override
public void stop()
{
new RunCarefully(
new Runnable() {
@Override
public void run()
{
stopWebServer();
}
},
new Runnable() {
@Override
public void run()
{
stopModules();
}
},
new Runnable() {
@Override
public void run()
{
stopRrdDb();
}
},
new Runnable() {
@Override
public void run()
{
stopDatabase();
}
}
).run();
//noinspection deprecation
log.log( "Successfully shutdown database." );
}
private void stopRrdDb()
{
try
{
if( rrdDbScheduler != null) rrdDbScheduler.stopJobs();
if( rrdDbWrapper != null ) rrdDbWrapper.close();
log.log( "Successfully shutdown Neo4j Server." );
} catch(IOException e)
{
// If we fail on shutdown, we can't really recover from it. Log the issue and carry on.
log.error( "Unable to cleanly shut down statistics database.", e );
}
}
private void stopWebServer()
{
if ( webServer != null )
{
webServer.stop();
}
}
private void stopDatabase()
{
if ( database != null )
{
try
{
database.stop();
}
catch ( Throwable e )
{
throw new RuntimeException( e );
}
}
}
@Override
public Database getDatabase()
{
return database;
}
@Override
public TransactionRegistry getTransactionRegistry()
{
return transactionRegistry;
}
@Override
public URI baseUri()
{
return uriBuilder.buildURI( getWebServerAddress(), getWebServerPort(), false );
}
public URI httpsUri()
{
return uriBuilder.buildURI( getWebServerAddress(), getHttpsPort(), true );
}
public WebServer getWebServer()
{
return webServer;
}
@Override
public Configurator getConfigurator()
{
return configurator;
}
@Override
public PluginManager getExtensionManager()
{
if ( hasModule( RESTApiModule.class ) )
{
return getModule( RESTApiModule.class ).getPlugins();
}
else
{
return null;
}
}
protected Collection<InjectableProvider<?>> createDefaultInjectables()
{
Collection<InjectableProvider<?>> singletons = new ArrayList<>();
Database database = getDatabase();
singletons.add( new DatabaseProvider( database ) );
singletons.add( new DatabaseActions.Provider( databaseActions ) );
singletons.add( new GraphDatabaseServiceProvider( database ) );
singletons.add( new NeoServerProvider( this ) );
singletons.add( new ConfigurationProvider( getConfiguration() ) );
singletons.add( new RrdDbProvider( rrdDbWrapper ) );
singletons.add( new WebServerProvider( getWebServer() ) );
PluginInvocatorProvider pluginInvocatorProvider = new PluginInvocatorProvider( this );
singletons.add( pluginInvocatorProvider );
RepresentationFormatRepository repository = new RepresentationFormatRepository( this );
singletons.add( new InputFormatProvider( repository ) );
singletons.add( new OutputFormatProvider( repository ) );
singletons.add( new CypherExecutorProvider( cypherExecutor ) );
singletons.add( providerForSingleton( transactionFacade, TransactionFacade.class ) );
singletons.add( new TransactionFilter( database ) );
singletons.add( new LoggingProvider( logging ) );
return singletons;
}
private boolean hasModule( Class<? extends ServerModule> clazz )
{
for ( ServerModule sm : serverModules )
{
if ( sm.getClass() == clazz )
{
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
private <T extends ServerModule> T getModule( Class<T> clazz )
{
for ( ServerModule sm : serverModules )
{
if ( sm.getClass() == clazz )
{
return (T) sm;
}
}
return null;
}
protected <T> T resolveDependency( Class<T> type )
{
return dependencyResolver.resolveDependency( type );
}
private final DependencyResolver dependencyResolver = new DependencyResolver.Adapter()
{
private <T> T resolveKnownSingleDependency( Class<T> type )
{
if ( type.equals( Database.class ) )
{
//noinspection unchecked
return (T) database;
}
else if ( type.equals( PreFlightTasks.class ) )
{
//noinspection unchecked
return (T) preflight;
}
else if ( type.equals( InterruptThreadTimer.class ) )
{
//noinspection unchecked
return (T) interruptStartupTimer;
}
// TODO: Note that several component dependencies are inverted here. For instance, logging
// should be provided by the server to the kernel, not the other way around. Same goes for job
// scheduling and configuration. Probably several others as well.
DependencyResolver kernelDependencyResolver = database.getGraph().getDependencyResolver();
return kernelDependencyResolver.resolveDependency( type );
}
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
{
return selector.select( type, option( resolveKnownSingleDependency( type ) ) );
}
};
}
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,427
|
@Ignore( "Not a test, just a helper for DumpProcessInformationTest" )
public class DumpableProcess extends UnicastRemoteObject
{
public DumpableProcess() throws RemoteException
{
super();
}
public static void main( String[] args ) throws Exception
{
new DumpableProcess().traceableMethod( args[0] );
}
public synchronized void traceableMethod( String signal ) throws Exception
{
// The parent process will listen to this signal to know that it's here.
System.out.println( signal );
wait();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpableProcess.java
|
2,428
|
public class DumpVmInformation
{
public static void dumpVmInfo( File directory ) throws IOException
{
File file = new File( directory, "main-vm-dump-" + System.currentTimeMillis() );
PrintStream out = null;
try
{
out = new PrintStream( file );
dumpVmInfo( out );
}
finally
{
if ( out != null )
out.close();
}
}
public static void dumpVmInfo( PrintStream out )
{
// Find the top thread group
ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();
while ( topThreadGroup.getParent() != null )
topThreadGroup = topThreadGroup.getParent();
// Get all the thread groups under the top.
ThreadGroup[] allGroups = new ThreadGroup[1000];
topThreadGroup.enumerate( allGroups, true );
// Dump the info.
for ( ThreadGroup group : allGroups )
{
if ( group == null )
break;
dumpThreadGroupInfo( group, out );
}
dumpThreadGroupInfo( topThreadGroup, out );
}
public static void dumpThreadGroupInfo( ThreadGroup tg, PrintStream out )
{
String parentName = (tg.getParent() == null ? null : tg.getParent().getName());
// Dump thread group info.
out.println( "---- GROUP:" + tg.getName() +
(parentName != null ? " parent:" + parentName : "" ) +
(tg.isDaemon() ? " daemon" : "" ) +
(tg.isDestroyed() ? " destroyed" : "" ) +
" ----" );
// Dump info for each thread.
Thread[] allThreads = new Thread[1000];
tg.enumerate( allThreads, false );
for ( Thread thread : allThreads )
{
if ( thread == null )
break;
out.println(
"\"" + thread.getName() + "\"" +
(thread.isDaemon() ? " daemon" : "") +
" prio=" + thread.getPriority() +
" tid=" + thread.getId() +
" " + thread.getState().name().toLowerCase() );
out.println( " " + State.class.getName() + ": " + thread.getState().name() );
for ( StackTraceElement element : thread.getStackTrace() )
{
out.println( "\tat " + element );
}
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpVmInformation.java
|
2,429
|
public class DumpProcessInformationTest
{
@Test
public void shouldDumpProcessInformation() throws Exception
{
// GIVEN
// a process spawned from this test which pauses at a specific point of execution
Process process = getRuntime().exec( new String[] { "java", "-cp", getProperty( "java.class.path" ),
DumpableProcess.class.getName(), SIGNAL } );
awaitSignal( process );
// WHEN
// dumping process information for that spawned process (knowing it's in the expected position)
DumpProcessInformation dumper = new DumpProcessInformation( new DevNullLoggingService(), directory );
Pair<Long, String> pid = single( dumper.getJPids( stringContains( DumpableProcess.class.getSimpleName() ) ) );
File threaddumpFile = dumper.doThreadDump( pid );
process.destroy();
// THEN
// the produced thread dump should contain that expected method at least
assertTrue( fileContains( threaddumpFile, "traceableMethod", DumpableProcess.class.getName() ) );
}
private boolean fileContains( File file, String... expectedStrings )
{
Set<String> expectedStringSet = asSet( expectedStrings );
for ( String line : asIterable( file, "UTF-8" ) )
{
Iterator<String> expectedStringIterator = expectedStringSet.iterator();
while ( expectedStringIterator.hasNext() )
{
if ( line.contains( expectedStringIterator.next() ) )
{
expectedStringIterator.remove();
}
}
}
return expectedStringSet.isEmpty();
}
private static final String SIGNAL = "here";
private final File directory = TargetDirectory.forTest( getClass() ).cleanDirectory( "dump" );
private void awaitSignal( Process process ) throws IOException
{
try ( BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) ) )
{
String line = reader.readLine();
if ( !SIGNAL.equals( line ) )
{
fail( "Got weird signal " + line );
}
// We got signal, great
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformationTest.java
|
2,430
|
{
@Override
public Void call() throws Exception
{
dump();
return null;
}
}, duration, timeUnit );
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformationRule.java
|
2,431
|
{
@Override
public void dump() throws Exception
{
new DumpProcessInformation( new SystemOutLogging(), baseDir ).doThreadDump( processFilter );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformationRule.java
|
2,432
|
{
@Override
public void dump()
{
DumpVmInformation.dumpVmInfo( out );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformationRule.java
|
2,433
|
public class DumpProcessInformationRule extends ExternalResource
{
public interface Dump
{
void dump() throws Exception;
}
public static Dump localVm( final PrintStream out )
{
return new Dump()
{
@Override
public void dump()
{
DumpVmInformation.dumpVmInfo( out );
}
};
}
public static Dump otherVm( final Predicate<String> processFilter, final File baseDir )
{
return new Dump()
{
@Override
public void dump() throws Exception
{
new DumpProcessInformation( new SystemOutLogging(), baseDir ).doThreadDump( processFilter );
}
};
}
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool( 2 );
private final long duration;
private final TimeUnit timeUnit;
private volatile ScheduledFuture<?> thunk = null;
private final Dump[] dumps;
/**
* Dumps process information about processes on the local machine, filtered by processFilter
*/
public DumpProcessInformationRule( long duration, TimeUnit timeUnit, Dump... dumps )
{
this.duration = duration;
this.timeUnit = timeUnit;
this.dumps = dumps;
}
@Override
protected synchronized void before() throws Throwable
{
if ( null == thunk )
{
super.before();
thunk = executor.schedule( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
dump();
return null;
}
}, duration, timeUnit );
}
else
{
throw new IllegalStateException( "process dumping thunk already started" );
}
}
@Override
protected synchronized void after()
{
if ( null != thunk && !thunk.isDone() )
{
thunk.cancel( true );
}
thunk = null;
super.after();
}
public void dump() throws Exception
{
for ( Dump dump : dumps )
{
dump.dump();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformationRule.java
|
2,434
|
public class DumpProcessInformation
{
public static void main( String[] args ) throws Exception
{
Args arg = new Args( args == null ? new String[0] : args );
boolean doHeapDump = arg.getBoolean( "heap", false, true );
String[] containing = arg.orphans().toArray( new String[arg.orphans().size()] );
String dumpDir = arg.get( "dir", "data" );
new DumpProcessInformation( new SystemOutLogging(), new File( dumpDir ) ).dumpRunningProcesses(
doHeapDump, containing );
}
private final StringLogger logger;
private final File outputDirectory;
public DumpProcessInformation( Logging logging, File outputDirectory )
{
this.logger = logging.getMessagesLog( getClass() );
this.outputDirectory = outputDirectory;
}
public void dumpRunningProcesses( boolean includeHeapDump, String... javaPidsContainingClassNames )
throws Exception
{
outputDirectory.mkdirs();
for ( Pair<Long, String> pid : getJPids( in( javaPidsContainingClassNames ) ) )
{
doThreadDump( pid );
if ( includeHeapDump )
{
doHeapDump( pid );
}
}
}
public File doThreadDump( Pair<Long, String> pid ) throws Exception
{
File outputFile = new File( outputDirectory, fileName( "threaddump", pid ) );
logger.info( "Creating thread dump of " + pid + " to " + outputFile.getAbsolutePath() );
String[] cmdarray = new String[] {"jstack", "" + pid.first()};
Process process = Runtime.getRuntime().exec( cmdarray );
writeProcessOutputToFile( process, outputFile );
return outputFile;
}
public void doHeapDump( Pair<Long, String> pid ) throws Exception
{
File outputFile = new File( outputDirectory, fileName( "heapdump", pid ) );
logger.info( "Creating heap dump of " + pid + " to " + outputFile.getAbsolutePath() );
String[] cmdarray = new String[] {"jmap", "-dump:file=" + outputFile.getAbsolutePath(), "" + pid.first() };
Runtime.getRuntime().exec( cmdarray ).waitFor();
}
public void doThreadDump( Predicate<String> processFilter ) throws Exception
{
for ( Pair<Long,String> pid : getJPids( processFilter ) )
{
doThreadDump( pid );
}
}
public Collection<Pair<Long, String>> getJPids( Predicate<String> filter ) throws Exception
{
Process process = Runtime.getRuntime().exec( new String[] { "jps", "-l" } );
BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
String line = null;
Collection<Pair<Long, String>> jPids = new ArrayList<>(), excludedJPids = new ArrayList<>();
while ( (line = reader.readLine()) != null )
{
int spaceIndex = line.indexOf( ' ' );
String name = line.substring( spaceIndex + 1 );
// Work-around for a windows problem where if your java.exe is in a directory
// containing spaces the value in the second column from jps output will be
// something like "C:\Program" if it was under "C:\Program Files\Java..."
// If that's the case then use the PID instead
if ( name.contains( ":" ) )
{
String pid = line.substring( 0, spaceIndex );
name = pid;
}
Pair<Long, String> pid = Pair.of( Long.parseLong( line.substring( 0, spaceIndex ) ), name );
if ( name.contains( DumpProcessInformation.class.getSimpleName() ) ||
name.contains( "Jps" ) ||
name.contains( "eclipse.equinox" ) ||
!filter.accept( name ) )
{
excludedJPids.add( pid );
continue;
}
jPids.add( pid );
}
process.waitFor();
logger.info( "Found jPids:" + jPids + ", excluded:" + excludedJPids );
return jPids;
}
private void writeProcessOutputToFile( Process process, File outputFile ) throws Exception
{
BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
String line = null;
try ( PrintStream out = new PrintStream( outputFile ) )
{
while ( (line = reader.readLine()) != null )
{
out.println( line );
}
}
process.waitFor();
}
private static String fileName( String category, Pair<Long,String> pid )
{
return time().replace( ':', '_' ).replace( '.', '_' ) +
"-" + category +
"-" + pid.first() +
"-" + pid.other();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_qa_tooling_DumpProcessInformation.java
|
2,435
|
public class ProcessHelper
{
public static void exec( File directory, String program, String... arguments ) throws IOException, InterruptedException
{
List<String> programPlusArgs = new ArrayList<String>( asList( program ) );
programPlusArgs.addAll( asList( arguments ) );
int resultCode = new ProcessBuilder( programPlusArgs )
.directory( directory )
.start().waitFor();
assertEquals( programPlusArgs.toString(), 0, resultCode );
}
}
| false
|
packaging_qa_src_test_java_org_neo4j_qa_features_support_ProcessHelper.java
|
2,436
|
public class FileHelper
{
public static void copyFile( File srcFile, File dstFile ) throws IOException
{
//noinspection ResultOfMethodCallIgnored
dstFile.getParentFile().mkdirs();
FileInputStream input = null;
FileOutputStream output = null;
try
{
input = new FileInputStream( srcFile );
output = new FileOutputStream( dstFile );
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ( (bytesRead = input.read( buffer )) != -1 )
{
output.write( buffer, 0, bytesRead );
}
}
catch ( IOException e )
{
// Because the message from this cause may not mention which file it's about
throw new IOException( "Could not copy '" + srcFile + "' to '" + dstFile + "'", e );
}
finally
{
if ( input != null )
{
input.close();
}
if ( output != null )
{
output.close();
}
}
}
}
| false
|
packaging_qa_src_test_java_org_neo4j_qa_features_support_FileHelper.java
|
2,437
|
public class StartAndStopFeatureTest
{
@Before
public void The_Neo4j_package_is_expanded_at_neo4j_home() throws Exception
{
String product = "neo4j-community";
String version = System.getProperty( "project_version" );
String platform = "unix";
String archiveName = product + "-" + version + "-" + platform + ".tar.gz";
File copiedArchive = new File( workingDirectory, archiveName );
copyFile( new File( "../standalone/target/" + archiveName ), copiedArchive );
exec( workingDirectory, "tar", "xzf", copiedArchive.getName() );
neo4jHome = new File( workingDirectory, product + "-" + version );
}
@Test
public void The_Neo4j_server_should_start_and_stop_using_a_command_line_script() throws Exception
{
When_I_start_Neo4j_Server();
And_wait_for_Server_started_at( "http://localhost:7474" );
Then_it_should_provide_the_Neo4j_REST_interface_at( "http://localhost:7474" );
When_I_stop_Neo4j_Server();
And_wait_for_Server_stopped_at( "http://localhost:7474" );
Then_it_should_not_provide_the_Neo4j_REST_interface_at( "http://localhost:7474" );
}
private final File workingDirectory = new File( "target/test-data/" + getClass().getName() );
private File neo4jHome;
private void When_I_start_Neo4j_Server() throws Exception
{
exec( neo4jHome, "bin/neo4j", "start" );
}
private void When_I_stop_Neo4j_Server() throws Exception
{
exec( neo4jHome, "bin/neo4j", "stop" );
}
private void And_wait_for_Server_started_at( String uri ) throws IOException, InterruptedException
{
boolean success = false;
long startTime = System.currentTimeMillis();
while ( !success && System.currentTimeMillis() - startTime < 60000 )
{
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
success = statusCode( uri, httpClient ) == 200;
}
catch ( ConnectException e )
{
System.out.println( "Connection refused, sleeping" );
}
finally
{
httpClient.getConnectionManager().shutdown();
}
Thread.sleep( 1000 );
}
assertTrue( "Timed out waiting for " + uri, success );
}
private void And_wait_for_Server_stopped_at( String uri ) throws IOException, InterruptedException
{
DefaultHttpClient httpClient = new DefaultHttpClient();
boolean success = false;
long startTime = System.currentTimeMillis();
while ( !success && System.currentTimeMillis() - startTime < 6000 )
{
try
{
statusCode( uri, httpClient );
System.out.println( "Connection still available, sleeping" );
}
catch ( ConnectException e )
{
success = true;
}
Thread.sleep( 1000 );
}
assertTrue( "Timed out waiting for " + uri, success );
}
private void Then_it_should_provide_the_Neo4j_REST_interface_at( String uri ) throws Exception
{
assertEquals( 200, statusCode( uri, new DefaultHttpClient() ) );
}
private void Then_it_should_not_provide_the_Neo4j_REST_interface_at( String uri ) throws Exception
{
try
{
statusCode( uri, new DefaultHttpClient() );
fail( "Should refuse connections" );
}
catch ( ConnectException e )
{
// expected
}
}
private int statusCode( String uri, DefaultHttpClient httpClient ) throws IOException
{
HttpResponse response = httpClient.execute( new HttpGet( uri ) );
EntityUtils.toString( response.getEntity() );
return response.getStatusLine().getStatusCode();
}
}
| false
|
packaging_qa_src_test_java_org_neo4j_qa_features_StartAndStopFeatureTest.java
|
2,438
|
public class MemoryMappingConfiguration
{
public static void addLegacyMemoryMappingConfiguration( Map<String, String> config, String totalMappedMemory )
{
long mappedMemory = Settings.BYTES.apply( totalMappedMemory );
long memoryUnit = mappedMemory / 472;
config.put( "neostore.nodestore.db.mapped_memory", mega( 20 * memoryUnit ) );
config.put( "neostore.propertystore.db.mapped_memory", mega( 90 * memoryUnit ) );
config.put( "neostore.propertystore.db.index.mapped_memory", mega( 1 * memoryUnit ) );
config.put( "neostore.propertystore.db.index.keys.mapped_memory", mega( 1 * memoryUnit ) );
config.put( "neostore.propertystore.db.strings.mapped_memory", mega( 130 * memoryUnit ) );
config.put( "neostore.propertystore.db.arrays.mapped_memory", mega( 130 * memoryUnit ) );
config.put( "neostore.relationshipstore.db.mapped_memory", mega( 100 * memoryUnit ) );
}
private static String mega( long bytes )
{
return (bytes / 1024 / 1024) + "M";
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_windowpool_MemoryMappingConfiguration.java
|
2,439
|
private static abstract class SettingAdapter<FROM, TO> extends Setting<TO>
{
private final Setting<FROM> source;
SettingAdapter( Setting<FROM> source )
{
super( source.name, null );
this.source = source;
}
@Override
TO parse( String value )
{
return adapt( source.parse( value ) );
}
abstract TO adapt( FROM value );
@Override
TO defaultValue()
{
return adapt( source.defaultValue() );
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,440
|
{
@Override
TO adapt( FROM value )
{
return conversion.convert( value );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,441
|
{
@Override
List<T> parse( String value )
{
if ( value.trim().equals( "" ) )
{
return emptyList();
}
String[] parts = value.split( "," );
List<T> result = new ArrayList<T>( parts.length );
for ( String part : parts )
{
result.add( singleSetting.parse( part ) );
}
return result;
}
@Override
public String asString( List<T> value )
{
StringBuilder result = new StringBuilder();
Iterator<T> iterator = value.iterator();
while ( iterator.hasNext() )
{
result.append( singleSetting.asString( iterator.next() ) );
if ( iterator.hasNext() )
{
result.append( ',' );
}
}
return result.toString();
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,442
|
new Runnable() {
@Override
public void run()
{
stopWebServer();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,443
|
new Runnable() {
@Override
public void run()
{
stopRrdDb();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,444
|
{
@Override
T parse( String value )
{
return Enum.valueOf( enumType, value );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,445
|
new Runnable() {
@Override
public void run()
{
stopDatabase();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,446
|
public class NeoServerDefaultPortAndHostnameDocIT extends AbstractRestFunctionalTestBase
{
@Test
public void shouldDefaultToSensiblePortIfNoneSpecifiedInConfig() throws Exception {
FunctionalTestHelper functionalTestHelper = new FunctionalTestHelper(server());
JaxRsResponse response = functionalTestHelper.get(functionalTestHelper.webAdminUri());
assertThat(response.getStatus(), is(200));
}
@Test
public void shouldDefaultToLocalhostOfNoneSpecifiedInConfig() throws Exception {
assertThat(server().baseUri().getHost(), is("localhost"));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_NeoServerDefaultPortAndHostnameDocIT.java
|
2,447
|
@Provider
public class LoggingProvider extends InjectableProvider<Logging>
{
private final Logging logging;
public LoggingProvider( Logging logging )
{
super( Logging.class );
this.logging = logging;
}
@Override
public Logging getValue( HttpContext c )
{
return logging;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_LoggingProvider.java
|
2,448
|
public class JAXRSHelper
{
public static List<String> listFrom( String... strings )
{
ArrayList<String> al = new ArrayList<String>();
if ( strings != null )
{
al.addAll( Arrays.asList( strings ) );
}
return al;
}
public static URI generateUriFor( URI baseUri, String serviceName )
{
if ( serviceName.startsWith( "/" ) )
{
serviceName = serviceName.substring( 1 );
}
StringBuilder sb = new StringBuilder();
try
{
String baseUriString = baseUri.toString();
sb.append( baseUriString );
if ( !baseUriString.endsWith( "/" ) )
{
sb.append( "/" );
}
sb.append( serviceName );
return new URI( sb.toString() );
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_JAXRSHelper.java
|
2,449
|
private static class NoOpInterruptThreadTimer extends InterruptThreadTimer
{
private State state = State.IDLE;
public NoOpInterruptThreadTimer()
{
}
@Override
public void startCountdown()
{
state = State.COUNTING;
}
@Override
public void stopCountdown()
{
state = State.IDLE;
}
@Override
public State getState()
{
return state;
}
@Override
public boolean wasTriggered()
{
return false;
}
@Override
public long getTimeoutMillis() {
return 0;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_InterruptThreadTimer.java
|
2,450
|
public static class InterruptThreadTask extends TimerTask
{
private final Thread threadToInterrupt;
private boolean wasExecuted = false;
public InterruptThreadTask(Thread threadToInterrupt)
{
this.threadToInterrupt = threadToInterrupt;
}
@Override
public void run()
{
wasExecuted = true;
threadToInterrupt.interrupt();
}
public boolean wasExecuted()
{
return this.wasExecuted;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_InterruptThreadTimer.java
|
2,451
|
private static class ActualInterruptThreadTimer extends InterruptThreadTimer
{
private final Timer timer = new Timer();
private final InterruptThreadTask task;
private final long timeout;
private State state = State.IDLE;
public ActualInterruptThreadTimer(long timeoutMillis, Thread threadToInterrupt)
{
this.task = new InterruptThreadTask(threadToInterrupt);
this.timeout = timeoutMillis;
}
@Override
public void startCountdown()
{
state = State.COUNTING;
timer.schedule(task, timeout);
}
@Override
public void stopCountdown()
{
state = State.IDLE;
timer.cancel();
}
@Override
public State getState()
{
switch ( state )
{
case IDLE:
return State.IDLE;
case COUNTING:
default:
// We don't know if the timeout has triggered at this point,
// so we need to check that
if ( wasTriggered() )
{
state = State.IDLE;
}
return state;
}
}
@Override
public boolean wasTriggered()
{
return task.wasExecuted();
}
@Override
public long getTimeoutMillis() {
return timeout;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_InterruptThreadTimer.java
|
2,452
|
public abstract class InterruptThreadTimer
{
public enum State
{
COUNTING,
IDLE
}
public static class InterruptThreadTask extends TimerTask
{
private final Thread threadToInterrupt;
private boolean wasExecuted = false;
public InterruptThreadTask(Thread threadToInterrupt)
{
this.threadToInterrupt = threadToInterrupt;
}
@Override
public void run()
{
wasExecuted = true;
threadToInterrupt.interrupt();
}
public boolean wasExecuted()
{
return this.wasExecuted;
}
}
public static InterruptThreadTimer createTimer(long timeoutMillis, Thread threadToInterrupt)
{
return new ActualInterruptThreadTimer(timeoutMillis, threadToInterrupt);
}
public static InterruptThreadTimer createNoOpTimer()
{
return new NoOpInterruptThreadTimer();
}
private static class ActualInterruptThreadTimer extends InterruptThreadTimer
{
private final Timer timer = new Timer();
private final InterruptThreadTask task;
private final long timeout;
private State state = State.IDLE;
public ActualInterruptThreadTimer(long timeoutMillis, Thread threadToInterrupt)
{
this.task = new InterruptThreadTask(threadToInterrupt);
this.timeout = timeoutMillis;
}
@Override
public void startCountdown()
{
state = State.COUNTING;
timer.schedule(task, timeout);
}
@Override
public void stopCountdown()
{
state = State.IDLE;
timer.cancel();
}
@Override
public State getState()
{
switch ( state )
{
case IDLE:
return State.IDLE;
case COUNTING:
default:
// We don't know if the timeout has triggered at this point,
// so we need to check that
if ( wasTriggered() )
{
state = State.IDLE;
}
return state;
}
}
@Override
public boolean wasTriggered()
{
return task.wasExecuted();
}
@Override
public long getTimeoutMillis() {
return timeout;
}
}
private static class NoOpInterruptThreadTimer extends InterruptThreadTimer
{
private State state = State.IDLE;
public NoOpInterruptThreadTimer()
{
}
@Override
public void startCountdown()
{
state = State.COUNTING;
}
@Override
public void stopCountdown()
{
state = State.IDLE;
}
@Override
public State getState()
{
return state;
}
@Override
public boolean wasTriggered()
{
return false;
}
@Override
public long getTimeoutMillis() {
return 0;
}
}
public abstract void startCountdown();
public abstract void stopCountdown();
public abstract boolean wasTriggered();
public abstract State getState();
public abstract long getTimeoutMillis();
}
| false
|
community_server_src_main_java_org_neo4j_server_InterruptThreadTimer.java
|
2,453
|
{
public void checkClientTrusted( X509Certificate[] arg0, String arg1 )
throws CertificateException
{
}
public void checkServerTrusted( X509Certificate[] arg0, String arg1 )
throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}};
| false
|
community_server_src_test_java_org_neo4j_server_HttpsEnabledDocIT.java
|
2,454
|
public class HttpsEnabledDocIT extends ExclusiveServerTestBase
{
private CommunityNeoServer server;
public @Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
@After
public void stopTheServer()
{
server.stop();
}
@Test
public void serverShouldSupportSsl() throws Exception
{
server = server().withHttpsEnabled()
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
assertThat( server.getHttpsEnabled(), is( true ) );
trustAllSslCerts();
assertThat( GET(server.httpsUri().toASCIIString()).status(), is( 200 ) );
}
@Test
public void webadminShouldBeRetrievableViaSsl() throws Exception
{
server = server().withHttpsEnabled()
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
assertThat( server.getHttpsEnabled(), is( true ) );
trustAllSslCerts();
assertThat( GET(server.httpsUri().toASCIIString() + "webadmin/" ).status(), is( 200 ) );
}
private void trustAllSslCerts()
{
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager()
{
public void checkClientTrusted( X509Certificate[] arg0, String arg1 )
throws CertificateException
{
}
public void checkServerTrusted( X509Certificate[] arg0, String arg1 )
throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}};
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance( "TLS" );
sc.init( null, trustAllCerts, new SecureRandom() );
HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() );
}
catch ( Exception e )
{
;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_HttpsEnabledDocIT.java
|
2,455
|
public class DatabaseTuningDocIT extends ExclusiveServerTestBase
{
@Ignore("Relies on internal config, which is bad")
@Test
public void shouldLoadAKnownGoodPropertyFile() throws IOException
{
CommunityNeoServer server = CommunityServerBuilder.server()
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.withDefaultDatabaseTuning()
.build();
server.start();
Map<Object, Object> params = null; // TODO This relies on internal stuff,
// which is no good: server.getDatabase().graph.getConfig().getParams();
assertTrue( propertyAndValuePresentIn( "neostore.nodestore.db.mapped_memory", "25M", params ) );
assertTrue( propertyAndValuePresentIn( "neostore.relationshipstore.db.mapped_memory", "50M", params ) );
assertTrue( propertyAndValuePresentIn( "neostore.propertystore.db.mapped_memory", "90M", params ) );
assertTrue( propertyAndValuePresentIn( "neostore.propertystore.db.strings.mapped_memory", "130M", params ) );
assertTrue( propertyAndValuePresentIn( "neostore.propertystore.db.arrays.mapped_memory", "130M", params ) );
server.stop();
}
private boolean propertyAndValuePresentIn( String name, String value, Map<Object, Object> params )
{
Object paramValue = params.get( name );
return paramValue != null && paramValue.toString().equals( value );
}
@Test
public void shouldLogWarningAndContinueIfTuningFilePropertyDoesNotResolve() throws IOException
{
Logging logging = new BufferingLogging();
NeoServer server = CommunityServerBuilder.server()
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.withNonResolvableTuningFile()
.withLogging( logging )
.build();
server.start();
String logDump = logging.toString();
assertThat( logDump,
containsString( String.format( "The specified file for database performance tuning properties [" ) ) );
assertThat( logDump, containsString( String.format( "] does not exist." ) ) );
server.stop();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_DatabaseTuningDocIT.java
|
2,456
|
public class CommunityNeoServer extends AbstractNeoServer
{
public CommunityNeoServer( Logging logging )
{
super( logging );
}
public CommunityNeoServer( Configurator configurator, Logging logging )
{
super( logging );
this.configurator = configurator;
init();
}
@Override
protected PreFlightTasks createPreflightTasks()
{
return new PreFlightTasks( logging,
// TODO: Move the config check into bootstrapper
//new EnsureNeo4jPropertiesExist(configurator.configuration()),
new EnsurePreparedForHttpLogging(configurator.configuration()),
new PerformUpgradeIfNecessary(getConfiguration(),
configurator.getDatabaseTuningProperties(), System.out, logging),
new PerformRecoveryIfNecessary(getConfiguration(),
configurator.getDatabaseTuningProperties(), System.out, logging));
}
@Override
protected Iterable<ServerModule> createServerModules()
{
return Arrays.asList(
new DiscoveryModule(webServer, logging),
new RESTApiModule(webServer, database, configurator.configuration(), logging),
new ManagementApiModule(webServer, configurator.configuration(), logging),
new ThirdPartyJAXRSModule(webServer, configurator, logging, this),
new WebAdminModule(webServer, logging),
new Neo4jBrowserModule(webServer, configurator.configuration(), logging, database),
new StatisticModule(webServer, statisticsCollector, configurator.configuration()),
new SecurityRulesModule(webServer, configurator.configuration(), logging));
}
@Override
protected Database createDatabase()
{
return new CommunityDatabase( configurator, logging );
}
@Override
protected WebServer createWebServer()
{
return new Jetty9WebServer( logging );
}
@Override
public Iterable<AdvertisableService> getServices()
{
List<AdvertisableService> toReturn = new ArrayList<AdvertisableService>( 3 );
toReturn.add( new ConsoleService( null, null, logging, null ) );
toReturn.add( new JmxService( null, null ) );
toReturn.add( new MonitorService( null, null ) );
return toReturn;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_CommunityNeoServer.java
|
2,457
|
public class CommunityBootstrapper extends Bootstrapper
{
@Override
protected NeoServer createNeoServer()
{
return new CommunityNeoServer( configurator, logging );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_CommunityBootstrapper.java
|
2,458
|
private static class MoreDerivedBootstrapper extends CommunityBootstrapper
{
}
| false
|
community_server_src_test_java_org_neo4j_server_BootstrapperTest.java
|
2,459
|
public class BootstrapperTest
{
@Test
public void shouldFindTheMostDerivedType() throws Exception
{
Bootstrapper bs = new CommunityBootstrapper();
Bootstrapper other = new MoreDerivedBootstrapper();
assertFalse( bs.isMoreDerivedThan( other ) );
assertTrue( other.isMoreDerivedThan( bs ) );
}
private static class MoreDerivedBootstrapper extends CommunityBootstrapper
{
}
}
| false
|
community_server_src_test_java_org_neo4j_server_BootstrapperTest.java
|
2,460
|
{
@Override
public void run()
{
log.log( "Neo4j Server shutdown initiated by request" );
if ( server != null )
{
server.stop();
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_Bootstrapper.java
|
2,461
|
public abstract class Bootstrapper
{
public static final Integer OK = 0;
public static final Integer WEB_SERVER_STARTUP_ERROR_CODE = 1;
public static final Integer GRAPH_DATABASE_STARTUP_ERROR_CODE = 2;
protected final LifeSupport life = new LifeSupport();
protected NeoServer server;
protected Configurator configurator;
private Thread shutdownHook;
protected Logging logging;
private ConsoleLogger log;
public static void main( String[] args )
{
Bootstrapper bootstrapper = loadMostDerivedBootstrapper();
Integer exit = bootstrapper.start( args );
if ( exit != 0 )
{
System.exit( exit );
}
}
public static Bootstrapper loadMostDerivedBootstrapper()
{
Bootstrapper winner = new CommunityBootstrapper();
for ( Bootstrapper candidate : Service.load( Bootstrapper.class ) )
{
if ( candidate.isMoreDerivedThan( winner ) )
{
winner = candidate;
}
}
return winner;
}
public void controlEvent( int arg )
{
// Do nothing, required by the WrapperListener interface
}
public Integer start()
{
return start( new String[0] );
}
// TODO: This does not use args, check if it is safe to remove them
public Integer start( String[] args )
{
try
{
BufferingConsoleLogger consoleBuffer = new BufferingConsoleLogger();
configurator = createConfigurator( consoleBuffer );
logging = createLogging( configurator );
log = logging.getConsoleLog( getClass() );
consoleBuffer.replayInto( log );
life.start();
checkCompatibility();
server = createNeoServer();
server.start();
addShutdownHook();
return OK;
}
catch ( TransactionFailureException tfe )
{
log.error( format( "Failed to start Neo Server on port [%d], because ",
configurator.configuration().getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT ) )
+ tfe + ". Another process may be using database location " + server.getDatabase()
.getLocation(), tfe );
return GRAPH_DATABASE_STARTUP_ERROR_CODE;
}
catch ( IllegalArgumentException e )
{
log.error( format( "Failed to start Neo Server on port [%s]",
configurator.configuration().getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT ) ), e );
return WEB_SERVER_STARTUP_ERROR_CODE;
}
catch ( Exception e )
{
log.error( format( "Failed to start Neo Server on port [%s]",
configurator.configuration().getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT ) ), e );
return WEB_SERVER_STARTUP_ERROR_CODE;
}
}
private Logging createLogging( Configurator configurator )
{
Config config = new Config( configurator.getDatabaseTuningProperties() );
return life.add( DefaultLogging.createDefaultLogging( config ) );
}
private void checkCompatibility()
{
new JvmChecker( logging.getMessagesLog( JvmChecker.class ),
new JvmMetadataRepository() ).checkJvmCompatibilityAndIssueWarning();
}
protected abstract NeoServer createNeoServer();
public void stop()
{
stop( 0 );
}
public int stop( int stopArg )
{
String location = "unknown location";
try
{
if ( server != null )
{
server.stop();
}
log.log( "Successfully shutdown Neo Server on port [%d], database [%s]",
configurator.configuration().getInt(Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT),
location );
removeShutdownHook();
life.shutdown();
return 0;
}
catch ( Exception e )
{
log.error( "Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ",
configurator.configuration().getInt(Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT), location, e.getMessage(), e );
return 1;
}
}
protected void removeShutdownHook()
{
if ( shutdownHook != null )
{
if ( !Runtime.getRuntime().removeShutdownHook( shutdownHook ) )
{
log.warn( "Unable to remove shutdown hook" );
}
}
}
public NeoServer getServer()
{
return server;
}
protected void addShutdownHook()
{
shutdownHook = new Thread()
{
@Override
public void run()
{
log.log( "Neo4j Server shutdown initiated by request" );
if ( server != null )
{
server.stop();
}
}
};
Runtime.getRuntime()
.addShutdownHook( shutdownHook );
}
protected Configurator createConfigurator( ConsoleLogger log )
{
File configFile = new File( System.getProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY,
Configurator.DEFAULT_CONFIG_DIR ) );
return new PropertyFileConfigurator( new Validator( new DatabaseLocationMustBeSpecifiedRule() ),
configFile, log );
}
protected boolean isMoreDerivedThan( Bootstrapper other )
{
// Default implementation just checks if this is a subclass of other
return other.getClass()
.isAssignableFrom( getClass() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_Bootstrapper.java
|
2,462
|
public class BatchOperationHeaderDocIT extends ExclusiveServerTestBase
{
private NeoServer server;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void cleanTheDatabase() throws IOException
{
server = server().withThirdPartyJaxRsPackage( "org.dummy.web.service",
DUMMY_WEB_SERVICE_MOUNT_POINT ).usingDatabaseDir( folder.getRoot().getAbsolutePath() ).build();
server.start();
}
@After
public void stopServer()
{
if ( server != null )
{
server.stop();
}
}
@Test
public void shouldPassHeaders() throws Exception
{
String jsonData = new PrettyJSON()
.array()
.object()
.key( "method" ).value( "GET" )
.key( "to" ).value( "../.." + DUMMY_WEB_SERVICE_MOUNT_POINT + "/needs-auth-header" )
.key( "body" ).object().endObject()
.endObject()
.endArray()
.toString();
JaxRsResponse response = new RestRequest( null, "user", "pass" )
.post( "http://localhost:7474/db/data/batch", jsonData );
assertEquals( 200, response.getStatus() );
final List<Map<String, Object>> responseData = jsonToList( response.getEntity() );
Map<String, Object> res = (Map<String, Object>) responseData.get( 0 ).get( "body" );
/*
* {
* Accept=[application/json],
* Content-Type=[application/json],
* Authorization=[Basic dXNlcjpwYXNz],
* User-Agent=[Java/1.6.0_27] <-- ignore that, it changes often
* Host=[localhost:7474],
* Connection=[keep-alive],
* Content-Length=[86]
* }
*/
assertEquals( "Basic dXNlcjpwYXNz", res.get( "Authorization" ) );
assertEquals( "application/json", res.get( "Accept" ) );
assertEquals( "application/json", res.get( "Content-Type" ) );
assertEquals( "localhost:7474", res.get( "Host" ) );
assertEquals( "keep-alive", res.get( "Connection" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_BatchOperationHeaderDocIT.java
|
2,463
|
public class AcceptorConfigurationIT extends ExclusiveServerTestBase
{
private CommunityNeoServer server;
@After
public void stopTheServer()
{
server.stop();
}
@Test
public void serverShouldNotHangWithThreadPoolSizeSmallerThanCpuCount() throws Exception
{
server = server().withMaxJettyThreads( 3 )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
assertThat( GET(server.baseUri().toString()).status(), is( 200 ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_AcceptorConfigurationIT.java
|
2,464
|
{
private <T> T resolveKnownSingleDependency( Class<T> type )
{
if ( type.equals( Database.class ) )
{
//noinspection unchecked
return (T) database;
}
else if ( type.equals( PreFlightTasks.class ) )
{
//noinspection unchecked
return (T) preflight;
}
else if ( type.equals( InterruptThreadTimer.class ) )
{
//noinspection unchecked
return (T) interruptStartupTimer;
}
// TODO: Note that several component dependencies are inverted here. For instance, logging
// should be provided by the server to the kernel, not the other way around. Same goes for job
// scheduling and configuration. Probably several others as well.
DependencyResolver kernelDependencyResolver = database.getGraph().getDependencyResolver();
return kernelDependencyResolver.resolveDependency( type );
}
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
{
return selector.select( type, option( resolveKnownSingleDependency( type ) ) );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_AbstractNeoServer.java
|
2,465
|
{
@Override
T parse( String value )
{
return Enum.valueOf( enumType, value );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,466
|
{
@Override
T adapt( T value )
{
for ( Predicate<? super T> predicate : predicates )
{
if ( !predicate.matches( value ) )
{
throw new IllegalArgumentException(
String.format( "'%s' does not match %s", value, predicate ) );
}
}
return value;
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,467
|
public class EnterpriseNeoServer extends AdvancedNeoServer
{
public EnterpriseNeoServer( Configurator configurator, Logging logging )
{
super( logging );
this.configurator = configurator;
init();
}
@Override
protected PreFlightTasks createPreflightTasks()
{
return new PreFlightTasks(
logging,
// TODO: This check should be done in the bootrapper,
// and verification of config should be done by the new
// config system.
//new EnsureEnterpriseNeo4jPropertiesExist(configurator.configuration()),
new EnsurePreparedForHttpLogging(configurator.configuration()),
new PerformUpgradeIfNecessary(getConfiguration(),
configurator.getDatabaseTuningProperties(), System.out, logging ),
new PerformRecoveryIfNecessary(getConfiguration(),
configurator.getDatabaseTuningProperties(), System.out, logging ));
}
@Override
protected Database createDatabase()
{
return new EnterpriseDatabase( configurator, logging );
}
@SuppressWarnings( "unchecked" )
@Override
protected Iterable<ServerModule> createServerModules()
{
return mix( asList(
(ServerModule) new MasterInfoServerModule( webServer, getConfiguration(), logging ) ),
super.createServerModules() );
}
@Override
protected InterruptThreadTimer createInterruptStartupTimer()
{
// If we are in HA mode, database startup can take a very long time, so
// we default to disabling the startup timeout here, unless explicitly overridden
// by configuration.
if(getConfiguration().getString( Configurator.DB_MODE_KEY, "single" ).equalsIgnoreCase("ha"))
{
long startupTimeout = getConfiguration().getInt(Configurator.STARTUP_TIMEOUT, 0) * 1000;
InterruptThreadTimer stopStartupTimer;
if(startupTimeout > 0)
{
stopStartupTimer = InterruptThreadTimer.createTimer(
startupTimeout,
Thread.currentThread());
} else
{
stopStartupTimer = InterruptThreadTimer.createNoOpTimer();
}
return stopStartupTimer;
} else
{
return super.createInterruptStartupTimer();
}
}
@Override
public Iterable<AdvertisableService> getServices()
{
if ( getDatabase().getGraph() instanceof HighlyAvailableGraphDatabase )
{
return Iterables.append( new MasterInfoService( null, null ), super.getServices() );
}
else
{
return super.getServices();
}
}
}
| false
|
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnterpriseNeoServer.java
|
2,468
|
SINGLE_STRING
{
@Override
Object generate()
{
return name();
}
},
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertyGenerator.java
|
2,469
|
{
@Override
public boolean matchesSafely( Map<String, Object> item )
{
return item.size() == size;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Map<String,Object> with size() == " ).appendValue( size );
}
};
| false
|
enterprise_enterprise-performance-tests_src_test_java_org_neo4j_perftest_enterprise_generator_DataGeneratorTest.java
|
2,470
|
{
@Override
public boolean matchesSafely( RelationshipType item )
{
return name.equals( item.name() );
}
@Override
public void describeTo( Description description )
{
description.appendText( "RelationshipType with name() == " ).appendValue( name );
}
};
| false
|
enterprise_enterprise-performance-tests_src_test_java_org_neo4j_perftest_enterprise_generator_DataGeneratorTest.java
|
2,471
|
public class DataGeneratorTest
{
@Test
public void shouldGenerateNodesAndRelationshipsWithProperties() throws Exception
{
// given
Configuration.Builder config = Configuration.builder();
config.setValue( DataGenerator.node_count, 5 );
config.setValue( DataGenerator.relationships, asList( new RelationshipSpec( "FOO", 1 ),
new RelationshipSpec( "BAR", 2 ) ) );
config.setValue( DataGenerator.node_properties,
asList( new PropertySpec( PropertyGenerator.STRING, 2 ) ) );
config.setValue( DataGenerator.relationship_properties,
asList( new PropertySpec( PropertyGenerator.STRING, 1 ) ) );
DataGenerator generator = new DataGenerator( config.build() );
BatchInserter batchInserter = mock( BatchInserter.class );
// when
generator.generateData( batchInserter );
// then
verify( batchInserter, times( 5 ) ).createNode( argThat( hasSize( 2 ) ) );
verify( batchInserter, times( 5 ) ).createRelationship( anyLong(), anyLong(), argThat( hasName( "FOO" ) ),
argThat( hasSize( 1 ) ) );
verify( batchInserter, times( 10 ) )
.createRelationship( anyLong(), anyLong(), argThat( hasName( "BAR" ) ), argThat( hasSize( 1 ) ) );
verifyNoMoreInteractions( batchInserter );
}
private static Matcher<RelationshipType> hasName( final String name )
{
return new TypeSafeMatcher<RelationshipType>()
{
@Override
public boolean matchesSafely( RelationshipType item )
{
return name.equals( item.name() );
}
@Override
public void describeTo( Description description )
{
description.appendText( "RelationshipType with name() == " ).appendValue( name );
}
};
}
private static Matcher<Map<String, Object>> hasSize( final int size )
{
return new TypeSafeMatcher<Map<String, Object>>()
{
@Override
public boolean matchesSafely( Map<String, Object> item )
{
return item.size() == size;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Map<String,Object> with size() == " ).appendValue( size );
}
};
}
}
| false
|
enterprise_enterprise-performance-tests_src_test_java_org_neo4j_perftest_enterprise_generator_DataGeneratorTest.java
|
2,472
|
public class DataGenerator
{
public static final Setting<String> store_dir = stringSetting( "neo4j.store_dir", "target/generated-data/graph.db" );
public static final Setting<Boolean> report_progress = booleanSetting( "report_progress", false );
static final Setting<Boolean> report_stats = booleanSetting( "report_stats", false );
static final Setting<Integer> node_count = adaptSetting(
restrictSetting( integerSetting( "node_count", 100 ), integerRange( 0, Integer.MAX_VALUE ) ),
Conversion.TO_INTEGER );
static final Setting<List<RelationshipSpec>> relationships = listSetting(
adaptSetting( stringSetting( "relationships" ), RelationshipSpec.FROM_STRING ),
asList( new RelationshipSpec( "RELATED_TO", 2 ) ) );
static final Setting<List<PropertySpec>> node_properties = listSetting(
adaptSetting( Setting.stringSetting( "node_properties" ), PropertySpec.PARSER ),
asList( new PropertySpec( PropertyGenerator.STRING, 1 ),
new PropertySpec( PropertyGenerator.BYTE_ARRAY, 1 ) ) );
static final Setting<List<PropertySpec>> relationship_properties = listSetting(
adaptSetting( Setting.stringSetting( "relationship_properties" ), PropertySpec.PARSER ),
Collections.<PropertySpec>emptyList() );
private static final Setting<String> all_stores_total_mapped_memory_size =
stringSetting( "all_stores_total_mapped_memory_size", "2G" );
public static final Random RANDOM = new Random();
private final boolean reportProgress;
private final int nodeCount;
private final int relationshipCount;
private final List<RelationshipSpec> relationshipsForEachNode;
private final List<PropertySpec> nodeProperties;
private final List<PropertySpec> relationshipProperties;
public static void main( String... args ) throws Exception
{
run( Parameters.configuration( SYSTEM_PROPERTIES, settingsOf( DataGenerator.class ) ).convert( args ) );
}
public DataGenerator( Configuration configuration )
{
this.reportProgress = configuration.get( report_progress );
this.nodeCount = configuration.get( node_count );
this.relationshipsForEachNode = configuration.get( relationships );
this.nodeProperties = configuration.get( node_properties );
this.relationshipProperties = configuration.get( relationship_properties );
int relCount = 0;
for ( RelationshipSpec rel : relationshipsForEachNode )
{
relCount += rel.count;
}
this.relationshipCount = nodeCount * relCount;
}
public static void run( Configuration configuration ) throws IOException
{
String storeDir = configuration.get( store_dir );
FileUtils.deleteRecursively( new File( storeDir ) );
DataGenerator generator = new DataGenerator( configuration );
BatchInserter batchInserter = BatchInserters.inserter( storeDir, batchInserterConfig( configuration ) );
try
{
generator.generateData( batchInserter );
}
finally
{
batchInserter.shutdown();
}
StoreAccess stores = new StoreAccess( storeDir );
try
{
printCount( stores.getNodeStore() );
printCount( stores.getRelationshipStore() );
printCount( stores.getPropertyStore() );
printCount( stores.getStringStore() );
printCount( stores.getArrayStore() );
if ( configuration.get( report_stats ) )
{
PropertyStats stats = new PropertyStats();
stats.applyFiltered( stores.getPropertyStore(), RecordStore.IN_USE );
System.out.println( stats );
}
}
finally
{
stores.close();
}
}
public void generateData( BatchInserter batchInserter )
{
ProgressMonitorFactory.MultiPartBuilder builder = initProgress();
ProgressListener nodeProgressListener = builder.progressForPart( "nodes", nodeCount );
ProgressListener relationshipsProgressListener = builder.progressForPart( "relationships", relationshipCount );
builder.build();
generateNodes( batchInserter, nodeProgressListener );
generateRelationships( batchInserter, relationshipsProgressListener );
}
@Override
public String toString()
{
return "DataGenerator{" +
"nodeCount=" + nodeCount +
", relationshipCount=" + relationshipCount +
", relationshipsForEachNode=" + relationshipsForEachNode +
", nodeProperties=" + nodeProperties +
", relationshipProperties=" + relationshipProperties +
'}';
}
private void generateNodes( BatchInserter batchInserter, ProgressListener progressListener )
{
for ( int i = 0; i < nodeCount; i++ )
{
batchInserter.createNode( generate( nodeProperties ) );
progressListener.set( i );
}
progressListener.done();
}
private void generateRelationships( BatchInserter batchInserter, ProgressListener progressListener )
{
for ( int i = 0; i < nodeCount; i++ )
{
for ( RelationshipSpec relationshipSpec : relationshipsForEachNode )
{
for ( int j = 0; j < relationshipSpec.count; j++ )
{
batchInserter.createRelationship( i, RANDOM.nextInt( nodeCount ), relationshipSpec,
generate( relationshipProperties ) );
progressListener.add( 1 );
}
}
}
progressListener.done();
}
protected ProgressMonitorFactory.MultiPartBuilder initProgress()
{
return (reportProgress ? ProgressMonitorFactory.textual( System.out ) : ProgressMonitorFactory.NONE)
.multipleParts( "Generating " + this );
}
private Map<String, Object> generate( List<PropertySpec> properties )
{
Map<String, Object> result = new HashMap<String, Object>();
for ( PropertySpec property : properties )
{
result.putAll( property.generate() );
}
return result;
}
private static void printCount( RecordStore<?> store )
{
File name = store.getStorageFileName();
System.out.format( "Number of records in %s: %d%n", name.getName(), store.getHighId() );
}
private static Map<String, String> batchInserterConfig( Configuration configuration )
{
Map<String, String> config = new HashMap<String, String>();
config.put( "use_memory_mapped_buffers", "true" );
config.put( "dump_configuration", "true" );
config.put( GraphDatabaseSettings.all_stores_total_mapped_memory_size.name(),
configuration.get( all_stores_total_mapped_memory_size ) );
addLegacyMemoryMappingConfiguration( config, configuration.get(
all_stores_total_mapped_memory_size ) );
return config;
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_DataGenerator.java
|
2,473
|
public final class IndexMap implements Cloneable
{
private final Map<Long, IndexProxy> indexesById;
private final Map<IndexDescriptor, IndexProxy> indexesByDescriptor;
public IndexMap()
{
this( new HashMap<Long, IndexProxy>(), new HashMap<IndexDescriptor, IndexProxy>() );
}
private IndexMap( Map<Long, IndexProxy> indexesById, Map<IndexDescriptor, IndexProxy> indexesByDescriptor )
{
this.indexesById = indexesById;
this.indexesByDescriptor = indexesByDescriptor;
}
public IndexProxy getIndexProxy( long indexId )
{
return indexesById.get( indexId );
}
public IndexProxy getIndexProxy( IndexDescriptor descriptor )
{
return indexesByDescriptor.get( descriptor );
}
public void putIndexProxy( long indexId, IndexProxy indexProxy )
{
indexesById.put( indexId, indexProxy );
indexesByDescriptor.put( indexProxy.getDescriptor(), indexProxy );
}
public IndexProxy removeIndexProxy( long indexId )
{
IndexProxy removedProxy = indexesById.remove( indexId );
if ( null != removedProxy )
{
indexesByDescriptor.remove( removedProxy.getDescriptor() );
}
return removedProxy;
}
public void foreachIndexProxy( BiConsumer<Long, IndexProxy> consumer )
{
for ( Map.Entry<Long, IndexProxy> entry : indexesById.entrySet() )
{
consumer.accept( entry.getKey(), entry.getValue() );
}
}
public Iterable<IndexProxy> getAllIndexProxies()
{
return indexesById.values();
}
@Override
public IndexMap clone()
{
return new IndexMap( cloneMap( indexesById ), cloneMap( indexesByDescriptor ) );
}
private <K, V> Map<K, V> cloneMap( Map<K, V> map )
{
Map<K, V> shallowCopy = new HashMap<>( map.size() );
shallowCopy.putAll( map );
return shallowCopy;
}
public Iterator<IndexDescriptor> descriptors()
{
return indexesByDescriptor.keySet().iterator();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_IndexMap.java
|
2,474
|
private class ProgressIndicator extends Indicator.Decorator
{
private final Timer total;
private Map<String, Timer> timers;
ProgressIndicator( String process )
{
super( TimingProgress.this.actual, process );
total = new Timer( null );
timers = new HashMap<String, Timer>();
}
ProgressIndicator( String process, int resolution )
{
super( TimingProgress.this.actual, process, resolution );
total = new Timer( null );
timers = new HashMap<String, Timer>();
}
@Override
public void startProcess( long totalCount )
{
super.startProcess( totalCount );
total.items = totalCount;
total.start();
}
@Override
public void startPart( String part, long totalCount )
{
super.startPart( part, totalCount );
Timer timer = new Timer( part );
timers.put( part, timer );
timer.items = totalCount;
timer.start();
}
@Override
public void completePart( String part )
{
timers.get( part ).stop();
super.completePart( part );
}
@Override
public void completeProcess()
{
total.stop();
super.completeProcess();
this.accept(visitor);
}
private void accept( Visitor visitor )
{
try
{
visitor.beginTimingProgress( total.items, total.time );
for ( Timer timer : timers.values() )
{
timer.accept( visitor );
}
visitor.endTimingProgress();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_TimingProgress.java
|
2,475
|
public class TimingProgress extends ProgressMonitorFactory
{
public interface Visitor
{
void beginTimingProgress( long totalElementCount, long totalTimeNanos ) throws IOException;
void phaseTimingProgress( String phase, long elementCount, long timeNanos ) throws IOException;
void endTimingProgress() throws IOException;
}
private final Visitor visitor;
private final ProgressMonitorFactory actual;
TimingProgress( Visitor visitor, ProgressMonitorFactory actual )
{
this.visitor = visitor;
this.actual = actual;
}
@Override
protected Indicator newIndicator( String process )
{
return new ProgressIndicator( process );
}
@Override
protected Indicator.OpenEnded newOpenEndedIndicator( String process, int resolution )
{
return new ProgressIndicator( process, resolution );
}
private static class Timer
{
private final String name;
private long time = 0;
private Long start = null;
private long items = 0;
Timer( String name )
{
this.name = name;
}
void start()
{
if ( start == null )
{
start = System.nanoTime();
}
}
void stop()
{
if ( start != null )
{
time += System.nanoTime() - start;
}
start = null;
}
void accept( Visitor visitor ) throws IOException
{
visitor.phaseTimingProgress( name, items, time );
}
}
private class ProgressIndicator extends Indicator.Decorator
{
private final Timer total;
private Map<String, Timer> timers;
ProgressIndicator( String process )
{
super( TimingProgress.this.actual, process );
total = new Timer( null );
timers = new HashMap<String, Timer>();
}
ProgressIndicator( String process, int resolution )
{
super( TimingProgress.this.actual, process, resolution );
total = new Timer( null );
timers = new HashMap<String, Timer>();
}
@Override
public void startProcess( long totalCount )
{
super.startProcess( totalCount );
total.items = totalCount;
total.start();
}
@Override
public void startPart( String part, long totalCount )
{
super.startPart( part, totalCount );
Timer timer = new Timer( part );
timers.put( part, timer );
timer.items = totalCount;
timer.start();
}
@Override
public void completePart( String part )
{
timers.get( part ).stop();
super.completePart( part );
}
@Override
public void completeProcess()
{
total.stop();
super.completeProcess();
this.accept(visitor);
}
private void accept( Visitor visitor )
{
try
{
visitor.beginTimingProgress( total.items, total.time );
for ( Timer timer : timers.values() )
{
timer.accept( visitor );
}
visitor.endTimingProgress();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_TimingProgress.java
|
2,476
|
class TimeLogger implements TimingProgress.Visitor
{
private final TimingProgress.Visitor next;
public TimeLogger( TimingProgress.Visitor next )
{
this.next = next;
}
static double nanosToMillis( long nanoTime )
{
return nanoTime / 1000000.0;
}
@Override
public void beginTimingProgress( long totalElementCount, long totalTimeNanos ) throws IOException
{
System.out.printf( "Processed %d elements in %.3f ms%n",
totalElementCount, nanosToMillis( totalTimeNanos ) );
next.beginTimingProgress( totalElementCount, totalTimeNanos );
}
@Override
public void phaseTimingProgress( String phase, long elementCount, long timeNanos ) throws IOException
{
next.phaseTimingProgress( phase, elementCount, timeNanos );
}
@Override
public void endTimingProgress() throws IOException
{
next.endTimingProgress();
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_TimeLogger.java
|
2,477
|
class JsonReportWriter implements TimingProgress.Visitor
{
private final File target;
private JsonGenerator json;
private boolean writeRecordsPerSecond = true;
private final Configuration configuration;
private final Config tuningConfiguration;
JsonReportWriter( Configuration configuration, Config tuningConfiguration )
{
this.configuration = configuration;
this.tuningConfiguration = tuningConfiguration;
target = new File( configuration.get( ConsistencyPerformanceCheck.report_file ) );
}
@Override
public void beginTimingProgress( long totalElementCount, long totalTimeNanos ) throws IOException
{
ensureOpen( false );
json = new JsonFactory().configure( JsonGenerator.Feature.AUTO_CLOSE_TARGET, true )
.createJsonGenerator( newFilePrintWriter( target, UTF_8 ) );
json.setPrettyPrinter( new DefaultPrettyPrinter() );
json.writeStartObject();
{
json.writeFieldName( "config" );
json.writeStartObject();
emitConfiguration();
json.writeEndObject();
}
{
json.writeFieldName( "tuningConfig" );
json.writeStartObject();
emitTuningConfiguration();
json.writeEndObject();
}
{
json.writeFieldName( "total" );
json.writeStartObject();
emitTime( totalElementCount, totalTimeNanos );
json.writeEndObject();
}
json.writeFieldName( "phases" );
json.writeStartArray();
}
private void emitConfiguration() throws IOException
{
for ( Setting<?> setting : settingsOf( DataGenerator.class, ConsistencyPerformanceCheck.class ) )
{
emitSetting( setting );
}
}
private <T> void emitSetting( Setting<T> setting ) throws IOException
{
json.writeStringField( setting.name(), setting.asString( configuration.get( setting ) ) );
}
private void emitTuningConfiguration() throws IOException
{
Map<String,String> params = new TreeMap<String,String>(tuningConfiguration.getParams());
for ( String key : params.keySet() )
{
json.writeStringField( key, params.get( key ) );
}
}
@Override
public void phaseTimingProgress( String phase, long elementCount, long timeNanos ) throws IOException
{
ensureOpen( true );
json.writeStartObject();
json.writeStringField( "name", phase );
emitTime( elementCount, timeNanos );
json.writeEndObject();
}
private void emitTime( long elementCount, long timeNanos ) throws IOException
{
json.writeNumberField( "elementCount", elementCount );
double millis = TimeLogger.nanosToMillis( timeNanos );
json.writeNumberField( "time", millis );
if ( writeRecordsPerSecond )
{
json.writeNumberField( "recordsPerSecond", (elementCount * 1000.0) / millis );
}
}
@Override
public void endTimingProgress() throws IOException
{
ensureOpen( true );
json.writeEndArray();
json.writeEndObject();
json.close();
}
private void ensureOpen( boolean open ) throws IOException
{
if ( (json == null) == open )
{
throw new IOException(
new IllegalStateException( String.format( "Writing %s started.", open ? "not" : "already" ) ) );
}
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_JsonReportWriter.java
|
2,478
|
public class ConsistencyPerformanceCheck
{
static final Setting<Boolean> generate_graph = booleanSetting( "generate_graph", false );
static final Setting<String> report_file = stringSetting( "report_file", "target/report.json" );
static final Setting<CheckerVersion> checker_version = enumSetting( "checker_version", CheckerVersion.NEW );
static final Setting<WindowPoolImplementation> window_pool_implementation =
enumSetting( "window_pool_implementation", WindowPoolImplementation.SCAN_RESISTANT );
static final Setting<TaskExecutionOrder> execution_order =
enumSetting( "execution_order", TaskExecutionOrder.SINGLE_THREADED );
static final Setting<Boolean> wait_before_check = booleanSetting( "wait_before_check", false );
static final Setting<String> all_stores_total_mapped_memory_size =
stringSetting( "all_stores_total_mapped_memory_size", "2G" );
static final Setting<String> mapped_memory_page_size = stringSetting( "mapped_memory_page_size", "4k" );
static final Setting<Boolean> log_mapped_memory_stats =
booleanSetting( "log_mapped_memory_stats", true );
static final Setting<String> log_mapped_memory_stats_filename =
stringSetting( "log_mapped_memory_stats_filename", "mapped_memory_stats.log" );
static final Setting<Long> log_mapped_memory_stats_interval =
integerSetting( "log_mapped_memory_stats_interval", 1000000 );
/**
* Sample execution:
* java -cp ... org.neo4j.perftest.enterprise.ccheck.ConsistencyPerformanceCheck
* -generate_graph
* -report_file target/ccheck_performance.json
* -neo4j.store_dir target/ccheck_perf_graph
* -report_progress
* -node_count 10000000
* -relationships FOO:2,BAR:1
* -node_properties INTEGER:2,STRING:1,BYTE_ARRAY:1
*/
public static void main( String... args ) throws Exception
{
run( Parameters.configuration( SYSTEM_PROPERTIES,
settingsOf( DataGenerator.class, ConsistencyPerformanceCheck.class ) )
.convert( args ) );
}
private static void run( Configuration configuration ) throws Exception
{
if ( configuration.get( generate_graph ) )
{
DataGenerator.run( configuration );
}
// ensure that the store is recovered
new GraphDatabaseFactory().newEmbeddedDatabase( configuration.get( DataGenerator.store_dir ) ).shutdown();
// run the consistency check
ProgressMonitorFactory progress;
if ( configuration.get( DataGenerator.report_progress ) )
{
progress = ProgressMonitorFactory.textual( System.out );
}
else
{
progress = ProgressMonitorFactory.NONE;
}
if ( configuration.get( wait_before_check ) )
{
System.out.println( "Press return to start the checker..." );
System.in.read();
}
Config tuningConfiguration = buildTuningConfiguration( configuration );
DirectStoreAccess directStoreAccess = createScannableStores( configuration.get( DataGenerator.store_dir ),
tuningConfiguration );
JsonReportWriter reportWriter = new JsonReportWriter( configuration, tuningConfiguration );
TimingProgress progressMonitor = new TimingProgress( new TimeLogger( reportWriter ), progress );
configuration.get( checker_version ).run( progressMonitor, directStoreAccess, tuningConfiguration );
}
private static DirectStoreAccess createScannableStores( String storeDir, Config tuningConfiguration )
{
StringLogger logger = StringLogger.DEV_NULL;
FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
StoreFactory factory = new StoreFactory(
tuningConfiguration,
new DefaultIdGeneratorFactory(),
tuningConfiguration.get( ConsistencyCheckSettings.consistency_check_window_pool_implementation )
.windowPoolFactory( tuningConfiguration, logger ),
fileSystem, logger, new DefaultTxHook() );
NeoStore neoStore = factory.newNeoStore( new File( storeDir, NeoStore.DEFAULT_NAME ) );
SchemaIndexProvider indexes = new LuceneSchemaIndexProvider( DirectoryFactory.PERSISTENT, tuningConfiguration );
return new DirectStoreAccess( new StoreAccess( neoStore ),
new LuceneLabelScanStoreBuilder( storeDir, neoStore, fileSystem, logger ).build(), indexes );
}
private static Config buildTuningConfiguration( Configuration configuration )
{
Map<String, String> passedOnConfiguration = passOn( configuration,
param( GraphDatabaseSettings.store_dir, DataGenerator.store_dir ),
param( GraphDatabaseSettings.all_stores_total_mapped_memory_size, all_stores_total_mapped_memory_size ),
param( ConsistencyCheckSettings.consistency_check_execution_order, execution_order ),
param( ConsistencyCheckSettings.consistency_check_window_pool_implementation,
window_pool_implementation ),
param( GraphDatabaseSettings.mapped_memory_page_size, mapped_memory_page_size ),
param( GraphDatabaseSettings.log_mapped_memory_stats, log_mapped_memory_stats ),
param( GraphDatabaseSettings.log_mapped_memory_stats_filename, log_mapped_memory_stats_filename ),
param( GraphDatabaseSettings.log_mapped_memory_stats_interval, log_mapped_memory_stats_interval ) );
addLegacyMemoryMappingConfiguration( passedOnConfiguration,
configuration.get( all_stores_total_mapped_memory_size ) );
return new Config( passedOnConfiguration, GraphDatabaseSettings.class );
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_ConsistencyPerformanceCheck.java
|
2,479
|
NEW
{
@Override
void run( ProgressMonitorFactory progress, DirectStoreAccess directStoreAccess, Config tuningConfiguration ) throws ConsistencyCheckIncompleteException
{
new FullCheck( tuningConfiguration, progress ).execute( directStoreAccess, StringLogger.DEV_NULL );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_CheckerVersion.java
|
2,480
|
public class MetricsLogExtensionFactory
extends KernelExtensionFactory<MetricsLogExtensionFactory.Dependencies>
{
public interface Dependencies
{
Monitors monitors();
Config config();
FileSystemAbstraction fileSystem();
TxManager txManager();
}
public MetricsLogExtensionFactory( )
{
super( "metricslog");
}
@Override
public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable
{
return new MetricsLogExtension(dependencies.monitors(), dependencies.config(), dependencies.fileSystem(), dependencies.txManager());
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_metrics_MetricsLogExtensionFactory.java
|
2,481
|
{
@Override
public void run()
{
try
{
csv.print( System.currentTimeMillis(),
diskCounterMetrics.getBytesWritten(), diskCounterMetrics.getBytesRead(),
networkCounterMetrics.getBytesWritten(), networkCounterMetrics.getBytesRead(),
txManager.getCommittedTxCount());
System.out.println( config.get( ClusterSettings.server_id ) + " bytes written:" + networkCounterMetrics
.getBytesWritten() );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}, 1, 1, TimeUnit.SECONDS );
| false
|
enterprise_ha_src_test_java_org_neo4j_metrics_MetricsLogExtension.java
|
2,482
|
public class MetricsLogExtension implements Lifecycle
{
private Monitors monitors;
private Config config;
private FileSystemAbstraction fileSystemAbstraction;
private TxManager txManager;
private ByteCounterMetrics networkCounterMetrics;
private ByteCounterMetrics diskCounterMetrics;
private ScheduledExecutorService executor;
private CSVFile csv;
public MetricsLogExtension( Monitors monitors, Config config, FileSystemAbstraction fileSystemAbstraction, TxManager txManager )
{
this.monitors = monitors;
this.config = config;
this.fileSystemAbstraction = fileSystemAbstraction;
this.txManager = txManager;
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
networkCounterMetrics = new ByteCounterMetrics();
monitors.addMonitorListener( networkCounterMetrics, MasterServer.class.getName() );
monitors.addMonitorListener( networkCounterMetrics, "logdeserializer" );
diskCounterMetrics = new ByteCounterMetrics();
monitors.addMonitorListener( diskCounterMetrics, XaLogicalLog.class.getName() );
File path = new File( config.get( GraphDatabaseSettings.store_dir ), "metrics.txt" );
System.out.println("CSV:"+path);
OutputStream file = fileSystemAbstraction.openAsOutputStream( path, false );
csv = new CSVFile( file, Iterables.<String, String>iterable( "timestamp", "diskWritten", "diskRead", "networkWritten", "networkRead", "committedTx" ) );
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
try
{
csv.print( System.currentTimeMillis(),
diskCounterMetrics.getBytesWritten(), diskCounterMetrics.getBytesRead(),
networkCounterMetrics.getBytesWritten(), networkCounterMetrics.getBytesRead(),
txManager.getCommittedTxCount());
System.out.println( config.get( ClusterSettings.server_id ) + " bytes written:" + networkCounterMetrics
.getBytesWritten() );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}, 1, 1, TimeUnit.SECONDS );
}
@Override
public void stop() throws Throwable
{
executor.shutdown();
if (!executor.awaitTermination( 10, TimeUnit.SECONDS ))
executor.shutdownNow();
csv.close();
monitors.removeMonitorListener( networkCounterMetrics );
}
@Override
public void shutdown() throws Throwable
{
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_metrics_MetricsLogExtension.java
|
2,483
|
public class CSVFile
implements Closeable
{
private final OutputStream out;
public CSVFile(OutputStream outStream, Iterable<String> columns)
throws IOException
{
this.out = outStream;
// Print header
StringBuilder builder = new StringBuilder( );
String separator = "";
for ( String column : columns )
{
builder.append( separator );
builder.append( column );
separator = "\t";
}
builder.append( '\n' );
out.write( builder.toString().getBytes( Charset.forName( "UTF-8" ) ) );
}
public void print(Number... values) throws IOException
{
StringBuilder builder = new StringBuilder( );
String separator = "";
for ( Number value : values )
{
builder.append( separator );
builder.append( value.longValue() );
separator = "\t";
}
builder.append( '\n' );
out.write( builder.toString().getBytes( Charset.forName( "UTF-8" ) ) );
}
@Override
public void close() throws IOException
{
out.close();
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_metrics_CSVFile.java
|
2,484
|
public class ByteCounterMetrics
implements ByteCounterMonitor
{
private long bytesWritten;
private long bytesRead;
@Override
public void bytesWritten( long numberOfBytes )
{
bytesWritten++;
}
@Override
public void bytesRead( long numberOfBytes )
{
bytesRead++;
}
public long getBytesWritten()
{
return bytesWritten;
}
public long getBytesRead()
{
return bytesRead;
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_metrics_ByteCounterMetrics.java
|
2,485
|
public class TestJavaTestDocsGenerator implements GraphHolder
{
private static GraphDatabaseService graphdb;
public @Rule
TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor(
this, true ) );
public @Rule
TestData<JavaTestDocsGenerator> gen = TestData.producedThrough( JavaTestDocsGenerator.PRODUCER );
File directory = TargetDirectory.forTest(getClass()).cleanDirectory( "testdocs" );
String sectionName = "testsection";
File sectionDirectory = new File(directory, sectionName);
@Documented( value = "Title1.\n\nhej\n@@snippet1\n\nmore docs\n@@snippet_2-1\n@@snippet12\n." )
@Test
@Graph( "I know you" )
public void can_create_docs_from_method_name() throws Exception
{
data.get();
JavaTestDocsGenerator doc = gen.get();
doc.setGraph( graphdb );
assertNotNull( data.get().get( "I" ) );
String snippet1 = "snippet1-value";
String snippet12 = "snippet12-value";
String snippet2 = "snippet2-value";
doc.addSnippet( "snippet1", snippet1 );
doc.addSnippet( "snippet12", snippet12 );
doc.addSnippet( "snippet_2-1", snippet2 );
doc.document( directory.getAbsolutePath(), sectionName );
String result = readFileAsString( new File( sectionDirectory,
"title1.asciidoc" ) );
assertTrue( result.contains( "include::includes/title1-snippet1.asciidoc[]" ) );
assertTrue( result.contains( "include::includes/title1-snippet_2-1.asciidoc[]" ) );
assertTrue( result.contains( "include::includes/title1-snippet12.asciidoc[]" ) );
File includes = new File( sectionDirectory, "includes" );
result = readFileAsString( new File( includes,
"title1-snippet1.asciidoc" ) );
assertTrue( result.contains( snippet1 ) );
result = readFileAsString( new File( includes,
"title1-snippet_2-1.asciidoc" ) );
assertTrue( result.contains( snippet2 ) );
result = readFileAsString( new File( includes,
"title1-snippet12.asciidoc" ) );
assertTrue( result.contains( snippet12 ) );
}
@Documented( value = "@@snippet1\n" )
@Test
@Graph( "I know you" )
public void will_not_complain_about_missing_snippets() throws Exception
{
data.get();
JavaTestDocsGenerator doc = gen.get();
doc.document( directory.getAbsolutePath(), sectionName );
}
/**
* Title2.
*
* @@snippet1
*
* more stuff
*
*
* @@snippet2
*/
@Documented
@Test
@Graph( "I know you" )
public void canCreateDocsFromSnippetsInAnnotations() throws Exception
{
data.get();
JavaTestDocsGenerator doc = gen.get();
doc.setGraph( graphdb );
assertNotNull( data.get().get( "I" ) );
String snippet1 = "snippet1-value";
String snippet2 = "snippet2-value";
doc.addSnippet( "snippet1", snippet1 );
doc.addSnippet( "snippet2", snippet2 );
doc.document( directory.getAbsolutePath(), sectionName );
String result = readFileAsString( new File( sectionDirectory,
"title2.asciidoc" ) );
assertTrue( result.contains( "include::includes/title2-snippet1.asciidoc[]" ) );
assertTrue( result.contains( "include::includes/title2-snippet2.asciidoc[]" ) );
result = readFileAsString( new File( new File( sectionDirectory,
"includes" ), "title2-snippet1.asciidoc" ) );
assertTrue( result.contains( snippet1 ) );
result = readFileAsString( new File( new File( sectionDirectory,
"includes" ), "title2-snippet2.asciidoc" ) );
assertTrue( result.contains( snippet2 ) );
}
public static String readFileAsString( File file )
throws java.io.IOException
{
byte[] buffer = new byte[(int) file.length()];
BufferedInputStream f = new BufferedInputStream( new FileInputStream(
file ) );
f.read( buffer );
return new String( buffer );
}
@Override
public GraphDatabaseService graphdb()
{
return graphdb;
}
@BeforeClass
public static void setUp()
{
graphdb = new TestGraphDatabaseFactory().newImpermanentDatabase();
}
@AfterClass
public static void shutdown()
{
try
{
if ( graphdb != null ) graphdb.shutdown();
}
finally
{
graphdb = null;
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_metatest_TestJavaTestDocsGenerator.java
|
2,486
|
public class TestImpermanentGraphDatabase
{
private ImpermanentGraphDatabase db;
@Before
public void createDb()
{
db = new ImpermanentGraphDatabase();
}
@After
public void tearDown()
{
db.shutdown();
}
@Test
public void should_keep_data_between_start_and_shutdown()
{
createNode();
assertEquals( "Expected one new node", 1, nodeCount() );
}
@Test
public void data_should_not_survive_shutdown()
{
createNode();
db.shutdown();
createDb();
assertEquals( "Should not see anything.", 0, nodeCount() );
}
@Test
public void should_remove_all_data()
{
try ( Transaction tx = db.beginTx() )
{
DynamicRelationshipType relationshipType = DynamicRelationshipType.withName("R");
Node n1 = db.createNode();
Node n2 = db.createNode();
Node n3 = db.createNode();
n1.createRelationshipTo(n2, relationshipType);
n2.createRelationshipTo(n1, relationshipType);
n3.createRelationshipTo(n1, relationshipType);
tx.success();
}
cleanDatabaseContent( db );
assertThat( nodeCount(), is( 0 ) );
}
private int nodeCount()
{
Transaction transaction = db.beginTx();
int count = IteratorUtil.count( GlobalGraphOperations.at( db ).getAllNodes() );
transaction.close();
return count;
}
private void createNode()
{
try ( Transaction tx = db.beginTx() )
{
db.createNode();
tx.success();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_metatest_TestImpermanentGraphDatabase.java
|
2,487
|
public class TestGraphDescription implements GraphHolder
{
private static GraphDatabaseService graphdb;
public @Rule
TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor(
this, true ) );
@Test
public void havingNoGraphAnnotationCreatesAnEmptyDataCollection()
throws Exception
{
assertTrue( "collection was not empty", data.get().isEmpty() );
}
@Test
@Graph( "I know you" )
public void canCreateGraphFromSingleString() throws Exception
{
verifyIKnowYou( "know", "I" );
}
@Test
@Graph( { "a TO b", "b TO c", "c TO a" } )
public void canCreateGraphFromMultipleStrings() throws Exception
{
Map<String, Node> graph = data.get();
Set<Node> unique = new HashSet<Node>();
Node n = graph.get( "a" );
while ( unique.add( n ) )
{
try(Transaction ignored = graphdb.beginTx())
{
n = n.getSingleRelationship(
DynamicRelationshipType.withName( "TO" ),
Direction.OUTGOING ).getEndNode();
}
}
assertEquals( graph.size(), unique.size() );
}
@Test
@Graph( { "a:Person EATS b:Banana" } )
public void ensurePeopleCanEatBananas() throws Exception
{
Map<String, Node> graph = data.get();
Node a = graph.get( "a" );
Node b = graph.get( "b" );
try(Transaction ignored = graphdb.beginTx())
{
assertTrue( a.hasLabel( label( "Person" ) ) );
assertTrue( b.hasLabel( label( "Banana" ) ) );
}
}
@Test
@Graph( { "a:Person EATS b:Banana", "a EATS b:Apple" } )
public void ensurePeopleCanEatBananasAndApples() throws Exception
{
Map<String, Node> graph = data.get();
Node a = graph.get( "a" );
Node b = graph.get( "b" );
try(Transaction ignored = graphdb.beginTx())
{
assertTrue( "Person label missing", a.hasLabel( label( "Person" ) ) );
assertTrue( "Banana label missing", b.hasLabel( label( "Banana" ) ) );
assertTrue( "Apple label missing", b.hasLabel( label( "Apple" ) ) );
}
}
@Test
@Graph( value = { "I know you" }, autoIndexNodes=true )
public void canAutoIndexNodes() throws Exception
{
data.get();
try(Transaction ignored = graphdb.beginTx())
{
assertTrue(
"can't look up node.",
graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
"name", "I" ).hasNext() );
}
}
@Test
@Graph( nodes = { @NODE( name = "I", setNameProperty=true, properties = {
@PROP( key = "name", value = "I" )})}, autoIndexNodes=true )
public void canAutoIndexNodesExplicitProps() throws Exception
{
data.get();
try(Transaction ignored = graphdb.beginTx())
{
assertTrue(
"can't look up node.",
graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
"name", "I" ).hasNext() );
}
}
@Test
@Graph( nodes = {
@NODE( name = "I", properties = {
@PROP( key = "name", value = "me" ),
@PROP( key = "bool", value = "true", type = GraphDescription.PropType.BOOLEAN ) } ),
@NODE( name = "you", setNameProperty = true ) }, relationships = { @REL( start = "I", end = "you", type = "knows", properties = {
@PROP( key = "name", value = "relProp" ),
@PROP( key = "valid", value = "true", type = GraphDescription.PropType.BOOLEAN ) } ) }, autoIndexRelationships = true )
public void canCreateMoreInvolvedGraphWithPropertiesAndAutoIndex()
throws Exception
{
data.get();
verifyIKnowYou( "knows", "me" );
try(Transaction ignored = graphdb.beginTx())
{
assertEquals( true, data.get().get( "I" ).getProperty( "bool" ) );
assertFalse( "node autoindex enabled.",
graphdb().index().getNodeAutoIndexer().isEnabled() );
assertTrue(
"can't look up rel.",
graphdb().index().getRelationshipAutoIndexer().getAutoIndex().get(
"name", "relProp" ).hasNext() );
assertTrue( "relationship autoindex enabled.",
graphdb().index().getRelationshipAutoIndexer().isEnabled() );
}
}
@Graph( value = { "I know you" }, nodes = { @NODE( name = "I", properties = { @PROP( key = "name", value = "me" ) } ) } )
private void verifyIKnowYou( String type, String myName )
{
try(Transaction ignored = graphdb.beginTx())
{
Map<String, Node> graph = data.get();
assertEquals( "Wrong graph size.", 2, graph.size() );
Node I = graph.get( "I" );
assertNotNull( "The node 'I' was not defined", I );
Node you = graph.get( "you" );
assertNotNull( "The node 'you' was not defined", you );
assertEquals( "'I' has wrong 'name'.", myName, I.getProperty( "name" ) );
assertEquals( "'you' has wrong 'name'.", "you",
you.getProperty( "name" ) );
Iterator<Relationship> rels = I.getRelationships().iterator();
assertTrue( "'I' has too few relationships", rels.hasNext() );
Relationship rel = rels.next();
assertEquals( "'I' is not related to 'you'", you, rel.getOtherNode( I ) );
assertEquals( "Wrong relationship type.", type, rel.getType().name() );
assertFalse( "'I' has too many relationships", rels.hasNext() );
rels = you.getRelationships().iterator();
assertTrue( "'you' has too few relationships", rels.hasNext() );
rel = rels.next();
assertEquals( "'you' is not related to 'i'", I, rel.getOtherNode( you ) );
assertEquals( "Wrong relationship type.", type, rel.getType().name() );
assertFalse( "'you' has too many relationships", rels.hasNext() );
assertEquals( "wrong direction", I, rel.getStartNode() );
}
}
@BeforeClass
public static void startDatabase()
{
graphdb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
}
@AfterClass
public static void stopDatabase()
{
if ( graphdb != null ) graphdb.shutdown();
graphdb = null;
}
@Override
public GraphDatabaseService graphdb()
{
return graphdb;
}
}
| false
|
community_neo4j_src_test_java_org_neo4j_metatest_TestGraphDescription.java
|
2,488
|
INTEGER
{
@Override
Object generate()
{
return DataGenerator.RANDOM.nextInt( 16 );
}
},
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertyGenerator.java
|
2,489
|
STRING
{
@Override
Object generate()
{
int length = 50 + DataGenerator.RANDOM.nextInt( 70 );
StringBuilder result = new StringBuilder( length );
for ( int i = 0; i < length; i++ )
{
result.append( (char) ('a' + DataGenerator.RANDOM.nextInt( 'z' - 'a' )) );
}
return result.toString();
}
},
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertyGenerator.java
|
2,490
|
{
@Override
Boolean parse( String value )
{
return Boolean.parseBoolean( value );
}
@Override
boolean isBoolean()
{
return true;
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,491
|
BYTE_ARRAY
{
@Override
Object generate()
{
// int length = 4 + RANDOM.nextInt( 60 );
int length = 50;
int[] array = new int[length];
for ( int i = 0; i < length; i++ )
{
array[i] = DataGenerator.RANDOM.nextInt( 256 );
}
return array;
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertyGenerator.java
|
2,492
|
{
@Override
Long parse( String value )
{
return Long.parseLong( value );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,493
|
{
@Override
String parse( String value )
{
return value;
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,494
|
public abstract class Setting<T>
{
public static Setting<String> stringSetting( String name )
{
return stringSetting( name, null );
}
public static Setting<String> stringSetting( String name, String defaultValue )
{
return new Setting<String>( name, defaultValue )
{
@Override
String parse( String value )
{
return value;
}
};
}
public static Setting<Long> integerSetting( String name, long defaultValue )
{
return new Setting<Long>( name, defaultValue )
{
@Override
Long parse( String value )
{
return Long.parseLong( value );
}
};
}
public static Setting<Boolean> booleanSetting( String name, boolean defaultValue )
{
return new Setting<Boolean>( name, defaultValue )
{
@Override
Boolean parse( String value )
{
return Boolean.parseBoolean( value );
}
@Override
boolean isBoolean()
{
return true;
}
};
}
public static <T> Setting<T> restrictSetting( Setting<T> setting, Predicate<? super T> firstPredicate,
Predicate<? super T>... morePredicates )
{
final Collection<Predicate<? super T>> predicates;
if ( morePredicates == null || morePredicates.length == 0 )
{
predicates = new ArrayList<Predicate<? super T>>( 1 );
predicates.add( firstPredicate );
}
else
{
predicates = new ArrayList<Predicate<? super T>>( 1 + morePredicates.length );
predicates.add( firstPredicate );
addAll( predicates, morePredicates );
}
return new SettingAdapter<T, T>( setting )
{
@Override
T adapt( T value )
{
for ( Predicate<? super T> predicate : predicates )
{
if ( !predicate.matches( value ) )
{
throw new IllegalArgumentException(
String.format( "'%s' does not match %s", value, predicate ) );
}
}
return value;
}
};
}
public static <T extends Enum<T>> Setting<T> enumSetting( final Class<T> enumType, String name )
{
return new Setting<T>( name, null )
{
@Override
T parse( String value )
{
return Enum.valueOf( enumType, value );
}
};
}
public static <T extends Enum<T>> Setting<T> enumSetting( String name, T defaultValue )
{
final Class<T> enumType = defaultValue.getDeclaringClass();
return new Setting<T>( name, defaultValue )
{
@Override
T parse( String value )
{
return Enum.valueOf( enumType, value );
}
};
}
public static <T> Setting<List<T>> listSetting( final Setting<T> singleSetting, final List<T> defaultValue )
{
return new Setting<List<T>>( singleSetting.name(), defaultValue )
{
@Override
List<T> parse( String value )
{
if ( value.trim().equals( "" ) )
{
return emptyList();
}
String[] parts = value.split( "," );
List<T> result = new ArrayList<T>( parts.length );
for ( String part : parts )
{
result.add( singleSetting.parse( part ) );
}
return result;
}
@Override
public String asString( List<T> value )
{
StringBuilder result = new StringBuilder();
Iterator<T> iterator = value.iterator();
while ( iterator.hasNext() )
{
result.append( singleSetting.asString( iterator.next() ) );
if ( iterator.hasNext() )
{
result.append( ',' );
}
}
return result.toString();
}
};
}
public static <FROM, TO> Setting<TO> adaptSetting( Setting<FROM> source,
final Conversion<? super FROM, TO> conversion )
{
return new SettingAdapter<FROM, TO>( source )
{
@Override
TO adapt( FROM value )
{
return conversion.convert( value );
}
};
}
private final String name;
private final T defaultValue;
private Setting( String name, T defaultValue )
{
this.name = name;
this.defaultValue = defaultValue;
}
@Override
public String toString()
{
return String.format( "Setting[%s]", name );
}
public String name()
{
return name;
}
T defaultValue()
{
if ( defaultValue == null )
{
throw new IllegalStateException( String.format( "Required setting '%s' not configured.", name ) );
}
return defaultValue;
}
abstract T parse( String value );
boolean isBoolean()
{
return false;
}
void validateValue( String value )
{
parse( value );
}
public String asString( T value )
{
return value.toString();
}
private static abstract class SettingAdapter<FROM, TO> extends Setting<TO>
{
private final Setting<FROM> source;
SettingAdapter( Setting<FROM> source )
{
super( source.name, null );
this.source = source;
}
@Override
TO parse( String value )
{
return adapt( source.parse( value ) );
}
abstract TO adapt( FROM value );
@Override
TO defaultValue()
{
return adapt( source.defaultValue() );
}
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Setting.java
|
2,495
|
{
@Override
boolean matches( Long value )
{
return value <= maxValue && value >= minValue;
}
@Override
public String toString()
{
return String.format( "%s, %s", minValue == null ? "]-inf" : ("[" + minValue), maxValue == null ? "inf]" : (maxValue + "]") );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Predicate.java
|
2,496
|
public abstract class Predicate<T>
{
public static Predicate<Long> integerRange( final Long minValue, final Long maxValue )
{
return new Predicate<Long>()
{
@Override
boolean matches( Long value )
{
return value <= maxValue && value >= minValue;
}
@Override
public String toString()
{
return String.format( "%s, %s", minValue == null ? "]-inf" : ("[" + minValue), maxValue == null ? "inf]" : (maxValue + "]") );
}
};
}
public static Predicate<Long> integerRange( Integer minValue, Integer maxValue )
{
return integerRange( minValue == null ? null : minValue.longValue(),
maxValue == null ? null : maxValue.longValue() );
}
abstract boolean matches( T value );
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Predicate.java
|
2,497
|
{
@Override
public Configuration convert( String[] args )
{
Configuration.Builder configurationBuilder = Configuration.builder();
if ( parser.parse( configurationBuilder, args ).length != 0 )
{
throw new IllegalArgumentException( "Positional arguments not supported." );
}
return Configuration.combine( configurationBuilder.build(), defaultConfiguration );
}
};
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Parameters.java
|
2,498
|
public class Parameters
{
public static Conversion<String[], Configuration> configuration( final Configuration defaultConfiguration,
Setting<?>... settings )
{
final Parameters parser = parser( settings );
return new Conversion<String[], Configuration>()
{
@Override
public Configuration convert( String[] args )
{
Configuration.Builder configurationBuilder = Configuration.builder();
if ( parser.parse( configurationBuilder, args ).length != 0 )
{
throw new IllegalArgumentException( "Positional arguments not supported." );
}
return Configuration.combine( configurationBuilder.build(), defaultConfiguration );
}
};
}
public String[] parse( Configuration.Builder configurationBuilder, String... args )
{
for ( int i = 0; i < args.length; i++ )
{
if ( args[i].charAt( 0 ) == '-' )
{
String flag = args[i].substring( 1 );
Setting<?> setting = settings.get( flag );
if ( setting == null )
{
throw new IllegalArgumentException( String.format( "Unknown parameter '%s'", args[i] ) );
}
if ( setting.isBoolean() )
{
configurationBuilder.set( setting, "true" );
continue;
}
if ( ++i == args.length )
{
throw new IllegalArgumentException( String.format( "Missing value for parameter '%s", args[i] ) );
}
configurationBuilder.set( setting, args[i] );
}
else
{
return Arrays.copyOfRange( args, i, args.length );
}
}
return new String[0];
}
public static Parameters parser( Setting<?>... settings )
{
return new Parameters( settings );
}
private final Map<String, Setting<?>> settings = new HashMap<String, Setting<?>>();
private Parameters( Setting<?>[] settings )
{
for ( Setting<?> setting : settings )
{
this.settings.put( setting.name(), setting );
}
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Parameters.java
|
2,499
|
public class DirectlyCorrelatedParameter
{
public static Map<String, String> passOn( Configuration configuration, DirectlyCorrelatedParameter... parameters )
{
HashMap<String, String> map = new HashMap<String, String>();
for ( DirectlyCorrelatedParameter parameter : parameters )
{
Setting<?> localSetting = parameter.localSetting;
map.put( parameter.databaseSetting.name(), asString( configuration, localSetting ) );
}
return map;
}
public static DirectlyCorrelatedParameter param( org.neo4j.graphdb.config.Setting<?> databaseSetting,
Setting<?> localSetting )
{
return new DirectlyCorrelatedParameter( localSetting, databaseSetting );
}
private static <T> String asString( Configuration configuration, Setting<T> localSetting )
{
return localSetting.asString( configuration.get( localSetting ) );
}
private final Setting<?> localSetting;
private final org.neo4j.graphdb.config.Setting<?> databaseSetting;
DirectlyCorrelatedParameter( Setting<?> localSetting, org.neo4j.graphdb.config.Setting<?> databaseSetting )
{
this.localSetting = localSetting;
this.databaseSetting = databaseSetting;
}
}
| false
|
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_DirectlyCorrelatedParameter.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.