org.neo4j.driver.v1.AuthTokens Java Examples

The following examples show how to use org.neo4j.driver.v1.AuthTokens. 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: Neo4jConnectionManager.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public Neo4jConnectionManager(Properties properties) {
  this.neo4jUrl = properties.getProperty(NEO4J_SERVER_URL);
  this.config = Config.build()
        .withMaxIdleSessions(Integer.parseInt(properties.getProperty(NEO4J_MAX_CONCURRENCY)))
        .toConfig();
  String authType = properties.getProperty(NEO4J_AUTH_TYPE);
  switch (Neo4jAuthType.valueOf(authType.toUpperCase())) {
    case BASIC:
      String username = properties.getProperty(NEO4J_AUTH_USER);
      String password = properties.getProperty(NEO4J_AUTH_PASSWORD);
      this.authToken = AuthTokens.basic(username, password);
      break;
    case NONE:
      LOGGER.debug("Creating NONE authentication");
      this.authToken = AuthTokens.none();
      break;
    default:
      throw new RuntimeException("Neo4j authentication type not supported");
  }
}
 
Example #3
Source File: ITNeo4JCypherExecutor.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    clientService = new Neo4JCypherClientService();
    runner = TestRunners.newTestRunner(MockProcessor.class);
    runner.addControllerService("clientService", clientService);
    runner.setProperty(clientService, Neo4JCypherClientService.USERNAME, user);
    runner.setProperty(clientService, Neo4JCypherClientService.PASSWORD, password);
    runner.enableControllerService(clientService);
    runner.setProperty(MockProcessor.CLIENT, "clientService");
    driver = GraphDatabase.driver(neo4jUrl, AuthTokens.basic(user, password));
    executeSession("match (n) detach delete n");

    StatementResult result = executeSession("match (n) return n");

    assertEquals("nodes should be equal", 0, result.list().size());
}
 
Example #4
Source File: Neo4jBoltClient.java    From streams with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {

        Objects.nonNull(config);
        assertThat("config.getScheme().startsWith(\"tcp\")", config.getScheme().startsWith("tcp"));

        LOGGER.info("Neo4jConfiguration.start {}", config);

        AuthToken authToken = null;
        if( StringUtils.isNotBlank(config.getUsername()) && StringUtils.isNotBlank(config.getPassword())) {
            authToken = AuthTokens.basic( config.getUsername(), config.getPassword() );
        }

        if( authToken == null ) {
            client = GraphDatabase.driver("bolt://" + config.getHosts().get(0) + ":" + config.getPort());
        } else {
            client = GraphDatabase.driver("bolt://" + config.getHosts().get(0) + ":" + config.getPort(), authToken);
        }

        Objects.nonNull(client);

    }
 
Example #5
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 #6
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 #7
Source File: GraphDBConnection.java    From Insights with Apache License 2.0 5 votes vote down vote up
private GraphDBConnection(String uri, String user, String password) {
	Integer maxIdleConnections = ApplicationConfigProvider.getInstance().getGraph().getMaxIdleConnections();
	if(maxIdleConnections == null) {
		maxIdleConnections = defaultMaxIdleConnections;
	}
	driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ),
									Config.build().withMaxIdleConnections(maxIdleConnections).toConfig() );
}
 
Example #8
Source File: Neo4JDocumentGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected Graph createGraph() {
  driver = GraphDatabase.driver(neo4jUrl, AuthTokens.basic(neo4jUsername, neo4jPassword));
  Neo4JElementIdProvider<?> vertexIdProvider = new DatabaseSequenceElementIdProvider(driver);
  Neo4JElementIdProvider<?> edgeIdProvider = new DatabaseSequenceElementIdProvider(driver);

  // create graph instance
  return new Neo4JGraph(driver, vertexIdProvider, edgeIdProvider);
}
 
Example #9
Source File: Neo4JEntityGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected Graph createGraph() {
  driver = GraphDatabase.driver(neo4jUrl, AuthTokens.basic(neo4jUsername, neo4jPassword));
  Neo4JElementIdProvider<?> vertexIdProvider = new DatabaseSequenceElementIdProvider(driver);
  Neo4JElementIdProvider<?> edgeIdProvider = new DatabaseSequenceElementIdProvider(driver);

  // create graph instance
  return new Neo4JGraph(driver, vertexIdProvider, edgeIdProvider);
}
 
Example #10
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 #11
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 #12
Source File: DBAuthTest.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoteBasicAuth() {
	Properties props = new Properties();
	props.setProperty(DBProperties.SERVER_ROOT_URI, "http://localhost:7474"); // not Bolt
	props.setProperty(DBProperties.DATABASE_DIR, "C:/NEO4J_DBS/01");
	DBType dbType = DBType.REMOTE;
	
	AuthToken auth = AuthTokens.basic("user", "password");
	
	IDBAccess dba = DBAccessFactory.createDBAccess(dbType, props, auth);
	String bauth = ((RemoteDBAccess)dba).getAuth();
	assertEquals("Basic dXNlcjpwYXNzd29yZA==", bauth);
	return;
}
 
Example #13
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 #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: 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 #16
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 #17
Source File: BoltDBAccess.java    From jcypher with Apache License 2.0 4 votes vote down vote up
@Override
public void setAuth(String userId, String password) {
	if (userId != null && password != null)
		this.authToken = AuthTokens.basic(userId, password);
}
 
Example #18
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());
}