Skip to content

Commit a5b8145

Browse files
authored
Merge pull request #744 from mneedham/aura-example
Aura example
2 parents 9ed7d75 + 0559fac commit a5b8145

File tree

2 files changed

+140
-6
lines changed

2 files changed

+140
-6
lines changed
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
* Copyright (c) 2002-2020 "Neo4j,"
3+
* Neo4j Sweden AB [http://neo4j.com]
4+
*
5+
* This file is part of Neo4j.
6+
*
7+
* Licensed under the Apache License, Version 2.0 (the "License");
8+
* you may not use this file except in compliance with the License.
9+
* You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing, software
14+
* distributed under the License is distributed on an "AS IS" BASIS,
15+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
* See the License for the specific language governing permissions and
17+
* limitations under the License.
18+
*/
19+
package org.neo4j.docs.driver;
20+
21+
// tag::driver-introduction-example-import[]
22+
23+
import org.neo4j.driver.*;
24+
import org.neo4j.driver.exceptions.Neo4jException;
25+
26+
import java.util.Collections;
27+
import java.util.HashMap;
28+
import java.util.Map;
29+
import java.util.logging.Level;
30+
import java.util.logging.Logger;
31+
32+
import static org.neo4j.driver.Config.TrustStrategy.trustAllCertificates;
33+
// end::driver-introduction-example-import[]
34+
35+
// tag::driver-introduction-example[]
36+
public class DriverIntroductionExample implements AutoCloseable {
37+
private static final Logger LOGGER = Logger.getLogger(DriverIntroductionExample.class.getName());
38+
private final Driver driver;
39+
40+
public DriverIntroductionExample(String uri, String user, String password, Config config) {
41+
// The driver is a long living object and should be opened during the start of your application
42+
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password), config);
43+
}
44+
45+
@Override
46+
public void close() throws Exception {
47+
// The driver object should be closed before the application ends.
48+
driver.close();
49+
}
50+
51+
public void createFriendship(final String person1Name, final String person2Name) {
52+
// To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/
53+
// The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/
54+
String createFriendshipQuery = "CREATE (p1:Person { name: $person1_name })\n" +
55+
"CREATE (p2:Person { name: $person2_name })\n" +
56+
"CREATE (p1)-[:KNOWS]->(p2)\n" +
57+
"RETURN p1, p2";
58+
59+
Map<String, Object> params = new HashMap<>();
60+
params.put("person1_name", person1Name);
61+
params.put("person2_name", person2Name);
62+
63+
try (Session session = driver.session()) {
64+
// Write transactions allow the driver to handle retries and transient errors
65+
Record record = session.writeTransaction(tx -> {
66+
Result result = tx.run(createFriendshipQuery, params);
67+
return result.single();
68+
});
69+
System.out.println(String.format("Created friendship between: %s, %s",
70+
record.get("p1").get("name").asString(),
71+
record.get("p2").get("name").asString()));
72+
// You should capture any errors along with the query and data for traceability
73+
} catch (Neo4jException ex) {
74+
LOGGER.log(Level.SEVERE, createFriendshipQuery + " raised an exception", ex);
75+
throw ex;
76+
}
77+
}
78+
79+
public void findPerson(final String personName) {
80+
String readPersonByNameQuery = "MATCH (p:Person)\n" +
81+
"WHERE p.name = $person_name\n" +
82+
"RETURN p.name AS name";
83+
84+
Map<String, Object> params = Collections.singletonMap("person_name", personName);
85+
86+
try (Session session = driver.session()) {
87+
Record record = session.readTransaction(tx -> {
88+
Result result = tx.run(readPersonByNameQuery, params);
89+
return result.single();
90+
});
91+
System.out.println(String.format("Found person: %s", record.get("name").asString()));
92+
// You should capture any errors along with the query and data for traceability
93+
} catch (Neo4jException ex) {
94+
LOGGER.log(Level.SEVERE, readPersonByNameQuery + " raised an exception", ex);
95+
throw ex;
96+
}
97+
}
98+
99+
public static void main(String... args) throws Exception {
100+
// Aura queries use an encrypted connection using the "neo4j+s" protocol
101+
String boltUrl = "%%BOLT_URL_PLACEHOLDER%%";
102+
103+
String user = "<Username for Neo4j Aura database>";
104+
String password = "<Password for Neo4j Aura database>";
105+
106+
// Aura queries use an encrypted connection
107+
Config config = Config.builder().withEncryption().build();
108+
109+
try (DriverIntroductionExample app = new DriverIntroductionExample(boltUrl, user, password, Config.defaultConfig())) {
110+
app.createFriendship("Alice", "David");
111+
app.findPerson("Alice");
112+
}
113+
}
114+
}
115+
// end::driver-introduction-example[]

examples/src/test/java/org/neo4j/docs/driver/ExamplesIT.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,7 @@
3232
import java.util.Set;
3333
import java.util.UUID;
3434

35-
import org.neo4j.driver.Driver;
36-
import org.neo4j.driver.Session;
37-
import org.neo4j.driver.SessionConfig;
38-
import org.neo4j.driver.Value;
39-
import org.neo4j.driver.Values;
35+
import org.neo4j.driver.*;
4036
import org.neo4j.driver.internal.util.EnabledOnNeo4jWith;
4137
import org.neo4j.driver.summary.QueryType;
4238
import org.neo4j.driver.summary.ResultSummary;
@@ -57,14 +53,14 @@
5753
import static org.hamcrest.junit.MatcherAssert.assertThat;
5854
import static org.junit.jupiter.api.Assertions.assertEquals;
5955
import static org.junit.jupiter.api.Assertions.assertTrue;
56+
import static org.neo4j.driver.Config.TrustStrategy.trustAllCertificates;
6057
import static org.neo4j.driver.Values.parameters;
6158
import static org.neo4j.driver.internal.util.Neo4jEdition.ENTERPRISE;
6259
import static org.neo4j.driver.internal.util.Neo4jFeature.BOLT_V4;
6360
import static org.neo4j.driver.util.Neo4jRunner.PASSWORD;
6461
import static org.neo4j.driver.util.Neo4jRunner.USER;
6562
import static org.neo4j.driver.util.TestUtil.await;
6663
import static org.neo4j.driver.util.TestUtil.createDatabase;
67-
import static org.neo4j.driver.util.TestUtil.databaseExists;
6864
import static org.neo4j.driver.util.TestUtil.dropDatabase;
6965

7066
@ParallelizableIT
@@ -304,6 +300,29 @@ void testShouldRunHelloWorld() throws Exception
304300
}
305301
}
306302

303+
@Test
304+
void testShouldRunDriverIntroduction() throws Exception
305+
{
306+
// Given
307+
Config config = Config.builder().withEncryption().withTrustStrategy(trustAllCertificates()).build();
308+
try (DriverIntroductionExample intro = new DriverIntroductionExample( uri, USER, PASSWORD, config) )
309+
{
310+
// When
311+
StdIOCapture stdIO = new StdIOCapture();
312+
313+
try ( AutoCloseable ignored = stdIO.capture() )
314+
{
315+
intro.createFriendship( "Alice", "David" );
316+
intro.findPerson( "Alice" );
317+
}
318+
319+
// Then
320+
assertThat( stdIO.stdout().size(), equalTo( 2 ) );
321+
assertThat( stdIO.stdout().get( 0 ), containsString( "Created friendship between: Alice, David" ) );
322+
assertThat( stdIO.stdout().get( 1 ), containsString( "Found person: Alice" ) );
323+
}
324+
}
325+
307326
@Test
308327
void testShouldRunReadWriteTransactionExample() throws Exception
309328
{

0 commit comments

Comments
 (0)