org.neo4j.driver.v1.Driver Java Examples

The following examples show how to use org.neo4j.driver.v1.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: Neo4JServerLiveTest.java    From tutorials with MIT License 12 votes vote down vote up
@Test
public void standAloneDriver() {
    Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "12345"));
    Session session = driver.session();

    session.run("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
            "-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
            "RETURN baeldung, tesla");

    StatementResult result = session.run("MATCH (company:Company)-[:owns]-> (car:Car)" +
            "WHERE car.make='tesla' and car.model='modelX'" +
            "RETURN company.name");

    Assert.assertTrue(result.hasNext());
    Assert.assertEquals(result.next().get("company.name").asString(), "Baeldung");

    session.close();
    driver.close();
}
 
Example #2
Source File: Neo4jContainerJUnitIntegrationTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldStart() {

    boolean actual = neo4jContainer.isRunning();
    assertThat(actual).isTrue();

    try (Driver driver = GraphDatabase
        .driver(neo4jContainer.getBoltUrl(), AuthTokens.basic("neo4j", "password"));
        Session session = driver.session()
    ) {
        long one = session.run("RETURN 1", Collections.emptyMap()).next().get(0).asLong();
        assertThat(one).isEqualTo(1L);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example #3
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldRunEnterprise() {
    assumeThat(Neo4jContainerTest.class.getResource(ACCEPTANCE_FILE_LOCATION)).isNotNull();

    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer()
            .withEnterpriseEdition()
            .withAdminPassword("Picard123")
    ) {
        neo4jContainer.start();
        try (
            Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            String edition = session
                .run("CALL dbms.components() YIELD edition RETURN edition", Collections.emptyMap())
                .next().get(0).asString();
            assertThat(edition).isEqualTo("enterprise");
        }
    }
}
 
Example #4
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldCopyDatabase() {
    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer()
            .withDatabase(MountableFile.forClasspathResource("/test-graph.db"));
    ) {
        neo4jContainer.start();
        try (
            Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            StatementResult result = session.run("MATCH (t:Thing) RETURN t");
            assertThat(result.list().stream().map(r -> r.get("t").get("name").asString()))
                .containsExactlyInAnyOrder("Thing", "Thing 2", "Thing 3", "A box");
        }
    }
}
 
Example #5
Source File: CypherHandlersIT.java    From rdf2neo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test {@link CyNodeLoadingHandler} to see if nodes are mapped from RDF and loaded into Neo4J
 */
@Test
public void testNodes () throws Exception
{
	try (	
		Driver neoDriver = GraphDatabase.driver( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
	)
	{
		Session session = neoDriver.session ( AccessMode.READ );
		StatementResult cursor = session.run ( "MATCH ( n:TestNode ) RETURN COUNT ( n ) AS ct" );
		Assert.assertEquals ( "Wrong count for TestNode", 2, cursor.next ().get ( "ct" ).asLong () );
		
		cursor = session.run ( "MATCH ( n:TestNode { iri:'" + iri ( "ex:2" ) + "'} ) RETURN properties ( n ) AS props" );
		assertTrue ( "ex:2 not returned!", cursor.hasNext () );
		
		Map<String, Object> map = cursor.next ().get ( "props" ).asMap ();
		assertEquals (  "Wrong property!", "another string", map.get ( "attrib3" ) );
	}
}
 
Example #6
Source File: CypherHandlersIT.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Loads some basic test RDF data into RDF.
 */
@Before
public void initNeoData () throws IOException
{
	initNeo ();

	try (	
			Driver neoDriver = GraphDatabase.driver( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
			RdfDataManager rdfMgr = new RdfDataManager ( RdfDataManagerTest.TDB_PATH );
		)
	{
		CyNodeLoadingHandler handler = new CyNodeLoadingHandler ();
		Neo4jDataManager neoMgr = new Neo4jDataManager ( neoDriver );
		
		// We need the same nodes in all tests
		handler.setRdfDataManager ( rdfMgr );
		handler.setNeo4jDataManager ( neoMgr );
		handler.setLabelsSparql ( RdfDataManagerTest.SPARQL_NODE_LABELS );
		handler.setNodePropsSparql ( RdfDataManagerTest.SPARQL_NODE_PROPS );
		
		Set<Resource> rdfNodes = 
			Stream.of ( iri ( "ex:1" ), iri ( "ex:2" ), iri ( "ex:3" ) )
			.map ( iri -> rdfMgr.getDataSet ().getDefaultModel ().createResource ( iri ) )
			.collect ( Collectors.toSet () );

		handler.accept ( rdfNodes );
	}
}
 
Example #7
Source File: BoltDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private Driver getDriver() {
	if (this.driver == null) {
		String uri = this.properties.getProperty(DBProperties.SERVER_ROOT_URI);
		if (this.authToken != null)
			this.driver = GraphDatabase.driver(uri, this.authToken);
		else
			this.driver = GraphDatabase.driver(uri);
		this.shutdownHook = registerShutdownHook();
	}
	return this.driver;
}
 
Example #8
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private static Driver getDriver(Neo4jContainer container) {

        AuthToken authToken = AuthTokens.none();
        if (container.getAdminPassword() != null) {
            authToken = AuthTokens.basic("neo4j", container.getAdminPassword());
        }
        return GraphDatabase.driver(container.getBoltUrl(), authToken);
    }
 
Example #9
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void shouldCopyPlugin() {
    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer()
            .withPlugins(MountableFile.forClasspathResource("/custom-plugins/hello-world.jar"));
    ) {
        neo4jContainer.start();
        try (
            Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            assertThatCustomPluginWasCopied(session);
        }
    }
}
 
Example #10
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void shouldCopyPlugins() {
    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer()
            .withPlugins(MountableFile.forClasspathResource("/custom-plugins"));
    ) {
        neo4jContainer.start();
        try (
            Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            assertThatCustomPluginWasCopied(session);
        }
    }
}
 
Example #11
Source File: Neo4jContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void shouldDisableAuthentication() {

    try (
        Neo4jContainer neo4jContainer = new Neo4jContainer().withoutAuthentication();
    ) {
        neo4jContainer.start();
        try (Driver driver = getDriver(neo4jContainer);
            Session session = driver.session()
        ) {
            long one = session.run("RETURN 1", Collections.emptyMap()).next().get(0).asLong();
            assertThat(one).isEqualTo(1L);
        }
    }
}
 
Example #12
Source File: CypherHandlersIT.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Facility to empty the Neo4j test DB. Auto-called by other tests.
 * It's here as static method, because we call it from other clasess as well.
 */
public static void initNeo ()
{
	try (	
			Driver neoDriver = GraphDatabase.driver( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
			Session session = neoDriver.session ();
		)
	{
		session.run ( "MATCH (n) DETACH DELETE n" );
	}
}
 
Example #13
Source File: Neo4jDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * The driver and target Neo4j destination used to send Cypher elements mapped from RDF.
 * We don't care about closing this, so the caller has to do it.
 */
public Driver getNeo4jDriver ()
{
	return neo4jDriver;
}
 
Example #14
Source File: CypherLoaderIT.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testMultiConfigLoading () throws Exception
{
	try ( MultiConfigCyLoader cymloader = new MultiConfigCyLoader (); )
	{
		cymloader.setCypherLoaderFactory ( () -> 
		{
			// You don't want to do this, see #testSpring()
			
			RdfDataManager rdfMgr = new RdfDataManager ();
			Driver neoDriver = GraphDatabase.driver ( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
			Neo4jDataManager neoMgr = new Neo4jDataManager ( neoDriver );			
			
			CyNodeLoadingHandler cyNodeHandler = new CyNodeLoadingHandler ();
			CyRelationLoadingHandler cyRelHandler = new CyRelationLoadingHandler ();
			
			cyNodeHandler.setRdfDataManager ( rdfMgr );
			cyNodeHandler.setNeo4jDataManager ( neoMgr );
			
			cyRelHandler.setRdfDataManager ( rdfMgr );
			cyRelHandler.setNeo4jDataManager ( neoMgr );

			CyNodeLoadingProcessor cyNodeProc = new CyNodeLoadingProcessor ();
			cyNodeProc.setBatchJob ( cyNodeHandler );
			
			CyRelationLoadingProcessor cyRelProc = new CyRelationLoadingProcessor ();
			cyRelProc.setBatchJob ( cyRelHandler );

			SimpleCyLoader cyloader = new SimpleCyLoader ();
			cyloader.setCyNodeLoader ( cyNodeProc );
			cyloader.setCyRelationLoader ( cyRelProc );
			cyloader.setRdfDataManager ( rdfMgr );
			
			return cyloader;
		});

		
		List<ConfigItem> config = new LinkedList<> ();
		config.add ( new ConfigItem ( 
			"places", 
			readResource ( "dbpedia_node_iris.sparql" ), 
			readResource ( "dbpedia_node_labels.sparql" ), 
			readResource ( "dbpedia_node_props.sparql" ), 
			readResource ( "dbpedia_rel_types.sparql" ), 
			readResource ( "dbpedia_rel_props.sparql" )			 
		));
		config.add ( new ConfigItem ( 
			"people", 
			readResource ( "dbpedia_people_iris.sparql" ), 
			readResource ( "dbpedia_people_labels.sparql" ), 
			readResource ( "dbpedia_people_props.sparql" ), 
			readResource ( "dbpedia_people_rel_types.sparql" ), 
			null			 
		));
		
		cymloader.setConfigItems ( config );

		cymloader.load ( RdfDataManagerTest.TDB_PATH );
	}
	// TODO: test!
}
 
Example #15
Source File: Neo4JCypherClientService.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Driver getDriver(ConfigurationContext context) {
    connectionUrl = context.getProperty(CONNECTION_URL).evaluateAttributeExpressions().getValue();
    username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
    password = context.getProperty(PASSWORD).getValue();

    Config.ConfigBuilder configBuilder = Config.build();
    String loadBalancingStrategyValue = context.getProperty(LOAD_BALANCING_STRATEGY).getValue();
    if ( ! StringUtils.isBlank(loadBalancingStrategyValue) ) {
        configBuilder = configBuilder.withLoadBalancingStrategy(
                Config.LoadBalancingStrategy.valueOf(loadBalancingStrategyValue));
    }

    configBuilder.withMaxConnectionPoolSize(context.getProperty(MAX_CONNECTION_POOL_SIZE).evaluateAttributeExpressions().asInteger());

    configBuilder.withConnectionTimeout(context.getProperty(CONNECTION_TIMEOUT).evaluateAttributeExpressions().asTimePeriod(TimeUnit.SECONDS), TimeUnit.SECONDS);

    configBuilder.withConnectionAcquisitionTimeout(context.getProperty(MAX_CONNECTION_ACQUISITION_TIMEOUT).evaluateAttributeExpressions().asTimePeriod(TimeUnit.SECONDS), TimeUnit.SECONDS);

    configBuilder.withMaxConnectionLifetime(context.getProperty(MAX_CONNECTION_LIFETIME).evaluateAttributeExpressions().asTimePeriod(TimeUnit.SECONDS), TimeUnit.SECONDS);

    configBuilder.withConnectionLivenessCheckTimeout(context.getProperty(IDLE_TIME_BEFORE_CONNECTION_TEST).evaluateAttributeExpressions().asTimePeriod(TimeUnit.SECONDS), TimeUnit.SECONDS);

    if ( context.getProperty(ENCRYPTION).asBoolean() ) {
        configBuilder.withEncryption();
    } else {
        configBuilder.withoutEncryption();
    }

    final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    if (sslService != null) {
        if ( sslService.isTrustStoreConfigured()) {
            configBuilder.withTrustStrategy(Config.TrustStrategy.trustCustomCertificateSignedBy(new File(
                    sslService.getTrustStoreFile())));
        } else {
            configBuilder.withTrustStrategy(Config.TrustStrategy.trustSystemCertificates());
        }
    }

    return GraphDatabase.driver( connectionUrl, AuthTokens.basic( username, password),
            configBuilder.toConfig());
}
 
Example #16
Source File: Neo4jDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Overridden just to add Spring annotations.
 */
@Autowired	 @Override
public void setNeo4jDriver ( Driver neo4jDriver ) {
	super.setNeo4jDriver ( neo4jDriver );
}
 
Example #17
Source File: BoltDBAccess.java    From jcypher with Apache License 2.0 4 votes vote down vote up
public BoltDBAccess(Driver driver) {
	super();
	this.driver = driver;
}
 
Example #18
Source File: NeoProfiler.java    From neoprofiler with Apache License 2.0 4 votes vote down vote up
public NeoProfiler(String storageLoc, Driver driver) { 
	this.driver = driver;
	this.storageLoc = storageLoc;
}
 
Example #19
Source File: Neo4jBoltClient.java    From streams with Apache License 2.0 4 votes vote down vote up
public Driver client() {
    return client;
}
 
Example #20
Source File: Neo4jDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setNeo4jDriver ( Driver neo4jDriver )
{
	this.neo4jDriver = neo4jDriver;
}
 
Example #21
Source File: Neo4jDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Neo4jDataManager ( Driver neo4jDriver ) {
	super ( neo4jDriver );
}
 
Example #22
Source File: CypherHandlersIT.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests {@link CyRelationLoadingHandler} to see if relations are mapped from RDF and loaded into Neo4J.
 */
@Test
public void testRelations () throws Exception
{
	try (	
		Driver neoDriver = GraphDatabase.driver( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
		RdfDataManager rdfMgr = new RdfDataManager ( RdfDataManagerTest.TDB_PATH );
	)
	{
		CyRelationLoadingHandler handler = new CyRelationLoadingHandler ();
		Neo4jDataManager neoMgr = new Neo4jDataManager ( neoDriver );

		handler.setRdfDataManager ( rdfMgr );
		handler.setNeo4jDataManager ( neoMgr );
		handler.setRelationTypesSparql ( RdfDataManagerTest.SPARQL_REL_TYPES );
		handler.setRelationPropsSparql ( RdfDataManagerTest.SPARQL_REL_PROPS  );

		Set<QuerySolution> relSparqlRows = new HashSet<> ();
		Dataset dataSet = rdfMgr.getDataSet ();
		Txn.executeRead ( dataSet,  () ->
			SparqlUtils.select ( RdfDataManagerTest.SPARQL_REL_TYPES, rdfMgr.getDataSet ().getDefaultModel () )
				.forEachRemaining ( row -> relSparqlRows.add ( row ) )
		);

		handler.accept ( relSparqlRows );

		// Verify
		
		CypherTester tester = new CypherTester ( neoMgr );
		
		Assert.assertTrue (
			"Wrong count for relations",
			tester.ask ( "MATCH ()-[r]->() RETURN COUNT ( r ) = 3" )
		);

		Assert.assertTrue (
			"Wrong count for {1 relatedTo 2}!",
			tester.ask ( 
				"MATCH p = (:TestNode{ iri:$iri1 })-[:relatedTo]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) = 1",
				"iri1", iri ( "ex:1" ), "iri2", iri ( "ex:2" )
			)
		);
		
		Assert.assertTrue (
			"Wrong count for {3 derivedFrom 1}!",
			tester.ask ( 
				"MATCH p = (:SuperTestNode{ iri:$iri1 })-[:derivedFrom]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) = 1",
				"iri1", iri ( "ex:3" ), "iri2", iri ( "ex:1" )
			)
		);

		Assert.assertTrue (
			"Wrong count for {3 derivedFrom 1}!",
			tester.ask ( 
				"MATCH p = (:SuperTestNode{ iri:$iri1 })-[:derivedFrom]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) = 1",
				"iri1", iri ( "ex:3" ), "iri2", iri ( "ex:1" )
			)
		);

		Assert.assertTrue (
			"Wrong count for {3 derivedFrom 1}!",
			tester.ask ( 
				"MATCH p = (:SuperTestNode{ iri:$iri1 })-[:derivedFrom]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) = 1",
				"iri1", iri ( "ex:3" ), "iri2", iri ( "ex:1" )
			)
		);
		
		
		Assert.assertTrue (
			"reified relation, wrong property value for 'note'!",
			tester.compare (
				// Test against the Cypher result
				notesv -> {
					List<Object> notes = notesv.asList ();
					if ( notes == null || notes.isEmpty () ) return false;

					// notes collection is sorted, then compared to the sorted values in the reference
					return notes
						.stream ()
						.sorted ()
						.collect ( Collectors.toList () )
						.equals ( 
							Arrays.asList ( new String[] { "Another Note", "Reified Relation" } )
						);
				},
				// the relation containing .note
				"MATCH (:TestNode{ iri:$iri1 })-[r:relatedTo]->(:AdditionalLabel{ iri:$iri2 })\n"
				+ "RETURN r.note\n",
				"iri1", iri ( "ex:2" ), "iri2", iri ( "ex:3" )
			)
		);
	} // try
}
 
Example #23
Source File: CypherTester.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * We don't care about closing the driver, this is up to the caller.
 */
public CypherTester ( Driver neo4jDriver )
{
	this ( new Neo4jDataManager ( neo4jDriver ) );
}
 
Example #24
Source File: CypherLoaderIT.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testLoading () throws Exception
{
	try (
		Driver neoDriver = GraphDatabase.driver ( "bolt://127.0.0.1:7687", AuthTokens.basic ( "neo4j", "test" ) );
		RdfDataManager rdfMgr = new RdfDataManager ( RdfDataManagerTest.TDB_PATH );
		SimpleCyLoader cyloader = new SimpleCyLoader ();
	)
	{
		// You don't want to do this, see #testSpring()

		Neo4jDataManager neoMgr = new Neo4jDataManager ( neoDriver );
		
		CyNodeLoadingHandler cyNodeHandler = new CyNodeLoadingHandler ();
		CyRelationLoadingHandler cyRelHandler = new CyRelationLoadingHandler ();
		
		cyNodeHandler.setLabelsSparql ( IOUtils.readResource ( "dbpedia_node_labels.sparql" ) );
		cyNodeHandler.setNodePropsSparql ( IOUtils.readResource ( "dbpedia_node_props.sparql" ) );
		cyNodeHandler.setRdfDataManager ( rdfMgr );
		cyNodeHandler.setNeo4jDataManager ( neoMgr );
		
		cyRelHandler.setRelationTypesSparql ( IOUtils.readResource ( "dbpedia_rel_types.sparql" ) );
		cyRelHandler.setRelationPropsSparql ( IOUtils.readResource ( "dbpedia_rel_props.sparql" ) );
		cyRelHandler.setRdfDataManager ( rdfMgr );
		cyRelHandler.setNeo4jDataManager ( neoMgr );

		CyNodeLoadingProcessor cyNodeProc = new CyNodeLoadingProcessor ();
		cyNodeProc.setNodeIrisSparql ( IOUtils.readResource ( "dbpedia_node_iris.sparql" ) );
		cyNodeProc.setBatchJob ( cyNodeHandler );
		
		CyRelationLoadingProcessor cyRelProc = new CyRelationLoadingProcessor ();
		cyRelProc.setBatchJob ( cyRelHandler );

		cyloader.setCyNodeLoader ( cyNodeProc );
		cyloader.setCyRelationLoader ( cyRelProc );
		
		cyloader.load ( RdfDataManagerTest.TDB_PATH );
		// TODO: test!
		
	} // try neoDriver
}
 
Example #25
Source File: Neo4jDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Neo4jDataManager ( Driver neo4jDriver )
{
	super ();
	this.neo4jDriver = neo4jDriver;
}
 
Example #26
Source File: Neo4jConnectionManager.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private Driver getDriver() {
  if (driver == null) {
    driver = GraphDatabase.driver(this.neo4jUrl, this.authToken, this.config);
  }
  return driver;
}
 
Example #27
Source File: GraphDBConnection.java    From Insights with Apache License 2.0 4 votes vote down vote up
public Driver getDriver() {
	if(driver == null) {
		getInstance();
	}
	return driver;
}
 
Example #28
Source File: Neo4JCypherClientService.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Helper method to help testability
 * @return Driver instance
 */
protected Driver getNeo4JDriver() {
    return neo4JDriver;
}
 
Example #29
Source File: NeoProfiler.java    From neoprofiler with Apache License 2.0 votes vote down vote up
public Driver getDriver() { return driver; }