@Test public void shouldConfigureProgrammatically() { Configuration.Builder builder = new Configuration.Builder(); builder.autoIndex("assert"); builder.generatedIndexesOutputDir("dir"); builder.generatedIndexesOutputFilename("filename"); builder.credentials("fred", "flintstone"); builder.uri("http://localhost:8080"); builder.connectionPoolSize(200); builder.encryptionLevel("REQUIRED"); builder.trustStrategy("TRUST_SIGNED_CERTIFICATES"); builder.trustCertFile("/tmp/cert"); builder.connectionLivenessCheckTimeout(1000); Configuration configuration = builder.build(); assertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.ASSERT); assertThat(configuration.getDumpDir()).isEqualTo("dir"); assertThat(configuration.getDumpFilename()).isEqualTo("filename"); assertThat(configuration.getDriverClassName()).isEqualTo("org.neo4j.ogm.drivers.http.driver.HttpDriver"); assertThat(configuration.getCredentials().credentials().toString()).isEqualTo("ZnJlZDpmbGludHN0b25l"); assertThat(configuration.getURI()).isEqualTo("http://localhost:8080"); assertThat(configuration.getConnectionPoolSize()).isEqualTo(200); assertThat(configuration.getEncryptionLevel()).isEqualTo("REQUIRED"); assertThat(configuration.getTrustStrategy()).isEqualTo("TRUST_SIGNED_CERTIFICATES"); assertThat(configuration.getTrustCertFile()).isEqualTo("/tmp/cert"); assertThat(configuration.getConnectionLivenessCheckTimeout().intValue()).isEqualTo(1000); }
Configuration configuration = new Configuration.Builder().uri("https://neo4j:password@localhost:7473") .trustStrategy("ACCEPT_UNSIGNED").build();
@Test public void impermanentInstancesShouldNotShareTheSameDatabase() { Configuration configuration = new Configuration.Builder().build(); try (EmbeddedDriver driver1 = new EmbeddedDriver(); EmbeddedDriver driver2 = new EmbeddedDriver() ) { driver1.configure(configuration); driver2.configure(configuration); GraphDatabaseService db1 = driver1.unwrap(GraphDatabaseService.class); GraphDatabaseService db2 = driver2.unwrap(GraphDatabaseService.class); try (Transaction tx = db1.beginTx()) { db1.execute("CREATE (n: Node {name: 'node'})"); tx.success(); } try (Transaction tx1 = db1.beginTx(); Transaction tx2 = db2.beginTx()) { Result r1 = db1.execute("MATCH (n) RETURN n"); Result r2 = db2.execute("MATCH (n) RETURN n"); assertThat(r1.hasNext()).isTrue(); assertThat(r2.hasNext()).isFalse(); tx1.success(); tx2.success(); } } catch (Exception e) { fail("Should not have thrown exception"); } }
@Test public void shouldBeAbleToHaveMultipleInstances() { Configuration configuration = new Configuration.Builder().build(); try ( EmbeddedDriver driver1 = new EmbeddedDriver(); EmbeddedDriver driver2 = new EmbeddedDriver()) { driver1.configure(configuration); driver2.configure(configuration); GraphDatabaseService service1 = driver1.unwrap(GraphDatabaseService.class); GraphDatabaseService service2 = driver2.unwrap(GraphDatabaseService.class); assertThat(service1).isNotNull(); assertThat(service2).isNotNull(); // instances should be different assertThat(service1 == service2).isFalse(); // underlying file stores should be different assertThat( service1.toString().equals(service2.toString())) .isFalse(); } }
private Neo4jTransactionManager getNeo4jTransactionManager() { if (neo4jTransactionManager == null) { synchronized (this) { if (neo4jTransactionManager == null) { Builder configBuilder = new Builder() .uri(config.getUri()) .credentials(config.getLogin(), config.getPassword()); if (config.getConnectionPoolSize() > 0) { configBuilder.connectionPoolSize(config.getConnectionPoolSize()); } SessionFactory sessionFactory = new SessionFactory(configBuilder.build(), "org.openkilda.model"); sessionFactory.metaData().registerConversionCallback( new SimpleConversionCallback("org.openkilda.persistence.converters")); neo4jTransactionManager = new Neo4jTransactionManager(sessionFactory); } } } return neo4jTransactionManager; } }
@Test public void indexesShouldBeCreatedForLoadableClassesInHierarchy() { final IndexDescription[] expectedIndexes = new IndexDescription[] { new IndexDescription("DefaultUser", "id"), new IndexDescription("Admin", "id"), new IndexDescription("ChildA", "uuid"), new IndexDescription("ChildB", "uuid"), new IndexDescription("ChildC", "uuid"), new IndexDescription("LabeledEntity", "uuid"), new IndexDescription("EntityWithImplicitPlusAdditionalLabels", "id") }; sessionFactory.runAutoIndexManager(getBaseConfiguration().autoIndex(AutoIndexMode.UPDATE.name()).build()); GraphDatabaseService service = getGraphDatabaseService(); try (Transaction tx = service.beginTx()) { IndexDescription[] indexes = StreamSupport.stream(service.schema().getIndexes().spliterator(), false) .map(IndexDescription::new).toArray(IndexDescription[]::new); assertThat(indexes).containsExactlyInAnyOrder(expectedIndexes); tx.success(); } }
/** * @see issue #35 */ @Test public void testInvalidCredentials() { session = new SessionFactory(getBaseConfiguration().credentials("neo4j", "invalid_password").build(), "dummy") .openSession(); try (Transaction tx = session.beginTransaction()) { fail("Driver should not have authenticated"); } catch (Exception rpe) { Throwable cause = rpe.getCause(); while (!(cause instanceof HttpResponseException)) { cause = cause.getCause(); } assertThat(cause.getMessage()).isEqualTo("Invalid username or password."); } } }
@Test public void abstractDriverShouldLoadCypherModificationsInCorrectOrder() { Thread currentThread = Thread.currentThread(); ClassLoader originalClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(new TestServiceLoaderClassLoader(originalClassLoader)); Configuration driverConfiguration = new Configuration.Builder() .withCustomProperty("config1", 6) .withCustomProperty("config2", 9) .build(); Driver driver = new TestDriver(); driver.configure(driverConfiguration); try { Function<String, String> cypherModification = driver.getCypherModification(); assertThat(cypherModification.apply("What do you get if you multiply six by nine?")) .isEqualTo("42"); } finally { currentThread.setContextClassLoader(originalClassLoader); } }
@Test public void translatesServiceUnavailabeException() { try (ServerControls serverControls = TestServerBuilders.newInProcessBuilder().newServer()) { BoltDriver driver = new BoltDriver(); Configuration ogmConfiguration = new Configuration.Builder().uri(serverControls.boltURI().toString()) .verifyConnection(true).build(); driver.configure(ogmConfiguration); SessionFactory sessionFactory = new SessionFactory(driver, DOMAIN_PACKAGE); Session session = sessionFactory.openSession(); serverControls.close(); assertThatExceptionOfType(ConnectionException.class).isThrownBy(() -> { session.loadAll(ConstraintedNode.class); }).withCauseInstanceOf(ServiceUnavailableException.class); } } }
@Test public void shouldInitialiseDriverAfterServerComesOnline() { TestServer testServer = new TestServer(true, true, 5); String uri = testServer.getUri(); testServer.shutdown(); Configuration configuration = configBuilder .uri(uri) .build(); SessionFactory sessionFactory = new SessionFactory(configuration, User.class.getPackage().getName()); testServer = new TestServer(false, true, 5, testServer.getPort()); Session session = sessionFactory.openSession(); User user = new User("John Doe"); session.save(user); User loaded = session.load(User.class, user.getId()); assertThat(loaded.getName()).isEqualTo("John Doe"); } }
/** * Create the {@link Configuration}. * * Reads the values from environment variables. If they are not set, falls back to default values. * * @return the {@link Configuration} */ public static Configuration getConfiguration() { String uri = getEnvOrDefault(ENV_URI, "bolt://localhost"); String username = getEnvOrDefault(ENV_USERNAME, "neo4j"); String password = getEnvOrDefault(ENV_SECRET, "neo4j"); LOGGER.info("Creating configuration for: {} with username: {}", uri, username); return new Configuration.Builder() .uri(uri) .credentials(username, password) .build(); }
@Test // GH-169 public void shouldCreateDirectoryIfMissing() throws IOException { final String EMBEDDED_DIR = "/var/tmp/ogmEmbeddedDir"; Path path = Paths.get(EMBEDDED_DIR); if (Files.exists(path)) { FileUtils.deleteDirectory(path); } Configuration configuration = new Configuration.Builder().uri("file://" + EMBEDDED_DIR).build(); try (EmbeddedDriver driver = new EmbeddedDriver()) { driver.configure(configuration); assertThat(configuration.getURI()).isEqualTo("file://" + EMBEDDED_DIR); assertThat(driver.unwrap(GraphDatabaseService.class)).isNotNull(); assertThat(Files.exists(path)).isTrue(); } FileUtils.deleteDirectory(path); }
/** * Constructs a new {@link SessionFactory} by initialising the object-graph mapping meta-data from the given list of domain * object packages and starts up the Neo4j database in embedded mode. If the embedded driver is not available this method * will throw a <code>Exception</code>. * <p> * The package names passed to this constructor should not contain wildcards or trailing full stops, for example, * "org.springframework.data.neo4j.example.domain" would be fine. The default behaviour is for sub-packages to be scanned * and you can also specify fully-qualified class names if you want to cherry pick particular classes. * </p> * Indexes will also be checked or built if configured. * * @param packages The packages to scan for domain objects */ public SessionFactory(String... packages) { this(new Configuration.Builder().build(), packages); }
public static Builder copy(Builder builder) { return new Builder() .uri(builder.uri) .connectionPoolSize(builder.connectionPoolSize) .encryptionLevel(builder.encryptionLevel) .trustStrategy(builder.trustStrategy) .trustCertFile(builder.trustCertFile) .connectionLivenessCheckTimeout(builder.connectionLivenessCheckTimeout) .verifyConnection(builder.verifyConnection) .autoIndex(builder.autoIndex) .generatedIndexesOutputDir(builder.generatedIndexesOutputDir) .generatedIndexesOutputFilename(builder.generatedIndexesOutputFilename) .neo4jConfLocation(builder.neo4jConfLocation) .credentials(builder.username, builder.password) .customProperties(new HashMap<>(builder.customProperties)); }
@Test public void shouldConfigureFromNameSpacePropertiesFile() { Configuration configuration = new Configuration.Builder( new ClasspathConfigurationSource("ogm-namespace.properties")).build(); assertThat(configuration.getAutoIndex()).isEqualTo(AutoIndexMode.DUMP); assertThat(configuration.getDumpDir()).isEqualTo("hello"); assertThat(configuration.getDumpFilename()).isEqualTo("generated-indexes2.cql"); assertThat(configuration.getDriverClassName()).isEqualTo("org.neo4j.ogm.drivers.http.driver.HttpDriver"); assertThat(configuration.getCredentials().credentials().toString()).isEqualTo("bmVvNGo6cGFzc3dvcmQ="); assertThat(configuration.getURI()).isEqualTo("http://localhost:7474"); assertThat(configuration.getConnectionPoolSize()).isEqualTo(100); assertThat(configuration.getEncryptionLevel()).isEqualTo("NONE"); assertThat(configuration.getTrustStrategy()).isEqualTo("TRUST_ON_FIRST_USE"); assertThat(configuration.getTrustCertFile()).isEqualTo("/tmp/cert"); }
@Test public void throwCorrectExceptionOnUnavailableCluster() throws Exception { Configuration configuration = new Configuration.Builder() .uri("bolt+routing://localhost:1022") .uris(new String[] { "bolt+routing://localhost:1023" }) .verifyConnection(true) .build(); try { new SessionFactory(configuration, "org.neo4j.ogm.domain.social"); } catch (Exception e) { Throwable cause = e.getCause(); assertThat(cause).isInstanceOf(ServiceUnavailableException.class); assertThat(cause).hasMessage("Failed to discover an available server"); } }
@BeforeClass public static void setUp() { assumeTrue(getBaseConfiguration().build().getDriverClassName().equals(BoltDriver.class.getName())); }
@Test public void shouldWriteAndRead() { try (EmbeddedDriver driver = new EmbeddedDriver()) { driver.configure(new Configuration.Builder().build()); GraphDatabaseService databaseService = driver.unwrap(GraphDatabaseService.class); try (Transaction tx = databaseService.beginTx()) { databaseService.execute("CREATE (n: Node {name: 'node'})"); Result r = databaseService.execute("MATCH (n) RETURN n"); assertThat(r.hasNext()).isTrue(); tx.success(); } } }
@Test public void testUnauthorizedDriver() { session = new SessionFactory(getBaseConfiguration().credentials("", "").build(), "dummy").openSession(); try (Transaction tx = session.beginTransaction()) { tx.commit(); fail("Driver should not have authenticated"); } catch (Exception rpe) { Throwable cause = rpe.getCause(); while (!(cause instanceof HttpResponseException)) { cause = cause.getCause(); } assertThat(cause.getMessage().startsWith("Invalid username or password")).isTrue(); } }
@Test public void shouldParseBoltUriSchemesCaseInsensitive() { Configuration configuration = new Configuration.Builder() .uri("BOLT://localhost") .build(); assertThat(configuration.getDriverClassName()).isEqualTo("org.neo4j.ogm.drivers.bolt.driver.BoltDriver"); assertThat(configuration.getURI()).isEqualTo("BOLT://localhost"); configuration = new Configuration.Builder() .uri("BOLT+ROUTING://localhost") .build(); assertThat(configuration.getDriverClassName()).isEqualTo("org.neo4j.ogm.drivers.bolt.driver.BoltDriver"); assertThat(configuration.getURI()).isEqualTo("BOLT+ROUTING://localhost"); }