org.neo4j.driver.Driver Java Examples

The following examples show how to use org.neo4j.driver.Driver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Neo4JGraphFactory.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
public static Graph open(Configuration configuration) {
    if (configuration == null)
        throw Graph.Exceptions.argumentCanNotBeNull("configuration");
    try {
        // graph name
        String graphName = configuration.getString(Neo4JGraphConfigurationBuilder.Neo4JGraphNameConfigurationKey);
        // create driver instance
        Driver driver = createDriverInstance(configuration);
        // create providers
        Neo4JElementIdProvider<?> vertexIdProvider = loadProvider(driver, configuration.getString(Neo4JGraphConfigurationBuilder.Neo4JVertexIdProviderClassNameConfigurationKey));
        Neo4JElementIdProvider<?> edgeIdProvider = loadProvider(driver, configuration.getString(Neo4JGraphConfigurationBuilder.Neo4JEdgeIdProviderClassNameConfigurationKey));
        // readonly
        boolean readonly = configuration.getBoolean(Neo4JGraphConfigurationBuilder.Neo4JReadonlyConfigurationKey);
        // database
        String database = configuration.getString(Neo4JGraphConfigurationBuilder.Neo4JDatabaseConfigurationKey, null);
        // check a read partition is required
        if (graphName != null)
            return new Neo4JGraph(new AnyLabelReadPartition(graphName), new String[]{graphName}, driver, database, vertexIdProvider, edgeIdProvider, configuration, readonly);
        // no graph name
        return new Neo4JGraph(new NoReadPartition(), new String[]{}, driver, database, vertexIdProvider, edgeIdProvider, configuration, readonly);
    }
    catch (Throwable ex) {
        // throw runtime exception
        throw new RuntimeException("Error creating Graph instance from configuration", ex);
    }
}
 
Example #2
Source File: Neo4jDriverRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private Driver initializeDriver(Neo4jConfiguration configuration,
        ShutdownContext shutdownContext) {

    String uri = configuration.uri;
    AuthToken authToken = AuthTokens.none();
    if (!configuration.authentication.disabled) {
        authToken = AuthTokens.basic(configuration.authentication.username, configuration.authentication.password);
    }

    Config.ConfigBuilder configBuilder = createBaseConfig();
    configureSsl(configBuilder);
    configurePoolSettings(configBuilder, configuration.pool);

    Driver driver = GraphDatabase.driver(uri, authToken, configBuilder.build());
    shutdownContext.addShutdownTask(driver::close);
    return driver;
}
 
Example #3
Source File: Neo4JGraphFactory.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
static Neo4JElementIdProvider<?> loadProvider(Driver driver, String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    // check class name
    if (className != null) {
        // load class
        Class<?> type = Class.forName(className);
        try {
            // check class has constructor with a Driver parameter
            Constructor<?> constructor = type.getConstructor(Driver.class);
            // create instance
            return (Neo4JElementIdProvider<?>)constructor.newInstance(driver);
        }
        catch (NoSuchMethodException | InvocationTargetException ex) {
            // create instance
            return (Neo4JElementIdProvider<?>)type.newInstance();
        }
    }
    return null;
}
 
Example #4
Source File: ExampleUsingDynamicDatabaseNameTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void createDatabase(@Autowired Driver driver) throws IOException {
	try (Session session = driver.session(SessionConfig.forDatabase("system"))) {
		// Corresponds to the mocked user at the top of this class.
		session.run("CREATE DATABASE someMovieEnthusiast");
	}

	try (BufferedReader moviesReader = new BufferedReader(
		new InputStreamReader(ExampleUsingDynamicDatabaseNameTest.class.getResourceAsStream("/movies.cypher")));
		Session session = driver.session(SessionConfig.forDatabase("someMovieEnthusiast"))) {

		session.run("MATCH (n) DETACH DELETE n");
		String moviesCypher = moviesReader.lines().collect(Collectors.joining(" "));
		session.run(moviesCypher);
	}
}
 
Example #5
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Neo4JGraph} instance.
 *
 * @param driver           The {@link Driver} instance with the database connection information.
 * @param database         The database name.
 * @param vertexIdProvider The {@link Neo4JElementIdProvider} for the {@link Vertex} id generation.
 * @param edgeIdProvider   The {@link Neo4JElementIdProvider} for the {@link Edge} id generation.
 * @param readonly         {@code true} indicates the Graph instance will be used to read from the Neo4J database.
 * @param bookmarks        The initial references to some previous transactions. Both null value and empty iterable are permitted, and indicate that the bookmarks do not exist or are unknown.
 */
public Neo4JGraph(Driver driver, String database, Neo4JElementIdProvider<?> vertexIdProvider, Neo4JElementIdProvider<?> edgeIdProvider, boolean readonly, String... bookmarks) {
    Objects.requireNonNull(driver, "driver cannot be null");
    Objects.requireNonNull(vertexIdProvider, "vertexIdProvider cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    // no label partition
    this.partition = new NoReadPartition();
    this.vertexLabels = Collections.emptySet();
    // store driver instance
    this.driver = driver;
    // database
    this.database = database;
    // store providers
    this.vertexIdProvider = vertexIdProvider;
    this.edgeIdProvider = edgeIdProvider;
    // graph factory configuration (required for tinkerpop test suite)
    this.configuration = null;
    // readonly & bookmarks
    this.readonly = readonly;
    this.bookmarks = Collections.singletonList(Bookmark.from(new HashSet<>(Arrays.asList(bookmarks))));
}
 
Example #6
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Neo4JGraph} instance with the given partition within the neo4j database.
 *
 * @param partition        The {@link Neo4JReadPartition} within the neo4j database.
 * @param vertexLabels     The set of labels to append to vertices created by the {@link Neo4JGraph} session.
 * @param driver           The {@link Driver} instance with the database connection information.
 * @param vertexIdProvider The {@link Neo4JElementIdProvider} for the {@link Vertex} id generation.
 * @param edgeIdProvider   The {@link Neo4JElementIdProvider} for the {@link Edge} id generation.
 * @param readonly         {@code true} indicates the Graph instance will be used to read from the Neo4J database.
 * @param bookmarks        The initial references to some previous transactions. Both null value and empty iterable are permitted, and indicate that the bookmarks do not exist or are unknown.
 */
@Deprecated
public Neo4JGraph(Neo4JReadPartition partition, String[] vertexLabels, Driver driver, Neo4JElementIdProvider<?> vertexIdProvider, Neo4JElementIdProvider<?> edgeIdProvider, boolean readonly, String... bookmarks) {
    Objects.requireNonNull(partition, "partition cannot be null");
    Objects.requireNonNull(vertexLabels, "vertexLabels cannot be null");
    Objects.requireNonNull(driver, "driver cannot be null");
    Objects.requireNonNull(vertexIdProvider, "vertexIdProvider cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    // initialize fields
    this.partition = partition;
    this.vertexLabels = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(vertexLabels)));
    this.driver = driver;
    // database
    this.database = null;
    // validate partition & additional labels
    if (!partition.containsVertex(this.vertexLabels))
        throw new IllegalArgumentException("Invalid vertexLabels, vertices created by the graph will not be part of the given partition");
    // store providers
    this.vertexIdProvider = vertexIdProvider;
    this.edgeIdProvider = edgeIdProvider;
    // graph factory configuration (required for tinkerpop test suite)
    this.configuration = null;
    // readonly & bookmarks
    this.readonly = readonly;
    this.bookmarks = Collections.singletonList(Bookmark.from(new HashSet<>(Arrays.asList(bookmarks))));
}
 
Example #7
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Neo4JGraph} instance with the given partition within the neo4j database.
 *
 * @param partition        The {@link Neo4JReadPartition} within the neo4j database.
 * @param vertexLabels     The set of labels to append to vertices created by the {@link Neo4JGraph} session.
 * @param driver           The {@link Driver} instance with the database connection information.
 * @param database         The database name.
 * @param vertexIdProvider The {@link Neo4JElementIdProvider} for the {@link Vertex} id generation.
 * @param edgeIdProvider   The {@link Neo4JElementIdProvider} for the {@link Edge} id generation.
 * @param configuration    The {@link Configuration} used to create the {@link Graph} instance.
 */
Neo4JGraph(Neo4JReadPartition partition, String[] vertexLabels, Driver driver, String database, Neo4JElementIdProvider<?> vertexIdProvider, Neo4JElementIdProvider<?> edgeIdProvider, Configuration configuration, boolean readonly, String... bookmarks) {
    Objects.requireNonNull(partition, "partition cannot be null");
    Objects.requireNonNull(vertexLabels, "vertexLabels cannot be null");
    Objects.requireNonNull(driver, "driver cannot be null");
    Objects.requireNonNull(vertexIdProvider, "vertexIdProvider cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    Objects.requireNonNull(configuration, "configuration cannot be null");
    // initialize fields
    this.partition = partition;
    this.vertexLabels = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(vertexLabels)));
    this.driver = driver;
    // database
    this.database = database;
    // validate partition & additional labels
    if (!partition.containsVertex(this.vertexLabels))
        throw new IllegalArgumentException("Invalid vertexLabels, vertices created by the graph will not be part of the given partition");
    // store providers
    this.vertexIdProvider = vertexIdProvider;
    this.edgeIdProvider = edgeIdProvider;
    // graph factory configuration (required for tinkerpop test suite)
    this.configuration = configuration;
    // general purpose graph
    this.readonly = readonly;
    this.bookmarks = Collections.singletonList(Bookmark.from(new HashSet<>(Arrays.asList(bookmarks))));
}
 
Example #8
Source File: Neo4JGraph.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Neo4JGraph} instance.
 *
 * @param driver           The {@link Driver} instance with the database connection information.
 * @param database         The database name.
 * @param vertexIdProvider The {@link Neo4JElementIdProvider} for the {@link Vertex} id generation.
 * @param edgeIdProvider   The {@link Neo4JElementIdProvider} for the {@link Edge} id generation.
 */
public Neo4JGraph(Driver driver, String database, Neo4JElementIdProvider<?> vertexIdProvider, Neo4JElementIdProvider<?> edgeIdProvider) {
    Objects.requireNonNull(driver, "driver cannot be null");
    Objects.requireNonNull(vertexIdProvider, "vertexIdProvider cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    // no label partition
    this.partition = new NoReadPartition();
    this.vertexLabels = Collections.emptySet();
    // store driver instance
    this.driver = driver;
    // database
    this.database = database;
    // store providers
    this.vertexIdProvider = vertexIdProvider;
    this.edgeIdProvider = edgeIdProvider;
    // graph factory configuration (required for tinkerpop test suite)
    this.configuration = null;
    // general purpose graph
    this.readonly = false;
    this.bookmarks = null;
}
 
Example #9
Source File: Neo4jTransactionManager.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * This methods provides a native Neo4j transaction to be used from within a {@link org.neo4j.springframework.data.core.Neo4jClient}.
 * In most cases this the native transaction will be controlled from the Neo4j specific
 * {@link org.springframework.transaction.PlatformTransactionManager}. However, SDN-RX provides support for other
 * transaction managers as well. This methods registers a session synchronization in such cases on the foreign transaction manager.
 *
 * @param driver         The driver that has been used as a synchronization object.
 * @param targetDatabase The target database
 * @return An optional managed transaction or {@literal null} if the method hasn't been called inside
 * an ongoing Spring transaction
 */
public static @Nullable Transaction retrieveTransaction(final Driver driver,
	@Nullable final String targetDatabase) {

	if (!TransactionSynchronizationManager.isSynchronizationActive()) {
		return null;
	}

	// Check whether we have a transaction managed by a Neo4j transaction manager
	Neo4jTransactionHolder connectionHolder = (Neo4jTransactionHolder) TransactionSynchronizationManager
		.getResource(driver);

	if (connectionHolder != null) {
		Transaction optionalOngoingTransaction = connectionHolder.getTransaction(targetDatabase);

		if (optionalOngoingTransaction != null) {
			return optionalOngoingTransaction;
		}

		throw new IllegalStateException(
			formatOngoingTxInAnotherDbErrorMessage(connectionHolder.getDatabaseName(), targetDatabase));
	}

	// Otherwise we open a session and synchronize it.
	Session session = driver.session(defaultSessionConfig(targetDatabase));
	Transaction transaction = session.beginTransaction(TransactionConfig.empty());
	// Manually create a new synchronization
	connectionHolder = new Neo4jTransactionHolder(new Neo4jTransactionContext(targetDatabase), session, transaction);
	connectionHolder.setSynchronizedWithTransaction(true);

	TransactionSynchronizationManager.registerSynchronization(
		new Neo4jSessionSynchronization(connectionHolder, driver));

	TransactionSynchronizationManager.bindResource(driver, connectionHolder);
	return connectionHolder.getTransaction(targetDatabase);
}
 
Example #10
Source File: Neo4jReactiveDataConfiguration.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Bean(ReactiveNeo4jRepositoryConfigurationExtension.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME)
@ConditionalOnMissingBean(ReactiveTransactionManager.class)
public ReactiveTransactionManager transactionManager(Driver driver,
	ReactiveDatabaseSelectionProvider databaseNameProvider) {

	return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
}
 
Example #11
Source File: Neo4jResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void createNodes(Driver driver) {
    try (Session session = driver.session();
            Transaction transaction = session.beginTransaction()) {
        transaction.run("CREATE (f:Framework {name: $name}) - [:CAN_USE] -> (n:Database {name: 'Neo4j'})",
                Values.parameters("name", "Quarkus"));
        transaction.commit();
    }
}
 
Example #12
Source File: Neo4jMappingContext.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	super.setApplicationContext(applicationContext);

	this.beanFactory = applicationContext.getAutowireCapableBeanFactory();
	Driver driver = this.beanFactory.getBean(Driver.class);
	((DefaultNeo4jConverter) this.converter).setTypeSystem(driver.defaultTypeSystem());
}
 
Example #13
Source File: Neo4jExtension.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * @return A possible shared driver instance, connected to either a database running inside test containers or
 * running locally.
 */
public Driver getDriver() {

	Driver driver = this.driverInstance;
	if (driver == null) {
		synchronized (this) {
			driver = this.driverInstance;
			if (driver == null) {
				this.driverInstance = GraphDatabase.driver(url, authToken, config);
				driver = this.driverInstance;
			}
		}
	}
	return driver;
}
 
Example #14
Source File: DriverMocks.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * @return An instance usable in a test where an open session with an ongoing transaction is required.
 */
public static Driver withOpenSessionAndTransaction() {

	Transaction transaction = mock(Transaction.class);
	when(transaction.isOpen()).thenReturn(true);

	Session session = mock(Session.class);
	when(session.isOpen()).thenReturn(true);
	when(session.beginTransaction(any(TransactionConfig.class))).thenReturn(transaction);

	Driver driver = mock(Driver.class);
	when(driver.session(any(SessionConfig.class))).thenReturn(session);
	return driver;
}
 
Example #15
Source File: Benchmarks.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
	Map<String, Object> neo4jConfig = prepareNeo4j();

	SpringApplication springApplication = new SpringApplication();
	springApplication.addPrimarySources(Collections.singletonList(Application.class));
	springApplication.setLazyInitialization(true);
	springApplication.setDefaultProperties(neo4jConfig);

	this.applicationContext = springApplication.run();
	this.movieRepository = applicationContext.getBean(MovieRepository.class);
	this.driver = applicationContext.getBean(Driver.class);
}
 
Example #16
Source File: ExceptionTranslationIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void clearDatabase(@Autowired Driver driver) {

	try (Session session = driver.session()) {
		session.run("MATCH (n) DETACH DELETE n").consume();
	}
}
 
Example #17
Source File: Benchmarks.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
	Map<String, Object> neo4jConfig = prepareNeo4j();

	SpringApplication springApplication = new SpringApplication();
	springApplication.addPrimarySources(Collections.singletonList(Application.class));
	springApplication.setLazyInitialization(true);
	springApplication.setDefaultProperties(neo4jConfig);

	this.applicationContext = springApplication.run();
	this.movieRepository = applicationContext.getBean(MovieRepository.class);
	this.driver = applicationContext.getBean(Driver.class);
}
 
Example #18
Source File: ReactiveTransactionManagerMixedDatabasesTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Autowired ReactiveTransactionManagerMixedDatabasesTest(
	Driver driver,
	ReactiveNeo4jTransactionManager neo4jTransactionManager
) {

	this.driver = driver;
	this.neo4jTransactionManager = neo4jTransactionManager;
}
 
Example #19
Source File: DatabaseSequenceElementIdProvider.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
public DatabaseSequenceElementIdProvider(Driver driver, long poolSize, String idFieldName, String sequenceNodeLabel) {
    Objects.requireNonNull(driver, "driver cannot be null");
    Objects.requireNonNull(idFieldName, "idFieldName cannot be null");
    Objects.requireNonNull(sequenceNodeLabel, "sequenceNodeLabel cannot be null");
    // initialize fields
    this.driver = driver;
    this.poolSize = poolSize;
    this.idFieldName = idFieldName;
    this.sequenceNodeLabel = sequenceNodeLabel;
}
 
Example #20
Source File: DatabaseSequenceElementIdProvider.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
public DatabaseSequenceElementIdProvider(Driver driver) {
    Objects.requireNonNull(driver, "driver cannot be null");
    // initialize fields
    this.driver = driver;
    this.poolSize = DefaultPoolSize;
    this.idFieldName = DefaultIdFieldName;
    this.sequenceNodeLabel = DefaultSequenceNodeLabel;
}
 
Example #21
Source File: TypeConversionIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return neo4jConnectionSupport.getDriver();
}
 
Example #22
Source File: AuditingIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return neo4jConnectionSupport.getDriver();
}
 
Example #23
Source File: DefaultNeo4jConverterIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return neo4jConnectionSupport.getDriver();
}
 
Example #24
Source File: OptimisticLockingIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return neo4jConnectionSupport.getDriver();
}
 
Example #25
Source File: OptimisticLockingIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Autowired OptimisticLockingIT(Driver driver) {
	this.driver = driver;
}
 
Example #26
Source File: Neo4jReactiveDataConfiguration.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean(ReactiveNeo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_CLIENT_BEAN_NAME)
@ConditionalOnMissingBean
public ReactiveNeo4jClient neo4jClient(Driver driver) {
	return ReactiveNeo4jClient.create(driver);
}
 
Example #27
Source File: IdGeneratorsIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Autowired IdGeneratorsIT(Driver driver) {
	super(driver);
}
 
Example #28
Source File: KotlinIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return neo4jConnectionSupport.getDriver();
}
 
Example #29
Source File: ProjectionIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Autowired ProjectionIT(Driver driver) {
	this.driver = driver;
}
 
Example #30
Source File: CustomReactiveBaseRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Bean
public Driver driver() {
	return DriverMocks.withOpenReactiveSessionAndTransaction();
}