Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
2,500
{ @Override public Integer convert( Number source ) { return source.intValue(); } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Conversion.java
2,501
public static final class Builder { public Configuration build() { return fromMap( new HashMap<String, String>( config ) ); } private final Map<String, String> config; private Builder( HashMap<String, String> config ) { this.config = config; } public void set( Setting<?> setting, String value ) { setting.validateValue( value ); config.put( setting.name(), value ); } public <T> void setValue( Setting<T> setting, T value ) { set( setting, setting.asString( value ) ); } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Configuration.java
2,502
{ @Override protected String getConfiguration( String name ) { return config.get( name ); } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Configuration.java
2,503
{ @Override protected String getConfiguration( String name ) { for ( Configuration configuration : configurations ) { String value = configuration.getConfiguration( name ); if ( value != null ) { return value; } } return null; } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Configuration.java
2,504
{ @Override protected String getConfiguration( String name ) { return System.getProperty( name ); } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Configuration.java
2,505
public abstract class Configuration { public static final Configuration SYSTEM_PROPERTIES = new Configuration() { @Override protected String getConfiguration( String name ) { return System.getProperty( name ); } }; public static Configuration combine( Configuration first, Configuration other, Configuration... more ) { final Configuration[] configurations = new Configuration[2 + (more == null ? 0 : more.length)]; configurations[0] = first; configurations[1] = other; if ( more != null ) { System.arraycopy( more, 0, configurations, 2, more.length ); } return new Configuration() { @Override protected String getConfiguration( String name ) { for ( Configuration configuration : configurations ) { String value = configuration.getConfiguration( name ); if ( value != null ) { return value; } } return null; } }; } public static Setting<?>[] settingsOf( Class<?>... settingsHolders ) { List<Setting<?>> result = new ArrayList<Setting<?>>(); for ( Class<?> settingsHolder : settingsHolders ) { for ( Field field : settingsHolder.getDeclaredFields() ) { if ( isStatic( field.getModifiers() ) && field.getType() == Setting.class ) { field.setAccessible( true ); try { result.add( (Setting) field.get( settingsHolder ) ); } catch ( IllegalAccessException e ) { throw new IllegalStateException( "Field should have been made accessible", e ); } } } } return result.toArray( new Setting<?>[result.size()] ); } public static Configuration fromMap( final Map<String, String> config ) { return new Configuration() { @Override protected String getConfiguration( String name ) { return config.get( name ); } }; } public static final class Builder { public Configuration build() { return fromMap( new HashMap<String, String>( config ) ); } private final Map<String, String> config; private Builder( HashMap<String, String> config ) { this.config = config; } public void set( Setting<?> setting, String value ) { setting.validateValue( value ); config.put( setting.name(), value ); } public <T> void setValue( Setting<T> setting, T value ) { set( setting, setting.asString( value ) ); } } public <T> T get( Setting<T> setting ) { String value = getConfiguration( setting.name() ); if ( value == null ) { return setting.defaultValue(); } return setting.parse( value ); } protected abstract String getConfiguration( String name ); public static Builder builder() { return new Builder( new HashMap<String, String>() ); } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_util_Configuration.java
2,506
{ @Override public RelationshipSpec convert( String source ) { String[] parts = source.split( ":" ); if ( parts.length != 2 ) { throw new IllegalArgumentException( "value must have the format <relationship label>:<count>" ); } return new RelationshipSpec( parts[0], Integer.parseInt( parts[1] ) ); } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_RelationshipSpec.java
2,507
class RelationshipSpec implements RelationshipType { static final Conversion<String, RelationshipSpec> FROM_STRING = new Conversion<String, RelationshipSpec>() { @Override public RelationshipSpec convert( String source ) { String[] parts = source.split( ":" ); if ( parts.length != 2 ) { throw new IllegalArgumentException( "value must have the format <relationship label>:<count>" ); } return new RelationshipSpec( parts[0], Integer.parseInt( parts[1] ) ); } }; private final String name; final int count; public RelationshipSpec( String name, int count ) { this.name = name; this.count = count; } @Override public String toString() { return name() + ":" + count; } @Override public String name() { return name; } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_RelationshipSpec.java
2,508
class PropertyStats extends RecordStore.Processor<RuntimeException> { Map<Integer, Long> sizeHistogram = new TreeMap<Integer, Long>(); Map<PropertyType, Long> typeHistogram = new EnumMap<PropertyType, Long>( PropertyType.class ); @Override public void processProperty( RecordStore<PropertyRecord> store, PropertyRecord property ) { List<PropertyBlock> blocks = property.getPropertyBlocks(); update( sizeHistogram, blocks.size() ); for ( PropertyBlock block : blocks ) { update( typeHistogram, block.getType() ); } } private <T> void update( Map<T, Long> histogram, T key ) { Long value = histogram.get( key ); histogram.put( key, (value == null) ? 1 : (value + 1) ); } @Override public String toString() { StringBuilder builder = new StringBuilder( getClass().getSimpleName() ).append( "{\n" ); for ( Map.Entry<Integer, Long> entry : sizeHistogram.entrySet() ) { builder.append( '\t' ).append( entry.getKey() ).append( ": " ).append( entry.getValue() ).append( '\n' ); } for ( Map.Entry<PropertyType, Long> entry : typeHistogram.entrySet() ) { builder.append( '\t' ).append( entry.getKey() ).append( ": " ).append( entry.getValue() ).append( '\n' ); } return builder.append( '}' ).toString(); } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertyStats.java
2,509
{ @Override public PropertySpec convert( String value ) { String[] tokens = value.split( ":" ); return new PropertySpec( PropertyGenerator.valueOf( tokens[0] ), Float.parseFloat( tokens[1] ) ); } };
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertySpec.java
2,510
class PropertySpec { public static final Conversion<String,PropertySpec> PARSER = new Conversion<String, PropertySpec>() { @Override public PropertySpec convert( String value ) { String[] tokens = value.split( ":" ); return new PropertySpec( PropertyGenerator.valueOf( tokens[0] ), Float.parseFloat( tokens[1] ) ); } }; private final PropertyGenerator propertyGenerator; private final float count; PropertySpec( PropertyGenerator propertyGenerator, float count ) { this.propertyGenerator = propertyGenerator; this.count = count; } public Map<String, Object> generate() { HashMap<String, Object> map = new HashMap<String, Object>(); int propertyCount = (int) count; if ( DataGenerator.RANDOM.nextFloat() < count - propertyCount) { propertyCount++; } for ( int i = 0; i < propertyCount; i++ ) { map.put( propertyGenerator.name() + "_" + i, propertyGenerator.generate() ); } return map; } @Override public String toString() { return propertyGenerator.name() + ":" + count; } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_generator_PropertySpec.java
2,511
public class NeoServerDocIT extends AbstractRestFunctionalTestBase { private FunctionalTestHelper functionalTestHelper; @Before public void cleanTheDatabase() { cleanDatabase(); functionalTestHelper = new FunctionalTestHelper( server() ); } @Test public void whenServerIsStartedItshouldStartASingleDatabase() throws Exception { assertNotNull( server().getDatabase() ); } @Test public void shouldRedirectRootToWebadmin() throws Exception { assertFalse( server().baseUri() .toString() .contains( "browser" ) ); JaxRsResponse response = RestRequest.req().get( server().baseUri().toString(), MediaType.TEXT_HTML_TYPE ); assertThat( response.getStatus(), is( 200 ) ); assertThat( response.getEntity(), containsString( "Neo4j" ) ); } @Test public void serverShouldProvideAWelcomePage() throws Exception { JaxRsResponse response = RestRequest.req().get( functionalTestHelper.webAdminUri() ); assertThat( response.getStatus(), is( 200 ) ); assertThat( response.getHeaders().getFirst( "Content-Type" ), containsString( "html" ) ); } }
false
community_server_src_test_java_org_neo4j_server_NeoServerDocIT.java
2,512
public class NeoServerJAXRSDocIT extends ExclusiveServerTestBase { private NeoServer server; @Before public void cleanTheDatabase() { ServerHelper.cleanTheDatabase( server ); } @After public void stopServer() { if ( server != null ) { server.stop(); } } @Test public void shouldMakeJAXRSClassesAvailableViaHTTP() throws Exception { server = ServerHelper.createNonPersistentServer(); FunctionalTestHelper functionalTestHelper = new FunctionalTestHelper( server ); JaxRsResponse response = new RestRequest().get( functionalTestHelper.webAdminUri() ); assertEquals( 200, response.getStatus() ); response.close(); } @Test public void shouldLoadThirdPartyJaxRsClasses() throws Exception { server = CommunityServerBuilder.server() .withThirdPartyJaxRsPackage( "org.dummy.web.service", DummyThirdPartyWebService.DUMMY_WEB_SERVICE_MOUNT_POINT ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); URI thirdPartyServiceUri = new URI( server.baseUri() .toString() + DummyThirdPartyWebService.DUMMY_WEB_SERVICE_MOUNT_POINT ).normalize(); String response = CLIENT.resource( thirdPartyServiceUri.toString() ) .get( String.class ); assertEquals( "hello", response ); // Assert that extensions gets initialized int nodesCreated = createSimpleDatabase( server.getDatabase().getGraph() ); thirdPartyServiceUri = new URI( server.baseUri() .toString() + DummyThirdPartyWebService.DUMMY_WEB_SERVICE_MOUNT_POINT + "/inject-test" ).normalize(); response = CLIENT.resource( thirdPartyServiceUri.toString() ) .get( String.class ); assertEquals( String.valueOf( nodesCreated ), response ); } private int createSimpleDatabase( final GraphDatabaseAPI graph ) { final int numberOfNodes = 10; new Transactor( graph, new UnitOfWork() { @Override public void doWork() { for ( int i = 0; i < numberOfNodes; i++ ) { graph.createNode(); } for ( Node n1 : GlobalGraphOperations.at(graph).getAllNodes() ) { for ( Node n2 : GlobalGraphOperations.at(graph).getAllNodes() ) { if ( n1.equals( n2 ) ) { continue; } n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "REL" ) ); } } } } ).execute(); return numberOfNodes; } }
false
community_server_src_test_java_org_neo4j_server_NeoServerJAXRSDocIT.java
2,513
{ @Override public void doWork() { for ( int i = 0; i < numberOfNodes; i++ ) { graph.createNode(); } for ( Node n1 : GlobalGraphOperations.at(graph).getAllNodes() ) { for ( Node n2 : GlobalGraphOperations.at(graph).getAllNodes() ) { if ( n1.equals( n2 ) ) { continue; } n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "REL" ) ); } } } } ).execute();
false
community_server_src_test_java_org_neo4j_server_NeoServerJAXRSDocIT.java
2,514
public class WebadminConfigurationRule implements ValidationRule { @Override public void validate( Configuration configuration ) throws RuleFailedException { String managementApi = validateConfigurationContainsKey( configuration, Configurator.MANAGEMENT_PATH_PROPERTY_KEY ); String restApi = validateConfigurationContainsKey( configuration, Configurator.REST_API_PATH_PROPERTY_KEY ); // Check URIs are ok URI managementUri = validateAndNormalizeUri( managementApi, Configurator.MANAGEMENT_PATH_PROPERTY_KEY ); URI restUri = validateAndNormalizeUri( restApi, Configurator.REST_API_PATH_PROPERTY_KEY ); // Overwrite the properties with the new normalised URIs configuration.clearProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY ); configuration.addProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY, managementUri.toString() ); configuration.clearProperty( Configurator.REST_API_PATH_PROPERTY_KEY ); configuration.addProperty( Configurator.REST_API_PATH_PROPERTY_KEY, restUri.toString() ); } private String trimTrailingSlash( String uri ) { if ( !uri.endsWith( "/" ) ) return uri; return uri.substring( 0, uri.length() - 1 ); } private URI validateAndNormalizeUri( String uri, String property ) throws RuleFailedException { URI result = null; try { result = new URI( uri ).normalize(); String resultStr = result.toString(); if ( resultStr.endsWith( "/" ) ) { result = new URI( trimTrailingSlash( resultStr ) ); } } catch ( URISyntaxException e ) { throw new RuleFailedException( "The specified URI [%s] for the property [%s] is invalid. Please correct the neo4j-server.properties file.", uri, property ); } return result; } private String validateConfigurationContainsKey( Configuration configuration, String key ) throws RuleFailedException { if ( !configuration.containsKey( key ) ) { throw new RuleFailedException( "Webadmin configuration not found. Check that the neo4j-server.properties file contains the [%s] property.", key ); } return (String) configuration.getProperty( key ); } }
false
community_server_src_main_java_org_neo4j_server_configuration_validation_WebadminConfigurationRule.java
2,515
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,516
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,517
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,518
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } } );
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,519
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,520
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { throw new RuleFailedException( "dummy rule failed during unit test" ); } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,521
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule()
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,522
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { throw new RuleFailedException( "dummy rule failed during unit test" ); } } );
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,523
public class ValidatorTest { @Test public void shouldFailWhenRuleFails() { Validator v = new Validator( new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { throw new RuleFailedException( "dummy rule failed during unit test" ); } } ); assertFalse( v.validate( null, ConsoleLogger.DEV_NULL ) ); } @Test public void shouldFailWhenAtLeastOneRuleFails() { Validator v = new Validator( new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { throw new RuleFailedException( "dummy rule failed during unit test" ); } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } } ); assertFalse( v.validate( null, ConsoleLogger.DEV_NULL ) ); } @Test public void shouldPassWhenAllRulesComplete() { Validator v = new Validator( new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } }, new ValidationRule() { @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } } ); assertTrue( v.validate( null, ConsoleLogger.DEV_NULL ) ); } }
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,524
public class Validator { private final ArrayList<ValidationRule> validationRules = new ArrayList<ValidationRule>(); public Validator( ValidationRule... rules ) { if ( rules == null ) { return; } for ( ValidationRule r : rules ) { this.validationRules.add( r ); } } public boolean validate( Configuration configuration, ConsoleLogger log ) { for ( ValidationRule vr : validationRules ) { try { vr.validate( configuration ); } catch ( RuleFailedException rfe ) { log.warn( rfe.getMessage() ); return false; } } return true; } public static final Validator NO_VALIDATION = new Validator(); }
false
community_server_src_main_java_org_neo4j_server_configuration_validation_Validator.java
2,525
@SuppressWarnings( "serial" ) public class RuleFailedException extends Exception { public RuleFailedException( String message ) { super( message ); } public RuleFailedException( String message, Object... args ) { super( String.format( message, args ) ); } }
false
community_server_src_main_java_org_neo4j_server_configuration_validation_RuleFailedException.java
2,526
public class DatabaseLocationMustBeSpecifiedRuleTest { @Test( expected = RuleFailedException.class ) public void shouldFailWhenDatabaseLocationIsAbsentFromConfig() throws RuleFailedException { DatabaseLocationMustBeSpecifiedRule theRule = new DatabaseLocationMustBeSpecifiedRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( "foo", "bar" ); theRule.validate( config ); } }
false
community_server_src_test_java_org_neo4j_server_configuration_validation_DatabaseLocationMustBeSpecifiedRuleTest.java
2,527
public class DatabaseLocationMustBeSpecifiedRule implements ValidationRule { public void validate( Configuration configuration ) throws RuleFailedException { String dbLocation = configuration.getString( Configurator.DATABASE_LOCATION_PROPERTY_KEY ); if ( dbLocation == null || dbLocation.length() < 1 ) { throw new RuleFailedException( "The key [%s] is missing from the Neo Server configuration.", Configurator.DATABASE_LOCATION_PROPERTY_KEY ); } } }
false
community_server_src_main_java_org_neo4j_server_configuration_validation_DatabaseLocationMustBeSpecifiedRule.java
2,528
public class ThirdPartyJaxRsPackage { private final String packageName; private final String mountPoint; public ThirdPartyJaxRsPackage( String packageName, String mountPoint ) { this.packageName = packageName; this.mountPoint = mountPoint; } public String getPackageName() { return packageName; } public String getMountPoint() { return mountPoint; } }
false
community_server_src_main_java_org_neo4j_server_configuration_ThirdPartyJaxRsPackage.java
2,529
public class ServerConfigurator extends Configurator.Adapter { private final MapBasedConfiguration config = new MapBasedConfiguration(); private final List<ThirdPartyJaxRsPackage> jaxRsPackages = new ArrayList<>(); public ServerConfigurator( GraphDatabaseAPI db ) { config.addProperty( DATABASE_LOCATION_PROPERTY_KEY, db.getStoreDir() ); } @Override public Configuration configuration() { return config; } @Override public Map<String, String> getDatabaseTuningProperties() { return stringMap(); } @Override public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsPackages() { return jaxRsPackages; } }
false
community_server_src_main_java_org_neo4j_server_configuration_ServerConfigurator.java
2,530
public class PropertyFileConfiguratorTest { @Rule public Mute mute = muteAll(); @Rule public TemporaryFolder folder = new TemporaryFolder( ); @Test public void whenDatabaseTuningFilePresentInDefaultLocationShouldLoadItEvenIfNotSpecified() throws IOException { File emptyPropertyFile = PropertyFileBuilder.builder( folder.getRoot() ) .build(); DatabaseTuningPropertyFileBuilder.builder( folder.getRoot() ) .build(); PropertyFileConfigurator configurator = new PropertyFileConfigurator( emptyPropertyFile ); assertNotNull( configurator.getDatabaseTuningProperties() .get( "neostore.nodestore.db.mapped_memory" ) ); assertEquals( "25M", configurator.getDatabaseTuningProperties() .get( "neostore.nodestore.db.mapped_memory" ) ); } @Test public void whenDatabaseTuningFilePresentInDefaultLocationShouldNotLoadIfAnotherSpecified() throws IOException { int unlikelyDefaultMemoryMappedValue = 8351; File databaseTuningPropertyFileWeWantToUse = DatabaseTuningPropertyFileBuilder.builder( folder.getRoot() ) .mappedMemory( unlikelyDefaultMemoryMappedValue ) .build(); File emptyPropertyFile = PropertyFileBuilder.builder( folder.getRoot() ) .withDbTuningPropertyFile( databaseTuningPropertyFileWeWantToUse ) .build(); // The tuning properties we want to ignore, in the same dir as the neo // server properties DatabaseTuningPropertyFileBuilder.builder( folder.newFolder() ) .build(); PropertyFileConfigurator configurator = new PropertyFileConfigurator( emptyPropertyFile ); assertNotNull( configurator.getDatabaseTuningProperties() .get( "neostore.nodestore.db.mapped_memory" ) ); assertEquals( String.valueOf( unlikelyDefaultMemoryMappedValue ) + "M", configurator.getDatabaseTuningProperties() .get( "neostore.nodestore.db.mapped_memory" ) ); } @Test public void shouldLogInfoWhenDefaultingToTuningPropertiesFileInTheSameDirectoryAsTheNeoServerPropertiesFile() throws IOException { File emptyPropertyFile = PropertyFileBuilder.builder( folder.getRoot() ) .build(); File tuningPropertiesFile = DatabaseTuningPropertyFileBuilder.builder( folder.getRoot() ) .build(); BufferingConsoleLogger logger = new BufferingConsoleLogger(); new PropertyFileConfigurator( Validator.NO_VALIDATION, emptyPropertyFile, logger ); assertThat( logger.toString(), containsString( String.format( "No database tuning file explicitly set, defaulting to [%s]", tuningPropertiesFile.getAbsolutePath() ) ) ); } @Test public void shouldRetainRegistrationOrderOfThirdPartyJaxRsPackages() throws IOException { File propertyFile = PropertyFileBuilder.builder( folder.getRoot() ) .withNameValue( Configurator.THIRD_PARTY_PACKAGES_KEY, "org.neo4j.extension.extension1=/extension1,org.neo4j.extension.extension2=/extension2," + "org.neo4j.extension.extension3=/extension3" ) .build(); PropertyFileConfigurator propertyFileConfigurator = new PropertyFileConfigurator( propertyFile ); List<ThirdPartyJaxRsPackage> thirdpartyJaxRsPackages = propertyFileConfigurator.getThirdpartyJaxRsPackages(); assertEquals( 3, thirdpartyJaxRsPackages.size() ); assertEquals( "/extension1", thirdpartyJaxRsPackages.get( 0 ).getMountPoint() ); assertEquals( "/extension2", thirdpartyJaxRsPackages.get( 1 ).getMountPoint() ); assertEquals( "/extension3", thirdpartyJaxRsPackages.get( 2 ).getMountPoint() ); } }
false
community_server_src_test_java_org_neo4j_server_configuration_PropertyFileConfiguratorTest.java
2,531
{ @Override public boolean accept( File dir, String name ) { return name.toLowerCase() .equals( NEO4J_PROPERTIES_FILENAME ); } } );
false
community_server_src_main_java_org_neo4j_server_configuration_PropertyFileConfigurator.java
2,532
public class PropertyFileConfigurator extends Configurator.Adapter { private static final String NEO4J_PROPERTIES_FILENAME = "neo4j.properties"; private final CompositeConfiguration serverConfiguration = new CompositeConfiguration(); private File propertyFileDirectory; private final Validator validator = new Validator(); private Map<String, String> databaseTuningProperties = null; public PropertyFileConfigurator( File propertiesFile ) { this( Validator.NO_VALIDATION, propertiesFile, ConsoleLogger.DEV_NULL ); } public PropertyFileConfigurator( Validator v, File propertiesFile, ConsoleLogger log ) { if ( propertiesFile == null ) { propertiesFile = new File( System.getProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY ) ); } try { propertyFileDirectory = propertiesFile.getParentFile(); loadPropertiesConfig( propertiesFile, log ); loadDatabaseTuningProperties( propertiesFile, log ); normalizeUris(); ensureRelativeUris(); if ( v != null ) { v.validate( this.configuration(), log ); } } catch ( ConfigurationException ce ) { log.warn( "Invalid configuration", ce ); } } @Override public Configuration configuration() { return serverConfiguration == null ? new SystemConfiguration() : serverConfiguration; } private void loadDatabaseTuningProperties( File configFile, ConsoleLogger log ) throws ConfigurationException { String databaseTuningPropertyFileLocation = serverConfiguration.getString( DB_TUNING_PROPERTY_FILE_KEY ); if ( databaseTuningPropertyFileLocation == null ) { if ( propertyFileDirectoryContainsDBTuningFile() ) { databaseTuningPropertyFileLocation = new File( propertyFileDirectory, NEO4J_PROPERTIES_FILENAME ).getAbsolutePath(); log.log( "No database tuning file explicitly set, defaulting to [%s]", databaseTuningPropertyFileLocation ); } else { log.log( "No database tuning properties (org.neo4j.server.db.tuning.properties) found in [%s], using defaults.", configFile.getPath() ); return; } } File databaseTuningPropertyFile = new File( databaseTuningPropertyFileLocation ); if ( !databaseTuningPropertyFile.exists() ) { log.warn( "The specified file for database performance tuning properties [%s] does not exist.", databaseTuningPropertyFileLocation ); return; } try { databaseTuningProperties = MapUtil.load(databaseTuningPropertyFile); } catch( IOException e ) { databaseTuningProperties = new HashMap<String, String>(); } } private void loadPropertiesConfig( File configFile, ConsoleLogger log ) throws ConfigurationException { PropertiesConfiguration propertiesConfig = new PropertiesConfiguration( configFile ); if ( validator.validate( propertiesConfig, log ) ) { serverConfiguration.addConfiguration( propertiesConfig ); } else { String failed = String.format( "Error processing [%s], configuration file has failed validation.", configFile.getAbsolutePath() ); log.error( failed ); throw new InvalidServerConfigurationException( failed ); } } private void normalizeUris() { try { for ( String key : new String[] { MANAGEMENT_PATH_PROPERTY_KEY, REST_API_PATH_PROPERTY_KEY } ) { if ( configuration().containsKey( key ) ) { URI normalizedUri = new URI( (String) configuration().getProperty( key ) ).normalize(); configuration().clearProperty( key ); configuration().addProperty( key, normalizedUri.toString() ); } } } catch ( URISyntaxException e ) { throw new RuntimeException( e ); } } private void ensureRelativeUris() { try { for ( String key : new String[] { MANAGEMENT_PATH_PROPERTY_KEY, REST_API_PATH_PROPERTY_KEY } ) { if ( configuration().containsKey( key ) ) { String path = new URI( (String) configuration().getProperty( key ) ).getPath(); configuration().clearProperty( key ); configuration().addProperty( key, path ); } } } catch ( URISyntaxException e ) { throw new RuntimeException( e ); } } private boolean propertyFileDirectoryContainsDBTuningFile() { File[] neo4jPropertyFiles = propertyFileDirectory.listFiles( new FilenameFilter() { @Override public boolean accept( File dir, String name ) { return name.toLowerCase() .equals( NEO4J_PROPERTIES_FILENAME ); } } ); return neo4jPropertyFiles != null && neo4jPropertyFiles.length == 1; } public File getPropertyFileDirectory() { return propertyFileDirectory; } @Override public Map<String, String> getDatabaseTuningProperties() { return databaseTuningProperties == null ? new HashMap<String, String>() : databaseTuningProperties; } @Override public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsPackages() { List<ThirdPartyJaxRsPackage> thirdPartyPackages = new ArrayList<ThirdPartyJaxRsPackage>(); List<String> packagesAndMountpoints = this.configuration().getList( THIRD_PARTY_PACKAGES_KEY ); for ( String packageAndMoutpoint : packagesAndMountpoints ) { String[] parts = packageAndMoutpoint.split( "=" ); if ( parts.length != 2 ) { throw new IllegalArgumentException( "config for " + THIRD_PARTY_PACKAGES_KEY + " is wrong: " + packageAndMoutpoint ); } String pkg = parts[0]; String mountPoint = parts[1]; thirdPartyPackages.add( new ThirdPartyJaxRsPackage( pkg, mountPoint ) ); } return thirdPartyPackages; } }
false
community_server_src_main_java_org_neo4j_server_configuration_PropertyFileConfigurator.java
2,533
private static class Tuple { public Tuple( String name, String value ) { this.name = name; this.value = value; } public String name; public String value; }
false
community_server_src_test_java_org_neo4j_server_configuration_PropertyFileBuilder.java
2,534
{ @Override public void validate( Configuration configuration ) throws RuleFailedException { // do nothing } } );
false
community_server_src_test_java_org_neo4j_server_configuration_validation_ValidatorTest.java
2,535
public class WebadminConfigurationRuleTest { private static final boolean theValidatorHasPassed = true; @Test( expected = RuleFailedException.class ) public void shouldFailIfNoWebadminConfigSpecified() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration emptyConfig = new BaseConfiguration(); rule.validate( emptyConfig ); assertFalse( theValidatorHasPassed ); } @Test( expected = RuleFailedException.class ) public void shouldFailIfOnlyRestApiKeySpecified() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( Configurator.REST_API_PATH_PROPERTY_KEY, "http://localhost:7474/db/data" ); rule.validate( config ); assertFalse( theValidatorHasPassed ); } @Test( expected = RuleFailedException.class ) public void shouldFailIfOnlyAdminApiKeySpecified() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY, "http://localhost:7474/db/manage" ); rule.validate( config ); assertFalse( theValidatorHasPassed ); } @Test public void shouldAllowAbsoluteUris() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( Configurator.REST_API_PATH_PROPERTY_KEY, "http://localhost:7474/db/data" ); config.addProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY, "http://localhost:7474/db/manage" ); rule.validate( config ); assertTrue( theValidatorHasPassed ); } @Test public void shouldAllowRelativeUris() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( Configurator.REST_API_PATH_PROPERTY_KEY, "/db/data" ); config.addProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY, "/db/manage" ); rule.validate( config ); assertTrue( theValidatorHasPassed ); } @Test public void shouldNormaliseUris() throws RuleFailedException { WebadminConfigurationRule rule = new WebadminConfigurationRule(); BaseConfiguration config = new BaseConfiguration(); config.addProperty( Configurator.REST_API_PATH_PROPERTY_KEY, "http://localhost:7474///db///data///" ); config.addProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY, "http://localhost:7474////db///manage" ); rule.validate( config ); assertThat( (String) config.getProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY ), not( containsString( "///" ) ) ); assertFalse( ( (String) config.getProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY ) ).endsWith( "//" ) ); assertFalse( ( (String) config.getProperty( Configurator.MANAGEMENT_PATH_PROPERTY_KEY ) ).endsWith( "/" ) ); assertThat( (String) config.getProperty( Configurator.REST_API_PATH_PROPERTY_KEY ), not( containsString( "///" ) ) ); assertFalse( ( (String) config.getProperty( Configurator.REST_API_PATH_PROPERTY_KEY ) ).endsWith( "//" ) ); assertFalse( ( (String) config.getProperty( Configurator.REST_API_PATH_PROPERTY_KEY ) ).endsWith( "/" ) ); } }
false
community_server_src_test_java_org_neo4j_server_configuration_validation_WebadminConfigurationRuleTest.java
2,536
public class NeoServerPortConflictDocIT extends ExclusiveServerTestBase { @Test public void shouldComplainIfServerPortIsAlreadyTaken() throws IOException { int contestedPort = 9999; try ( ServerSocket ignored = new ServerSocket( contestedPort, 0, InetAddress.getByName(Jetty9WebServer.DEFAULT_ADDRESS ) ) ) { Logging logging = new BufferingLogging(); CommunityNeoServer server = CommunityServerBuilder.server() .onPort( contestedPort ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .onHost( Jetty9WebServer.DEFAULT_ADDRESS ) .withLogging( logging ) .build(); try { server.start(); fail( "Should have reported failure to start" ); } catch ( ServerStartupException e ) { assertThat( e.getMessage(), containsString( "Starting Neo4j Server failed" ) ); } // Don't include the SEVERE string since it's // OS-regional-settings-specific assertThat( logging.toString(), containsString( String.format( "Failed to start Neo Server" ) ) ); server.stop(); } } }
false
community_server_src_test_java_org_neo4j_server_NeoServerPortConflictDocIT.java
2,537
public class CommunityDatabase implements Database { protected final Configurator configurator; protected final Configuration serverConfiguration; protected final Logging logging; protected final ConsoleLogger log; private boolean isRunning = false; private AbstractGraphDatabase graph; @SuppressWarnings("deprecation") public CommunityDatabase( Configurator configurator, Logging logging ) { this.logging = logging; this.configurator = configurator; this.serverConfiguration = configurator.configuration(); this.log = logging.getConsoleLog( getClass() ); } protected AbstractGraphDatabase createDb() { return (AbstractGraphDatabase) new org.neo4j.graphdb.factory.GraphDatabaseFactory() .newEmbeddedDatabaseBuilder( serverConfiguration.getString( DATABASE_LOCATION_PROPERTY_KEY, DEFAULT_DATABASE_LOCATION_PROPERTY_KEY ) ) .setConfig( getDbTuningPropertiesWithServerDefaults() ) .newGraphDatabase(); } @Override public String getLocation() { return graph.getStoreDir(); } @Override public Logging getLogging() { return logging; } @Override public org.neo4j.graphdb.index.Index<Relationship> getRelationshipIndex( String name ) { RelationshipIndex index = graph.index().forRelationships( name ); if ( index == null ) { throw new RuntimeException( "No index for [" + name + "]" ); } return index; } @Override public org.neo4j.graphdb.index.Index<Node> getNodeIndex( String name ) { org.neo4j.graphdb.index.Index<Node> index = graph.index() .forNodes( name ); if ( index == null ) { throw new RuntimeException( "No index for [" + name + "]" ); } return index; } @Override public IndexManager getIndexManager() { return graph.index(); } @Override public GraphDatabaseAPI getGraph() { return graph; } @Override public void init() throws Throwable { } @Override public void start() throws Throwable { try { this.graph = createDb(); isRunning = true; log.log( "Successfully started database" ); } catch ( Exception e ) { log.error( "Failed to start database.", e ); throw e; } } @Override public void stop() throws Throwable { try { if ( this.graph != null ) { this.graph.shutdown(); isRunning = false; this.graph = null; log.log( "Successfully stopped database" ); } } catch ( Exception e ) { log.error( String.format("Database did not stop cleanly. Reason [%s]", e.getMessage()) ); throw e; } } @Override public void shutdown() throws Throwable { } @Override public boolean isRunning() { return isRunning; } protected Map<String, String> getDbTuningPropertiesWithServerDefaults() { Map<String, String> result = new HashMap<>( configurator.getDatabaseTuningProperties() ); putIfAbsent( result, ShellSettings.remote_shell_enabled.name(), Settings.TRUE ); putIfAbsent( result, GraphDatabaseSettings.keep_logical_logs.name(), Settings.TRUE ); try { result.put( UdcSettings.udc_source.name(), "server" ); } catch ( NoClassDefFoundError e ) { // UDC is not on classpath, ignore } return result; } private void putIfAbsent( Map<String, String> databaseProperties, String configKey, String configValue ) { if ( databaseProperties.get( configKey ) == null ) { databaseProperties.put( configKey, configValue ); } } }
false
community_server_src_main_java_org_neo4j_server_database_CommunityDatabase.java
2,538
{ @Override public Configuration configuration() { return new MapConfiguration( stringMap( DATABASE_LOCATION_PROPERTY_KEY, testDirectory.directory().getPath() ) ); } }, DevNullLoggingService.DEV_NULL );
false
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_EnterpriseDatabaseIT.java
2,539
public class EnterpriseDatabaseIT { @Rule public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() ); @Test public void shouldStartInSingleModeByDefault() throws Throwable { EnterpriseDatabase db = new EnterpriseDatabase( new Configurator.Adapter() { @Override public Configuration configuration() { return new MapConfiguration( stringMap( DATABASE_LOCATION_PROPERTY_KEY, testDirectory.directory().getPath() ) ); } }, DevNullLoggingService.DEV_NULL ); try { db.start(); assertThat( db.getGraph(), is( EmbeddedGraphDatabase.class ) ); } finally { db.stop(); } } }
false
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_EnterpriseDatabaseIT.java
2,540
HA { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( databaseStoreDirectory ). setConfig( databaseProperties ).newGraphDatabase(); } };
false
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnterpriseDatabase.java
2,541
SINGLE { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new org.neo4j.graphdb.factory.GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( databaseStoreDirectory). setConfig( databaseProperties ).newGraphDatabase(); } },
false
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnterpriseDatabase.java
2,542
public class EnterpriseDatabase extends CommunityDatabase { enum DatabaseMode implements GraphDatabaseFactory { SINGLE { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new org.neo4j.graphdb.factory.GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( databaseStoreDirectory). setConfig( databaseProperties ).newGraphDatabase(); } }, HA { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( databaseStoreDirectory ). setConfig( databaseProperties ).newGraphDatabase(); } }; @Override public abstract GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ); } public EnterpriseDatabase( Configurator configurator, Logging logging ) { super( configurator, logging ); } @Override protected AbstractGraphDatabase createDb() { GraphDatabaseFactory factory = DatabaseMode.valueOf( serverConfiguration.getString( Configurator.DB_MODE_KEY, DatabaseMode.SINGLE.name() ).toUpperCase() ); return (AbstractGraphDatabase) factory.createDatabase( serverConfiguration.getString( Configurator.DATABASE_LOCATION_PROPERTY_KEY, Configurator.DEFAULT_DATABASE_LOCATION_PROPERTY_KEY ), getDbTuningPropertiesWithServerDefaults() ); } }
false
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnterpriseDatabase.java
2,543
public class EnterpriseBootstrapper extends AdvancedBootstrapper { @Override protected NeoServer createNeoServer() { return new EnterpriseNeoServer( configurator, logging ); } }
false
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnterpriseBootstrapper.java
2,544
public class EnsureEnterpriseNeo4jPropertiesExist extends EnsureNeo4jPropertiesExist { public static final String CONFIG_KEY_OLD_SERVER_ID = "ha.machine_id"; public static final String CONFIG_KEY_OLD_COORDINATORS = "ha.zoo_keeper_servers"; public EnsureEnterpriseNeo4jPropertiesExist( Configuration config ) { super( config ); } // TODO: This validation should be done by the settings classes in HA // and by the enterprise server settings, once we have refactored them // to use the new config scheme. @Override protected boolean validateProperties( Properties configProperties ) { String dbMode = configProperties.getProperty( Configurator.DB_MODE_KEY, EnterpriseDatabase.DatabaseMode.SINGLE.name() ); dbMode = dbMode.toUpperCase(); if ( dbMode.equals( EnterpriseDatabase.DatabaseMode.SINGLE.name() ) ) { return true; } if ( !dbMode.equals( EnterpriseDatabase.DatabaseMode.HA.name() ) ) { failureMessage = String.format( "Illegal value for %s \"%s\" in %s", Configurator.DB_MODE_KEY, dbMode, Configurator.NEO_SERVER_CONFIG_FILE_KEY ); return false; } String dbTuningFilename = configProperties.getProperty( Configurator.DB_TUNING_PROPERTY_FILE_KEY ); if ( dbTuningFilename == null ) { failureMessage = String.format( "High-Availability mode requires %s to be set in %s", Configurator.DB_TUNING_PROPERTY_FILE_KEY, Configurator.NEO_SERVER_CONFIG_FILE_KEY ); return false; } else { File dbTuningFile = new File( dbTuningFilename ); if ( !dbTuningFile.exists() ) { failureMessage = String.format( "No database tuning file at [%s]", dbTuningFile.getAbsoluteFile() ); return false; } else { Properties dbTuning = new Properties(); try { InputStream tuningStream = new FileInputStream( dbTuningFile ); try { dbTuning.load( tuningStream ); } finally { tuningStream.close(); } } catch ( IOException e ) { // Shouldn't happen, we already covered those cases failureMessage = e.getMessage(); return false; } String machineId = null; try { machineId = getSinglePropertyFromCandidates( dbTuning, ClusterSettings.server_id.name(), CONFIG_KEY_OLD_SERVER_ID, "<not set>" ); if ( Integer.parseInt( machineId ) < 0 ) { throw new NumberFormatException(); } } catch ( NumberFormatException e ) { failureMessage = String.format( "%s in %s needs to be a non-negative integer, not %s", ClusterSettings.server_id.name(), dbTuningFilename, machineId ); return false; } catch ( IllegalArgumentException e ) { failureMessage = String.format( "%s in %s", e.getMessage(), dbTuningFilename ); return false; } } } return true; } private String getSinglePropertyFromCandidates( Properties dbTuning, String first, String other, String defaultValue ) { String firstValue = dbTuning.getProperty( first ); String otherValue = dbTuning.getProperty( other ); if ( firstValue == null && otherValue == null ) { return defaultValue; } // Perhaps not a correct use of IllegalArgumentException if ( firstValue != null && otherValue != null ) { throw new IllegalArgumentException( "Multiple configuration values set for the same logical property [" + first + "," + other + "]" ); } return firstValue != null ? firstValue : otherValue; } }
false
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_EnsureEnterpriseNeo4jPropertiesExist.java
2,545
public class WrappedDatabase extends CommunityDatabase { private final AbstractGraphDatabase db; public WrappedDatabase( AbstractGraphDatabase db ) { this( db, new ServerConfigurator( db ) ); } public WrappedDatabase( AbstractGraphDatabase db, Configurator configurator ) { super( configurator, getLogging( db ) ); this.db = db; try { start(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } } @Override protected AbstractGraphDatabase createDb() { return db; } @Override public void stop() throws Throwable { // No-op } @Override public Logging getLogging() { return getLogging( db ); } private static Logging getLogging( AbstractGraphDatabase db ) { return db.getDependencyResolver().resolveDependency( Logging.class ); } }
false
community_server_src_main_java_org_neo4j_server_database_WrappedDatabase.java
2,546
{ @Override public Configuration configuration() { return new MapConfiguration( stringMap( Configurator.DATABASE_LOCATION_PROPERTY_KEY, tempDir.getAbsolutePath() ) ); } @Override public Map<String, String> getDatabaseTuningProperties() { return stringMap( ShellSettings.remote_shell_enabled.name(), Settings.TRUE, ShellSettings.remote_shell_port.name(), "" + customPort ); } }, logging );
false
community_server_src_test_java_org_neo4j_server_database_TestCommunityDatabase.java
2,547
{ @Override public Configuration configuration() { return new MapConfiguration( serverProperties ); } };
false
community_server_src_test_java_org_neo4j_server_database_TestCommunityDatabase.java
2,548
public class TestCommunityDatabase { @Rule public Mute mute = muteAll(); private File databaseDirectory; private Database theDatabase; private boolean deletionFailureOk; private Logging logging; @Before public void setup() throws Exception { databaseDirectory = createTempDir(); logging = new BufferingLogging(); theDatabase = new CommunityDatabase( configuratorWithServerProperties( stringMap( Configurator.DATABASE_LOCATION_PROPERTY_KEY, databaseDirectory.getAbsolutePath() ) ), logging ); } private static Configurator configuratorWithServerProperties( final Map<String, String> serverProperties ) { return new Configurator.Adapter() { @Override public Configuration configuration() { return new MapConfiguration( serverProperties ); } }; } @After public void shutdownDatabase() throws Throwable { this.theDatabase.stop(); try { FileUtils.forceDelete( databaseDirectory ); } catch ( IOException e ) { // TODO Removed this when EmbeddedGraphDatabase startup failures // closes its // files properly. if ( !deletionFailureOk ) { throw e; } } } @Test public void shouldLogOnSuccessfulStartup() throws Throwable { theDatabase.start(); assertThat( logging.toString(), containsString( "Successfully started database" ) ); } @Test public void shouldShutdownCleanly() throws Throwable { theDatabase.start(); theDatabase.stop(); assertThat( logging.toString(), containsString( "Successfully stopped database" ) ); } @Test public void shouldComplainIfDatabaseLocationIsAlreadyInUse() throws Throwable { deletionFailureOk = true; theDatabase.start(); CommunityDatabase db = new CommunityDatabase( configuratorWithServerProperties( stringMap( Configurator.DATABASE_LOCATION_PROPERTY_KEY, databaseDirectory.getAbsolutePath() ) ), logging ); try { db.start(); } catch ( RuntimeException e ) { // Wrapped in a lifecycle exception, needs to be dug out assertThat( e.getCause().getCause(), instanceOf( StoreLockException.class ) ); } } @Test public void connectWithShellOnDefaultPortWhenNoShellConfigSupplied() throws Throwable { theDatabase.start(); ShellLobby.newClient() .shutdown(); } @Test public void shouldBeAbleToOverrideShellConfig() throws Throwable { final int customPort = findFreeShellPortToUse( 8881 ); final File tempDir = createTempDir(); Database otherDb = new CommunityDatabase( new Configurator.Adapter() { @Override public Configuration configuration() { return new MapConfiguration( stringMap( Configurator.DATABASE_LOCATION_PROPERTY_KEY, tempDir.getAbsolutePath() ) ); } @Override public Map<String, String> getDatabaseTuningProperties() { return stringMap( ShellSettings.remote_shell_enabled.name(), Settings.TRUE, ShellSettings.remote_shell_port.name(), "" + customPort ); } }, logging ); otherDb.start(); // Try to connect with a shell client to that custom port. // Throws exception if unable to connect ShellLobby.newClient( customPort ) .shutdown(); otherDb.stop(); // FileUtils.forceDelete( tempDir ); } @Test @SuppressWarnings( "deprecation" ) public void shouldBeAbleToGetLocation() throws Throwable { theDatabase.start(); assertThat( theDatabase.getLocation(), is( theDatabase.getGraph().getStoreDir() ) ); } private int findFreeShellPortToUse( int startingPort ) { // Make sure there's no other random stuff on that port while ( true ) { try { ShellLobby.newClient( startingPort++ ).shutdown(); } catch ( ShellException e ) { // Good return startingPort; } } } }
false
community_server_src_test_java_org_neo4j_server_database_TestCommunityDatabase.java
2,549
static class Plain implements RrdDbWrapper { private final RrdDb db; public Plain( RrdDb db ) { this.db = db; } @Override public RrdDb get() { return db; } @Override public void close() throws IOException { db.close(); } }
false
community_server_src_main_java_org_neo4j_server_database_RrdDbWrapper.java
2,550
return new InjectableProvider<E>(componentClass) { @Override public E getValue(HttpContext httpContext) { return component; } };
false
community_server_src_main_java_org_neo4j_server_database_InjectableProvider.java
2,551
public abstract class InjectableProvider<E> extends AbstractHttpContextInjectable<E> implements com.sun.jersey.spi.inject.InjectableProvider<Context, Class<E>> { public final Class<E> t; public static <E> InjectableProvider<? extends E> providerForSingleton(final E component, final Class<E> componentClass) { return new InjectableProvider<E>(componentClass) { @Override public E getValue(HttpContext httpContext) { return component; } }; } public InjectableProvider( Class<E> t ) { this.t = t; } public Injectable<E> getInjectable( ComponentContext ic, Context a, Class<E> c ) { if ( c.equals( t ) ) { return getInjectable(); } return null; } public Injectable<E> getInjectable() { return this; } public ComponentScope getScope() { return ComponentScope.PerRequest; } }
false
community_server_src_main_java_org_neo4j_server_database_InjectableProvider.java
2,552
@Provider public class GraphDatabaseServiceProvider extends InjectableProvider<GraphDatabaseService> { public Database database; public GraphDatabaseServiceProvider( Database database ) { super( GraphDatabaseService.class ); this.database = database; } @Override public GraphDatabaseService getValue( HttpContext httpContext ) { return database.getGraph(); } }
false
community_server_src_main_java_org_neo4j_server_database_GraphDatabaseServiceProvider.java
2,553
public class EphemeralDatabase extends CommunityDatabase { public EphemeralDatabase( Configurator configurator ) { super( configurator, DevNullLoggingService.DEV_NULL ); } @Override protected AbstractGraphDatabase createDb() { return (AbstractGraphDatabase) new TestGraphDatabaseFactory() .newImpermanentDatabaseBuilder() .setConfig( getDbTuningPropertiesWithServerDefaults() ) .newGraphDatabase(); } @Override public void shutdown() { if ( this.getGraph() != null ) { this.getGraph().shutdown(); } } }
false
community_server_src_test_java_org_neo4j_server_database_EphemeralDatabase.java
2,554
@Provider public class DatabaseProvider extends InjectableProvider<Database> { public Database db; public DatabaseProvider( Database db ) { super( Database.class ); this.db = db; } @Override public Database getValue( HttpContext httpContext ) { return db; } }
false
community_server_src_main_java_org_neo4j_server_database_DatabaseProvider.java
2,555
@Provider public class CypherExecutorProvider extends InjectableProvider<CypherExecutor> { public CypherExecutor cypherExecutor; public CypherExecutorProvider( CypherExecutor cypherExecutor ) { super( CypherExecutor.class ); this.cypherExecutor = cypherExecutor; } @Override public CypherExecutor getValue( HttpContext httpContext ) { return cypherExecutor; } }
false
community_server_src_main_java_org_neo4j_server_database_CypherExecutorProvider.java
2,556
public class CypherExecutor extends LifecycleAdapter { private final Database database; private final StringLogger logger; private ExecutionEngine executionEngine; public CypherExecutor( Database database, StringLogger logger ) { this.database = database; this.logger = logger; } public ExecutionEngine getExecutionEngine() { return executionEngine; } @Override public void start() throws Throwable { this.executionEngine = new ExecutionEngine( database.getGraph(), logger ); } @Override public void stop() throws Throwable { this.executionEngine = null; } }
false
community_server_src_main_java_org_neo4j_server_database_CypherExecutor.java
2,557
public class PropertyFileBuilder { private final String portNo = "7474"; private final String webAdminUri = "http://localhost:7474/db/manage/"; private final String webAdminDataUri = "http://localhost:7474/db/data/"; private String dbTuningPropertyFile = null; private final ArrayList<Tuple> nameValuePairs = new ArrayList<Tuple>(); private final File directory; private static class Tuple { public Tuple( String name, String value ) { this.name = name; this.value = value; } public String name; public String value; } public static PropertyFileBuilder builder( File directory ) { return new PropertyFileBuilder( directory ); } private PropertyFileBuilder( File directory ) { this.directory = directory; } public File build() throws IOException { File file = new File( directory, "config" ); Map<String, String> properties = MapUtil.stringMap( Configurator.DATABASE_LOCATION_PROPERTY_KEY, directory.getAbsolutePath(), Configurator.RRDB_LOCATION_PROPERTY_KEY, directory.getAbsolutePath(), Configurator.MANAGEMENT_PATH_PROPERTY_KEY, webAdminUri, Configurator.REST_API_PATH_PROPERTY_KEY, webAdminDataUri ); if ( portNo != null ) properties.put( Configurator.WEBSERVER_PORT_PROPERTY_KEY, portNo ); if ( dbTuningPropertyFile != null ) properties.put( Configurator.DB_TUNING_PROPERTY_FILE_KEY, dbTuningPropertyFile ); for ( Tuple t : nameValuePairs ) properties.put( t.name, t.value ); ServerTestUtils.writePropertiesToFile( properties, file ); return file; } public PropertyFileBuilder withDbTuningPropertyFile( File f ) { dbTuningPropertyFile = f.getAbsolutePath(); return this; } public PropertyFileBuilder withNameValue( String name, String value ) { nameValuePairs.add( new Tuple( name, value ) ); return this; } public PropertyFileBuilder withDbTuningPropertyFile( String propertyFileLocation ) { dbTuningPropertyFile = propertyFileLocation; return this; } }
false
community_server_src_test_java_org_neo4j_server_configuration_PropertyFileBuilder.java
2,558
public class MapBasedConfiguration extends AbstractConfiguration { private Map<String, Object> config = new HashMap<String, Object>(); @Override public boolean isEmpty() { return config.isEmpty(); } @Override public boolean containsKey( String key ) { return config.containsKey( key ); } @Override public Object getProperty( String key ) { return config.get( key ); } @Override public Iterator<String> getKeys() { return config.keySet() .iterator(); } @Override protected void addPropertyDirect( String key, Object value ) { config.put( key, value ); } }
false
community_server_src_main_java_org_neo4j_server_configuration_MapBasedConfiguration.java
2,559
@SuppressWarnings( "serial" ) public class InvalidServerConfigurationException extends RuntimeException { public InvalidServerConfigurationException( String message ) { super( message ); } }
false
community_server_src_main_java_org_neo4j_server_configuration_InvalidServerConfigurationException.java
2,560
public class DatabaseTuningPropertyFileBuilder { private File parentDirectory = null; private String mappedMemory = null; public static DatabaseTuningPropertyFileBuilder builder( File directory ) { return new DatabaseTuningPropertyFileBuilder( directory ); } private DatabaseTuningPropertyFileBuilder( File directory ) { this.parentDirectory = directory; } public File build() throws IOException { File temporaryConfigFile = new File( parentDirectory, "neo4j.properties" ); Map<String, String> properties = MapUtil.stringMap( "neostore.relationshipstore.db.mapped_memory", "50M", "neostore.propertystore.db.mapped_memory", "90M", "neostore.propertystore.db.strings.mapped_memory", "130M", "neostore.propertystore.db.arrays.mapped_memory", "150M" ); if ( mappedMemory == null ) { properties.put( "neostore.nodestore.db.mapped_memory", "25M" ); } else { properties.put( "neostore.nodestore.db.mapped_memory", mappedMemory ); } writePropertiesToFile( properties, temporaryConfigFile ); return temporaryConfigFile; } public DatabaseTuningPropertyFileBuilder mappedMemory( int i ) { this.mappedMemory = String.valueOf( i ) + "M"; return this; } }
false
community_server_src_test_java_org_neo4j_server_configuration_DatabaseTuningPropertyFileBuilder.java
2,561
public class StatisticsCollectionEnabledDocIT extends ExclusiveServerTestBase { private CommunityNeoServer server; @After public void stopTheServer() { server.stop(); } @Test public void statisticsShouldBeDisabledByDefault() throws Exception { server = server() .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); create().resource( server.baseUri() ).get( ClientResponse.class ); StatisticRecord snapshot = server.statisticsCollector.createSnapshot(); assertThat( snapshot.getRequests(), is( 0L ) ); } @Test public void statisticsCouldBeEnabled() throws Exception { server = server().withProperty( WEBSERVER_ENABLE_STATISTICS_COLLECTION, "true" ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); create().resource( server.baseUri() ).get( ClientResponse.class ); StatisticRecord snapshot = server.statisticsCollector.createSnapshot(); assertThat( snapshot.getRequests(), greaterThan( 0L ) ); } }
false
community_server_src_test_java_org_neo4j_server_StatisticsCollectionEnabledDocIT.java
2,562
private static class ConfiguratorBuilder { private final Configurator configurator; public ConfiguratorBuilder( Configurator initialConfigurator ) { this.configurator = initialConfigurator; } public ConfiguratorBuilder atPort( int port ) { configurator.configuration().setProperty( Configurator.WEBSERVER_PORT_PROPERTY_KEY, port ); return this; } public ConfiguratorBuilder withStartupTimeout( int seconds ) { configurator.configuration().setProperty( Configurator.STARTUP_TIMEOUT, seconds ); return this; } public Configurator build() { return configurator; } }
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,563
{ @Override public void doWork() { deleteAllNodesAndRelationships( dbRule.getGraphDatabaseService() ); deleteAllIndexes( dbRule.getGraphDatabaseService() ); } private void deleteAllNodesAndRelationships( final GraphDatabaseService db ) { Iterable<Node> allNodes = GlobalGraphOperations.at(db).getAllNodes(); for ( Node n : allNodes ) { Iterable<Relationship> relationships = n.getRelationships(); for ( Relationship rel : relationships ) { rel.delete(); } if ( n.getId() != 0 ) { // Don't delete the reference node - tests depend on it // :-( n.delete(); } else { // Remove all state from the reference node instead for ( String key : n.getPropertyKeys() ) { n.removeProperty( key ); } } } } private void deleteAllIndexes( final GraphDatabaseService db ) { IndexManager indexManager = db.index(); for ( String indexName : indexManager.nodeIndexNames() ) { try { db.index().forNodes( indexName ).delete(); } catch ( UnsupportedOperationException e ) { // Encountered a read-only index. } } for ( String indexName : indexManager.relationshipIndexNames() ) { try { db.index().forRelationships( indexName ).delete(); } catch ( UnsupportedOperationException e ) { // Encountered a read-only index. } } for ( String k : indexManager.getNodeAutoIndexer().getAutoIndexedProperties() ) { indexManager.getNodeAutoIndexer().stopAutoIndexingProperty( k ); } indexManager.getNodeAutoIndexer().setEnabled( false ); for ( String k : indexManager.getRelationshipAutoIndexer().getAutoIndexedProperties() ) { indexManager.getRelationshipAutoIndexer().stopAutoIndexingProperty( k ); } indexManager.getRelationshipAutoIndexer().setEnabled( false ); } } ).execute();
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,564
{ @Override public void start() { timerStartSignal.get().run(); try { Thread.sleep( 1000 * 5 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } if ( preventMovingFurtherThanStartingModules ) { fail( "Should not get here" ); } } @Override public void stop() { } };
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,565
{ @Override public void run() { realTimer.startCountdown(); } } );
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,566
{ @Override public boolean wasTriggered() { return realTimer.wasTriggered(); } @Override public void stopCountdown() { realTimer.stopCountdown(); } @Override public void startCountdown() { timerStartSignal.set( new Runnable() { @Override public void run() { realTimer.startCountdown(); } } ); } @Override public long getTimeoutMillis() { return realTimer.getTimeoutMillis(); } @Override public State getState() { return realTimer.getState(); } };
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,567
{ @Override protected InterruptThreadTimer createInterruptStartupTimer() { /* Create an InterruptThreadTimer that won't start its count down until server modules have * started to load (and in the case of these tests wait long enough for the timer to trigger. * This makes it deterministic precisely where in the startup sequence the interrupt happens. * Whereas this is a bit too deterministic compared to the real world, this is a test that must * complete in the same way every time. Another test should verify that an interrupt happening * anywhere in the startup sequence still aborts the startup and cleans up properly. */ InterruptThreadTimer realTimer = super.createInterruptStartupTimer(); return timerThatStartsWhenModulesStartsLoading( realTimer ); } private InterruptThreadTimer timerThatStartsWhenModulesStartsLoading( final InterruptThreadTimer realTimer ) { return new InterruptThreadTimer() { @Override public boolean wasTriggered() { return realTimer.wasTriggered(); } @Override public void stopCountdown() { realTimer.stopCountdown(); } @Override public void startCountdown() { timerStartSignal.set( new Runnable() { @Override public void run() { realTimer.startCountdown(); } } ); } @Override public long getTimeoutMillis() { return realTimer.getTimeoutMillis(); } @Override public State getState() { return realTimer.getState(); } }; } @Override protected Iterable<ServerModule> createServerModules() { ServerModule slowModule = new ServerModule() { @Override public void start() { timerStartSignal.get().run(); try { Thread.sleep( 1000 * 5 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } if ( preventMovingFurtherThanStartingModules ) { fail( "Should not get here" ); } } @Override public void stop() { } }; return Arrays.asList( slowModule ); } };
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,568
{ @Override protected Iterable<ServerModule> createServerModules() { return Arrays.asList(); } };
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,569
public class StartupTimeoutDocIT { @Test public void shouldTimeoutIfStartupTakesLongerThanTimeout() throws IOException { // GIVEN Configurator configurator = buildProperties().withStartupTimeout( 1 ).atPort( 7480 ).build(); server = createSlowServer( configurator, true ); // WHEN try { server.start(); fail( "Should have been interrupted." ); } catch ( ServerStartupException e ) { // THEN assertThat( e.getMessage(), containsString( "Startup took longer than" ) ); } } @Test public void shouldNotFailIfStartupTakesLessTimeThanTimeout() throws IOException { Configurator configurator = buildProperties().withStartupTimeout( 100 ).atPort( 7480 ).build(); server = new CommunityNeoServer( configurator, DevNullLoggingService.DEV_NULL ) { @Override protected Iterable<ServerModule> createServerModules() { return Arrays.asList(); } }; // When try { server.start(); } catch ( ServerStartupException e ) { fail( "Should not have been interupted." ); } // Then InterruptThreadTimer timer = server.getDependencyResolver().resolveDependency( InterruptThreadTimer.class ); assertThat( timer.getState(), is( InterruptThreadTimer.State.IDLE ) ); } @Test public void shouldNotTimeOutIfTimeoutDisabled() throws IOException { Configurator configurator = buildProperties().withStartupTimeout( 0 ).atPort( 7480 ).build(); server = createSlowServer( configurator, false ); // When server.start(); // Then // No exceptions should have been thrown } private CommunityNeoServer createSlowServer( Configurator configurator, final boolean preventMovingFurtherThanStartingModules ) { final AtomicReference<Runnable> timerStartSignal = new AtomicReference<>(); CommunityNeoServer server = new CommunityNeoServer( configurator, DevNullLoggingService.DEV_NULL ) { @Override protected InterruptThreadTimer createInterruptStartupTimer() { /* Create an InterruptThreadTimer that won't start its count down until server modules have * started to load (and in the case of these tests wait long enough for the timer to trigger. * This makes it deterministic precisely where in the startup sequence the interrupt happens. * Whereas this is a bit too deterministic compared to the real world, this is a test that must * complete in the same way every time. Another test should verify that an interrupt happening * anywhere in the startup sequence still aborts the startup and cleans up properly. */ InterruptThreadTimer realTimer = super.createInterruptStartupTimer(); return timerThatStartsWhenModulesStartsLoading( realTimer ); } private InterruptThreadTimer timerThatStartsWhenModulesStartsLoading( final InterruptThreadTimer realTimer ) { return new InterruptThreadTimer() { @Override public boolean wasTriggered() { return realTimer.wasTriggered(); } @Override public void stopCountdown() { realTimer.stopCountdown(); } @Override public void startCountdown() { timerStartSignal.set( new Runnable() { @Override public void run() { realTimer.startCountdown(); } } ); } @Override public long getTimeoutMillis() { return realTimer.getTimeoutMillis(); } @Override public State getState() { return realTimer.getState(); } }; } @Override protected Iterable<ServerModule> createServerModules() { ServerModule slowModule = new ServerModule() { @Override public void start() { timerStartSignal.get().run(); try { Thread.sleep( 1000 * 5 ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } if ( preventMovingFurtherThanStartingModules ) { fail( "Should not get here" ); } } @Override public void stop() { } }; return Arrays.asList( slowModule ); } }; return server; } private ConfiguratorBuilder buildProperties() throws IOException { new File( test.directory().getAbsolutePath() + DIRSEP + "conf" ).mkdirs(); Properties databaseProperties = new Properties(); String databasePropertiesFileName = test.directory().getAbsolutePath() + DIRSEP + "conf" + DIRSEP + "neo4j.properties"; databaseProperties.store( new FileWriter( databasePropertiesFileName ), null ); Properties serverProperties = new Properties(); String serverPropertiesFilename = test.directory().getAbsolutePath() + DIRSEP + "conf" + DIRSEP + "neo4j-server.properties"; serverProperties.setProperty( Configurator.DATABASE_LOCATION_PROPERTY_KEY, test.directory().getAbsolutePath() + DIRSEP + "data" + DIRSEP + "graph.db" ); serverProperties.setProperty( Configurator.DB_TUNING_PROPERTY_FILE_KEY, databasePropertiesFileName ); serverProperties.setProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY, serverPropertiesFilename ); serverProperties.store( new FileWriter( serverPropertiesFilename ), null ); return new ConfiguratorBuilder( new PropertyFileConfigurator( new File( serverPropertiesFilename ) ) ); } public @Rule ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule(); TargetDirectory target = TargetDirectory.forTest( StartupTimeoutDocIT.class ); private static final String DIRSEP = File.separator; @Rule public TargetDirectory.TestDirectory test = target.testDirectory(); public CommunityNeoServer server; public @Rule TestName testName = new TestName(); @After public void stopServer() { if ( server != null ) { server.stop(); server = null; } } @Before public void printTestName() { // MP: Historically this test class has provided pretty flaky tests, mostly only reproducible on CI systems. // to be able to know in which order tests executed might give hints about problems (while we're debugging // the flakiness). System.out.println( "=== Executing: " + StartupTimeoutDocIT.class.getSimpleName() + "#" + testName.getMethodName() ); } private void clearAll() { new Transactor( dbRule.getGraphDatabaseService(), new UnitOfWork() { @Override public void doWork() { deleteAllNodesAndRelationships( dbRule.getGraphDatabaseService() ); deleteAllIndexes( dbRule.getGraphDatabaseService() ); } private void deleteAllNodesAndRelationships( final GraphDatabaseService db ) { Iterable<Node> allNodes = GlobalGraphOperations.at(db).getAllNodes(); for ( Node n : allNodes ) { Iterable<Relationship> relationships = n.getRelationships(); for ( Relationship rel : relationships ) { rel.delete(); } if ( n.getId() != 0 ) { // Don't delete the reference node - tests depend on it // :-( n.delete(); } else { // Remove all state from the reference node instead for ( String key : n.getPropertyKeys() ) { n.removeProperty( key ); } } } } private void deleteAllIndexes( final GraphDatabaseService db ) { IndexManager indexManager = db.index(); for ( String indexName : indexManager.nodeIndexNames() ) { try { db.index().forNodes( indexName ).delete(); } catch ( UnsupportedOperationException e ) { // Encountered a read-only index. } } for ( String indexName : indexManager.relationshipIndexNames() ) { try { db.index().forRelationships( indexName ).delete(); } catch ( UnsupportedOperationException e ) { // Encountered a read-only index. } } for ( String k : indexManager.getNodeAutoIndexer().getAutoIndexedProperties() ) { indexManager.getNodeAutoIndexer().stopAutoIndexingProperty( k ); } indexManager.getNodeAutoIndexer().setEnabled( false ); for ( String k : indexManager.getRelationshipAutoIndexer().getAutoIndexedProperties() ) { indexManager.getRelationshipAutoIndexer().stopAutoIndexingProperty( k ); } indexManager.getRelationshipAutoIndexer().setEnabled( false ); } } ).execute(); } /** * Produces more readable and understandable test code where this builder is used compared to raw Configurator. */ private static class ConfiguratorBuilder { private final Configurator configurator; public ConfiguratorBuilder( Configurator initialConfigurator ) { this.configurator = initialConfigurator; } public ConfiguratorBuilder atPort( int port ) { configurator.configuration().setProperty( Configurator.WEBSERVER_PORT_PROPERTY_KEY, port ); return this; } public ConfiguratorBuilder withStartupTimeout( int seconds ) { configurator.configuration().setProperty( Configurator.STARTUP_TIMEOUT, seconds ); return this; } public Configurator build() { return configurator; } } }
false
community_server_src_test_java_org_neo4j_server_StartupTimeoutDocIT.java
2,570
{ @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( databaseProperties ).newGraphDatabase(); } };
false
community_server_src_test_java_org_neo4j_server_ServerTestUtils.java
2,571
{ @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new org.neo4j.graphdb.factory.GraphDatabaseFactory().newEmbeddedDatabaseBuilder( databaseStoreDirectory ).setConfig( databaseProperties ).newGraphDatabase(); } };
false
community_server_src_test_java_org_neo4j_server_ServerTestUtils.java
2,572
public class ServerTestUtils { public static final GraphDatabaseFactory EMBEDDED_GRAPH_DATABASE_FACTORY = new GraphDatabaseFactory() { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new org.neo4j.graphdb.factory.GraphDatabaseFactory().newEmbeddedDatabaseBuilder( databaseStoreDirectory ).setConfig( databaseProperties ).newGraphDatabase(); } }; public static final GraphDatabaseFactory EPHEMERAL_GRAPH_DATABASE_FACTORY = new GraphDatabaseFactory() { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( databaseProperties ).newGraphDatabase(); } }; public static File createTempDir() throws IOException { File d = File.createTempFile( "neo4j-test", "dir" ); if ( !d.delete() ) { throw new RuntimeException( "temp config directory pre-delete failed" ); } if ( !d.mkdirs() ) { throw new RuntimeException( "temp config directory not created" ); } d.deleteOnExit(); return d; } public static File createTempPropertyFile() throws IOException { File file = File.createTempFile( "neo4j", "properties" ); file.delete(); return file; } public static void writePropertiesToFile( String outerPropertyName, Map<String, String> properties, File propertyFile ) { writePropertyToFile( outerPropertyName, asOneLine( properties ), propertyFile ); } public static void writePropertiesToFile( Map<String, String> properties, File propertyFile ) { Properties props = loadProperties( propertyFile ); for ( Map.Entry<String, String> entry : properties.entrySet() ) { props.setProperty( entry.getKey(), entry.getValue() ); } storeProperties( propertyFile, props ); } public static String asOneLine( Map<String, String> properties ) { StringBuilder builder = new StringBuilder(); for ( Map.Entry<String, String> property : properties.entrySet() ) { builder.append( ( builder.length() > 0 ? "," : "" ) ); builder.append( property.getKey() + "=" + property.getValue() ); } return builder.toString(); } public static void writePropertyToFile( String name, String value, File propertyFile ) { Properties properties = loadProperties( propertyFile ); properties.setProperty( name, value ); storeProperties( propertyFile, properties ); } private static void storeProperties( File propertyFile, Properties properties ) { OutputStream out = null; try { out = new FileOutputStream( propertyFile ); properties.store( out, "" ); } catch ( IOException e ) { throw new RuntimeException( e ); } finally { safeClose( out ); } } private static Properties loadProperties( File propertyFile ) { Properties properties = new Properties(); if ( propertyFile.exists() ) { InputStream in = null; try { in = new FileInputStream( propertyFile ); properties.load( in ); } catch ( IOException e ) { throw new RuntimeException( e ); } finally { safeClose( in ); } } return properties; } private static void safeClose( Closeable closeable ) { if ( closeable != null ) { try { closeable.close(); } catch ( IOException e ) { e.printStackTrace(); } } } public static File createTempPropertyFile( File parentDir ) throws IOException { File file = new File( parentDir, "test-" + new Random().nextInt() + ".properties" ); file.deleteOnExit(); return file; } }
false
community_server_src_test_java_org_neo4j_server_ServerTestUtils.java
2,573
public class ServerStartupException extends RuntimeException { /** * Creates a new exception with a message and an error code. * * @param message sensible explanation about the exception, excluding the * error code value, which will be automatically appended * @param errorCode unique identifying number for the error */ public ServerStartupException( String message, Integer errorCode ) { super( message + " Error code: " + errorCode.toString() ); } public ServerStartupException( String message, Throwable t ) { super( message, t); } public ServerStartupException( String message ) { super( message ); } }
false
community_server_src_main_java_org_neo4j_server_ServerStartupException.java
2,574
public class ServerConfigDocIT extends ExclusiveServerTestBase { private CommunityNeoServer server; @After public void stopTheServer() { server.stop(); } @Test public void shouldPickUpPortFromConfig() throws Exception { final int NON_DEFAULT_PORT = 4321; server = server().onPort( NON_DEFAULT_PORT ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); assertEquals( NON_DEFAULT_PORT, server.getWebServerPort() ); JaxRsResponse response = new RestRequest( server.baseUri() ).get(); assertThat( response.getStatus(), is( 200 ) ); response.close(); } @Test public void shouldPickupRelativeUrisForWebAdminAndWebAdminRest() throws IOException { String webAdminDataUri = "/a/different/webadmin/data/uri/"; String webAdminManagementUri = "/a/different/webadmin/management/uri/"; server = server().withRelativeWebDataAdminUriPath( webAdminDataUri ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .withRelativeWebAdminUriPath( webAdminManagementUri ) .build(); server.start(); JaxRsResponse response = new RestRequest().get( "http://localhost:7474" + webAdminDataUri, MediaType.TEXT_HTML_TYPE ); assertEquals( 200, response.getStatus() ); response = new RestRequest().get( "http://localhost:7474" + webAdminManagementUri ); assertEquals( 200, response.getStatus() ); response.close(); } @Test public void shouldGenerateWADLWhenExplicitlyEnabledInConfig() throws IOException { server = server().withProperty( Configurator.WADL_ENABLED, "true" ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); JaxRsResponse response = new RestRequest().get( "http://localhost:7474/application.wadl", MediaType.WILDCARD_TYPE ); assertEquals( 200, response.getStatus() ); assertEquals( "application/vnd.sun.wadl+xml", response.getHeaders().get( "Content-Type" ).iterator().next() ); assertThat( response.getEntity(), containsString( "<application xmlns=\"http://wadl.dev.java" + ".net/2009/02\">" ) ); } @Test public void shouldNotGenerateWADLWhenNotExplicitlyEnabledInConfig() throws IOException { server = server() .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); JaxRsResponse response = new RestRequest().get( "http://localhost:7474/application.wadl", MediaType.WILDCARD_TYPE ); assertEquals( 404, response.getStatus() ); } @Test public void shouldNotGenerateWADLWhenExplicitlyDisabledInConfig() throws IOException { server = server().withProperty( Configurator.WADL_ENABLED, "false" ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); JaxRsResponse response = new RestRequest().get( "http://localhost:7474/application.wadl", MediaType.WILDCARD_TYPE ); assertEquals( 404, response.getStatus() ); } @Test public void shouldHaveSandboxingEnabledByDefault() throws Exception { // Given server = server() .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); server.start(); String node = POST( server.baseUri().toASCIIString() + "db/data/node" ).location(); // When JaxRsResponse response = new RestRequest().post( node + "/traverse/node", "{\n" + " \"order\" : \"breadth_first\",\n" + " \"return_filter\" : {\n" + " \"body\" : \"position.getClass().getClassLoader()\",\n" + " \"language\" : \"javascript\"\n" + " },\n" + " \"prune_evaluator\" : {\n" + " \"body\" : \"position.getClass().getClassLoader()\",\n" + " \"language\" : \"javascript\"\n" + " },\n" + " \"uniqueness\" : \"node_global\",\n" + " \"relationships\" : [ {\n" + " \"direction\" : \"all\",\n" + " \"type\" : \"knows\"\n" + " }, {\n" + " \"direction\" : \"all\",\n" + " \"type\" : \"loves\"\n" + " } ],\n" + " \"max_depth\" : 3\n" + "}", MediaType.APPLICATION_JSON_TYPE ); // Then assertEquals( 400, response.getStatus() ); } /* * We can't actually test that disabling sandboxing works, because of the set-once global nature of Rhino * security. Instead, we test here that changing it triggers the expected exception, letting us know that * the code that *would* have set it to disabled realizes it has already been set to sandboxed. * * This at least lets us know that the configuration attribute gets picked up and used. */ @Test(expected = RuntimeException.class) public void shouldBeAbleToDisableSandboxing() throws Exception { // NOTE: This has to be initialized to sandboxed, because it can only be initialized once per JVM session, // and all other tests depend on it being sandboxed. GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED ); server = server().withProperty( Configurator.SCRIPT_SANDBOXING_ENABLED_KEY, "false" ) .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .build(); // When server.start(); } }
false
community_server_src_test_java_org_neo4j_server_ServerConfigDocIT.java
2,575
public class RoundRobinJobScheduler implements JobScheduler { private final List<ScheduledJob> scheduledJobs = new LinkedList<ScheduledJob>(); private final Logging logging; public RoundRobinJobScheduler( Logging logging ) { this.logging = logging; } @Override public void scheduleAtFixedRate( Runnable job, String jobName, long delay, long period ) { ScheduledJob scheduledJob = new ScheduledJob( job, jobName, delay, period, logging ); scheduledJobs.add( scheduledJob ); } public void stopJobs() { for ( ScheduledJob job : scheduledJobs ) { job.cancel(); } } }
false
community_server_src_main_java_org_neo4j_server_RoundRobinJobScheduler.java
2,576
public class PreflightTasksDocIT extends ExclusiveServerTestBase { private NeoServer server; @Test( expected = ServerStartupException.class ) public void shouldExitWhenFailedStartupHealthCheck() throws Throwable { server = CommunityServerBuilder.server() .usingDatabaseDir( folder.getRoot().getAbsolutePath() ) .withFailingPreflightTasks() .build(); server.start(); } }
false
community_server_src_test_java_org_neo4j_server_PreflightTasksDocIT.java
2,577
public class NeoServerStartupLoggingDocIT extends ExclusiveServerTestBase { private static Logging logging; private static NeoServer server; @BeforeClass public static void setupServer() throws IOException { logging = new BufferingLogging(); server = ServerHelper.createNonPersistentServer( logging ); } @Before public void cleanTheDatabase() { ServerHelper.cleanTheDatabase( server ); } @AfterClass public static void stopServer() { server.stop(); } @Test public void shouldLogStartup() throws Exception { // Check the logs assertThat( logging.toString().length(), is( greaterThan( 0 ) ) ); // Check the server is alive Client nonRedirectingClient = Client.create(); nonRedirectingClient.setFollowRedirects( false ); final JaxRsResponse response = new RestRequest(server.baseUri(), nonRedirectingClient).get(); assertThat( response.getStatus(), is( greaterThan( 199 ) ) ); } }
false
community_server_src_test_java_org_neo4j_server_NeoServerStartupLoggingDocIT.java
2,578
public class NeoServerShutdownLoggingDocIT extends ExclusiveServerTestBase { private Logging logging; private NeoServer server; @Before public void setupServer() throws IOException { logging = new BufferingLogging(); server = ServerHelper.createPersistentServer(folder.getRoot(), logging); ServerHelper.cleanTheDatabase( server ); } @After public void shutdownTheServer() { if ( server != null ) { server.stop(); } } @Test public void shouldLogShutdown() throws Exception { server.stop(); assertThat( logging.toString(), containsString( "Successfully shutdown database." ) ); } }
false
community_server_src_test_java_org_neo4j_server_NeoServerShutdownLoggingDocIT.java
2,579
@Provider public class NeoServerProvider extends InjectableProvider<NeoServer> { public NeoServer neoServer; public NeoServerProvider( NeoServer db ) { super( NeoServer.class ); this.neoServer = db; } @Override public NeoServer getValue( HttpContext httpContext ) { return neoServer; } }
false
community_server_src_main_java_org_neo4j_server_NeoServerProvider.java
2,580
public class TestInterruptThreadTimer { @Test public void shouldInterruptIfTimeoutIsReached() { try { InterruptThreadTimer timer = InterruptThreadTimer.createTimer(100, Thread.currentThread()); timer.startCountdown(); Thread.sleep(3000); fail("Should have been interrupted."); } catch(InterruptedException e) { // ok } } @Test public void shouldNotInterruptIfTimeoutIsNotReached() { try { InterruptThreadTimer timer = InterruptThreadTimer.createTimer(1000 * 10, Thread.currentThread()); timer.startCountdown(); Thread.sleep(1); timer.stopCountdown(); } catch(InterruptedException e) { fail("Should not have been interrupted."); } } }
false
community_server_src_test_java_org_neo4j_server_TestInterruptThreadTimer.java
2,581
public class TransactionTimeoutDocIT extends ExclusiveServerTestBase { private CommunityNeoServer server; @After public void stopTheServer() { server.stop(); } @Test public void shouldHonorReallyLowSessionTimeout() throws Exception { // Given server = server().withProperty( TRANSACTION_TIMEOUT, "1" ).build(); server.start(); String tx = HTTP.POST( txURI(), asList( map( "statement", "CREATE n" ) ) ).location(); // When Thread.sleep( 1000 * 5 ); Map<String, Object> response = HTTP.POST( tx + "/commit" ).content(); // Then @SuppressWarnings("unchecked") List<Map<String, Object>> errors = (List<Map<String, Object>>) response.get( "errors" ); assertThat( (String) errors.get( 0 ).get( "code" ), equalTo( UnknownId.code().serialize() ) ); } private String txURI() { return server.baseUri().toString() + "db/data/transaction"; } }
false
community_server_src_test_java_org_neo4j_server_TransactionTimeoutDocIT.java
2,582
public class WebTestUtils { private static boolean available( int port ) { if ( port < 1111 || port > 9999 ) { throw new IllegalArgumentException( "Invalid start port: " + port ); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket( port ); ss.setReuseAddress( true ); ds = new DatagramSocket( port ); ds.setReuseAddress( true ); return true; } catch ( IOException e ) { } finally { if ( ds != null ) { ds.close(); } if ( ss != null ) { try { ss.close(); } catch ( IOException e ) { throw new RuntimeException( e ); } } } return false; } public static int nextAvailablePortNumber() { int nonPriveledgedPortNumber = 1111; while ( !available( nonPriveledgedPortNumber ) ) { nonPriveledgedPortNumber++; } return nonPriveledgedPortNumber; } }
false
community_server_src_test_java_org_neo4j_server_WebTestUtils.java
2,583
{ @Override public void run() { server.stop(); server.start(); } };
false
advanced_server-advanced_src_main_java_org_neo4j_server_advanced_jmx_ServerManagement.java
2,584
public class ConfiguratorTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void shouldProvideAConfiguration() throws IOException { File configFile = PropertyFileBuilder.builder( folder.getRoot() ) .build(); Configuration config = new PropertyFileConfigurator( configFile ).configuration(); assertNotNull( config ); } @Test public void shouldUseSpecifiedConfigFile() throws Exception { File configFile = PropertyFileBuilder.builder( folder.getRoot() ) .withNameValue( "foo", "bar" ) .build(); Configuration testConf = new PropertyFileConfigurator( configFile ).configuration(); final String EXPECTED_VALUE = "bar"; assertEquals( EXPECTED_VALUE, testConf.getString( "foo" ) ); } @Test public void shouldAcceptDuplicateKeysWithSameValue() throws IOException { File configFile = PropertyFileBuilder.builder( folder.getRoot() ) .withNameValue( "foo", "bar" ) .withNameValue( "foo", "bar" ) .build(); Configurator configurator = new PropertyFileConfigurator( configFile ); Configuration testConf = configurator.configuration(); assertNotNull( testConf ); final String EXPECTED_VALUE = "bar"; assertEquals( EXPECTED_VALUE, testConf.getString( "foo" ) ); } @Test public void shouldSupportProvidingDatabaseTuningParametersSeparately() throws IOException { File databaseTuningPropertyFile = DatabaseTuningPropertyFileBuilder.builder( folder.getRoot() ) .build(); File propertyFileWithDbTuningProperty = PropertyFileBuilder.builder( folder.getRoot() ) .withDbTuningPropertyFile( databaseTuningPropertyFile ) .build(); Configurator configurator = new PropertyFileConfigurator( propertyFileWithDbTuningProperty ); Map<String, String> databaseTuningProperties = configurator.getDatabaseTuningProperties(); assertNotNull( databaseTuningProperties ); assertEquals( 5, databaseTuningProperties.size() ); } @Test public void shouldFindThirdPartyJaxRsPackages() throws IOException { File file = ServerTestUtils.createTempPropertyFile( folder.getRoot() ); FileWriter fstream = new FileWriter( file, true ); BufferedWriter out = new BufferedWriter( fstream ); out.write( Configurator.THIRD_PARTY_PACKAGES_KEY ); out.write( "=" ); out.write( "com.foo.bar=\"mount/point/foo\"," ); out.write( "com.foo.baz=\"/bar\"," ); out.write( "com.foo.foobarbaz=\"/\"" ); out.write( System.getProperty( "line.separator" ) ); out.close(); Configurator configurator = new PropertyFileConfigurator( file ); List<ThirdPartyJaxRsPackage> thirdpartyJaxRsPackages = configurator.getThirdpartyJaxRsPackages(); assertNotNull( thirdpartyJaxRsPackages ); assertEquals( 3, thirdpartyJaxRsPackages.size() ); } }
false
community_server_src_test_java_org_neo4j_server_configuration_ConfiguratorTest.java
2,585
public static abstract class Adapter implements Configurator { @Override public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsClasses() { return getThirdpartyJaxRsPackages(); } @Override public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsPackages() { return emptyList(); } @Override public Map<String, String> getDatabaseTuningProperties() { return emptyMap(); } @Override public Configuration configuration() { return new MapConfiguration( emptyMap() ); } }
false
community_server_src_main_java_org_neo4j_server_configuration_Configurator.java
2,586
{ };
false
community_server_src_main_java_org_neo4j_server_configuration_Configurator.java
2,587
{ final Iterator<?> keys = config.getKeys(); @Override protected String fetchNextOrNull() { while ( keys.hasNext() ) { Object key = keys.next(); if ( key instanceof String ) { return key + " = " + config.getProperty( (String) key ); } } return null; } }, true );
false
community_server_src_main_java_org_neo4j_server_configuration_Configurator.java
2,588
{ @Override public void dumpDiagnostics( final Configurator source, DiagnosticsPhase phase, StringLogger log ) { if ( phase.isInitialization() || phase.isExplicitlyRequested() ) { final Configuration config = source.configuration(); log.logLongMessage( "Server configuration:", new PrefetchingIterator<String>() { final Iterator<?> keys = config.getKeys(); @Override protected String fetchNextOrNull() { while ( keys.hasNext() ) { Object key = keys.next(); if ( key instanceof String ) { return key + " = " + config.getProperty( (String) key ); } } return null; } }, true ); } } @Override public String toString() { return Configurator.class.getName(); } };
false
community_server_src_main_java_org_neo4j_server_configuration_Configurator.java
2,589
List<String> DEFAULT_MANAGEMENT_CONSOLE_ENGINES = new ArrayList<String>(){ private static final long serialVersionUID = 6621747998288594121L; { add(new ShellSessionCreator().name()); }};
false
community_server_src_main_java_org_neo4j_server_configuration_Configurator.java
2,590
@Provider public class ConfigurationProvider extends InjectableProvider<Configuration> { private Configuration config; public ConfigurationProvider( Configuration config ) { super( Configuration.class ); this.config = config; } @Override public Configuration getValue( HttpContext httpContext ) { return config; } }
false
community_server_src_main_java_org_neo4j_server_configuration_ConfigurationProvider.java
2,591
public class JMXManagementModule implements ServerModule { private final NeoServer server; public JMXManagementModule( NeoServer server ) { this.server = server; } @Override public void start() { try { ServerManagement serverManagement = new ServerManagement( server ); MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); beanServer.registerMBean( serverManagement, createObjectName() ); } catch ( Exception e ) { throw new RuntimeException( "Unable to initialize jmx management, see nested exception.", e ); } } @Override public void stop() { try { MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); beanServer.unregisterMBean( createObjectName() ); } catch ( InstanceNotFoundException e ) { // ok } catch ( Exception e ) { throw new RuntimeException( "Unable to shut down jmx management, see nested exception.", e ); } } private ObjectName createObjectName() throws MalformedObjectNameException { return new ObjectName( "org.neo4j.ServerManagement", "restartServer", "lifecycle" ); } }
false
advanced_server-advanced_src_main_java_org_neo4j_server_advanced_modules_JMXManagementModule.java
2,592
public final class ServerManagement implements ServerManagementMBean { private final NeoServer server; public ServerManagement(NeoServer bs) { this.server = bs; } @Override public synchronized void restartServer() { Thread thread = new Thread( "restart thread" ) { @Override public void run() { server.stop(); server.start(); } }; thread.setDaemon( false ); thread.start(); System.out.println("restarting server"); try { thread.join(); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } }
false
advanced_server-advanced_src_main_java_org_neo4j_server_advanced_jmx_ServerManagement.java
2,593
public class WrappingNeoServer extends CommunityNeoServer { private final GraphDatabaseAPI db; public WrappingNeoServer( GraphDatabaseAPI db ) { this( db, new ServerConfigurator( db ) ); } public WrappingNeoServer( GraphDatabaseAPI db, Configurator configurator ) { super( db.getDependencyResolver().resolveDependency( Logging.class ) ); this.db = db; this.configurator = configurator; init(); } @Override protected Database createDatabase() { return new WrappedDatabase( (AbstractGraphDatabase)db, configurator ); } @Override protected PreFlightTasks createPreflightTasks() { return new PreFlightTasks( logging ); } }
false
community_server_src_main_java_org_neo4j_server_WrappingNeoServer.java
2,594
private class TestAdvancedNeoServer extends AdvancedNeoServer { private final File configFile; public TestAdvancedNeoServer( Configurator propertyFileConfigurator, File configFile, Logging logging ) { super( propertyFileConfigurator, logging ); this.configFile = configFile; } @Override protected PreFlightTasks createPreflightTasks() { return preflightTasks; } @Override protected Database createDatabase() { return persistent ? super.createDatabase() : new EphemeralDatabase( configurator ); } @Override protected DatabaseActions createDatabaseActions() { return createDatabaseActionsObject( database, configurator ); } @Override public void stop() { super.stop(); configFile.delete(); } }
false
advanced_server-advanced_src_test_java_org_neo4j_server_advanced_helpers_AdvancedServerBuilder.java
2,595
public class AdvancedServerBuilder extends CommunityServerBuilder { public AdvancedServerBuilder( Logging logging ) { super( given( logging ) ); } public static AdvancedServerBuilder server( Logging logging ) { return new AdvancedServerBuilder( logging ); } public static AdvancedServerBuilder server() { return new AdvancedServerBuilder( null ); } @Override public AdvancedNeoServer build() throws IOException { return (AdvancedNeoServer) super.build(); } @Override public AdvancedNeoServer build( File configFile, Configurator configurator, Logging logging ) { return new TestAdvancedNeoServer( configurator, configFile, logging ); } private class TestAdvancedNeoServer extends AdvancedNeoServer { private final File configFile; public TestAdvancedNeoServer( Configurator propertyFileConfigurator, File configFile, Logging logging ) { super( propertyFileConfigurator, logging ); this.configFile = configFile; } @Override protected PreFlightTasks createPreflightTasks() { return preflightTasks; } @Override protected Database createDatabase() { return persistent ? super.createDatabase() : new EphemeralDatabase( configurator ); } @Override protected DatabaseActions createDatabaseActions() { return createDatabaseActionsObject( database, configurator ); } @Override public void stop() { super.stop(); configFile.delete(); } } }
false
advanced_server-advanced_src_test_java_org_neo4j_server_advanced_helpers_AdvancedServerBuilder.java
2,596
public class BootstrapperTest { @Test public void shouldBeAbleToRestartServer() throws Exception { TargetDirectory target = TargetDirectory.forTest( getClass() ); String dbDir1 = target.cleanDirectory( "db1" ).getAbsolutePath(); Configurator config = new PropertyFileConfigurator( Validator.NO_VALIDATION, AdvancedServerBuilder .server() .usingDatabaseDir( dbDir1 ) .createPropertiesFiles(), ConsoleLogger.DEV_NULL ); // TODO: This needs to be here because of a startuphealthcheck // that requires this system property. Look into moving // config file check into bootstrapper to avoid this. File irrelevant = target.file( "irrelevant" ); irrelevant.createNewFile(); config.configuration().setProperty( "org.neo4j.server.properties", irrelevant.getAbsolutePath()); AdvancedNeoServer server = new AdvancedNeoServer( config, new SingleLoggingService( StringLogger.SYSTEM ) ); server.start( ); assertNotNull( server.getDatabase().getGraph() ); // Change the database location String dbDir2 = target.cleanDirectory( "db2" ).getAbsolutePath(); Configuration conf = config.configuration(); conf.setProperty( Configurator.DATABASE_LOCATION_PROPERTY_KEY, dbDir2 ); ServerManagement bean = new ServerManagement( server ); bean.restartServer(); } }
false
advanced_server-advanced_src_test_java_org_neo4j_server_advanced_BootstrapperTest.java
2,597
public class AdvancedNeoServer extends CommunityNeoServer { protected AdvancedNeoServer( Logging logging ) { super( logging ); } public AdvancedNeoServer( Configurator configurator, Logging logging ) { super( logging ); this.configurator = configurator; init(); } @Override @SuppressWarnings("unchecked") protected Iterable<ServerModule> createServerModules() { return Iterables.mix(Arrays.asList( (ServerModule)new JMXManagementModule(this)), super.createServerModules()); } }
false
advanced_server-advanced_src_main_java_org_neo4j_server_advanced_AdvancedNeoServer.java
2,598
public class AdvancedBootstrapperTest { @Test public void bootstrapperLoadsAdvancedServerBootstrapper() throws Exception { assertThat( Bootstrapper.loadMostDerivedBootstrapper(), is( instanceOf( AdvancedBootstrapper.class ) ) ); } }
false
advanced_server-advanced_src_test_java_org_neo4j_server_advanced_AdvancedBootstrapperTest.java
2,599
public class AdvancedBootstrapper extends CommunityBootstrapper { @Override protected NeoServer createNeoServer() { return new AdvancedNeoServer( configurator, logging ); } }
false
advanced_server-advanced_src_main_java_org_neo4j_server_advanced_AdvancedBootstrapper.java