Java源码示例:org.neo4j.driver.Driver
示例1
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;
}
示例2
@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);
}
}
示例3
/**
* 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))));
}
示例4
/**
* 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))));
}
示例5
/**
* 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;
}
示例6
/**
* 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))));
}
示例7
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;
}
示例8
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);
}
}
示例9
/**
* @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;
}
示例10
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();
}
}
示例11
@Bean(ReactiveNeo4jRepositoryConfigurationExtension.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME)
@ConditionalOnMissingBean(ReactiveTransactionManager.class)
public ReactiveTransactionManager transactionManager(Driver driver,
ReactiveDatabaseSelectionProvider databaseNameProvider) {
return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
}
示例12
@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());
}
示例13
/**
* 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);
}
示例14
/**
* @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;
}
示例15
@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);
}
示例16
@BeforeEach
void clearDatabase(@Autowired Driver driver) {
try (Session session = driver.session()) {
session.run("MATCH (n) DETACH DELETE n").consume();
}
}
示例17
@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);
}
示例18
@Autowired ReactiveTransactionManagerMixedDatabasesTest(
Driver driver,
ReactiveNeo4jTransactionManager neo4jTransactionManager
) {
this.driver = driver;
this.neo4jTransactionManager = neo4jTransactionManager;
}
示例19
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;
}
示例20
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;
}
示例21
@Bean
public Driver driver() { // <5>
return GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "secret"));
}
示例22
@Singleton
@Produces
public Driver driver() {
return driver;
}
示例23
@Autowired ReactiveRelationshipsIT(Driver driver) {
super(driver);
}
示例24
@Bean(ReactiveNeo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_CLIENT_BEAN_NAME)
@ConditionalOnMissingBean
public ReactiveNeo4jClient neo4jClient(Driver driver) {
return ReactiveNeo4jClient.create(driver);
}
示例25
@Autowired ReactiveAuditingIT(Driver driver, ReactiveTransactionManager transactionManager) {
super(driver);
this.transactionManager = transactionManager;
}
示例26
@Bean("myCustomClient")
Neo4jClient neo4jClient(Driver driver) {
return Neo4jClient.create(driver);
}
示例27
@Bean("myCustomReactiveClient")
ReactiveNeo4jClient neo4jClient(Driver driver) {
return ReactiveNeo4jClient.create(driver);
}
示例28
@Bean
public Driver driver() {
return DriverMocks.withOpenReactiveSessionAndTransaction();
}
示例29
Neo4jSessionSynchronization(Neo4jTransactionHolder connectionHolder, Driver driver) {
super(connectionHolder, driver);
this.localConnectionHolder = connectionHolder;
}
示例30
public ReactiveNeo4jTransactionManager(Driver driver) {
this(driver, ReactiveDatabaseSelectionProvider.getDefaultSelectionProvider());
}