Java Code Examples for org.neo4j.driver.v1.Session#close()

The following examples show how to use org.neo4j.driver.v1.Session#close() . 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: QueryRunner.java    From neoprofiler with Apache License 2.0 6 votes vote down vote up
public List<NeoProperty> getSampleProperties(NeoProfiler parent, Entity n) {
	List<NeoProperty> props = new ArrayList<NeoProperty>();
	
	Session s = parent.getDriver().session();
	try ( Transaction tx = s.beginTransaction() ) {			 
		Iterator<String> propKeys = n.keys().iterator();
		
		while(propKeys.hasNext()) {
			String key = propKeys.next();
			Object val = n.get(key);
			
			props.add(new NeoProperty(key, val.getClass().getSimpleName()));				
		}
		
	} finally {
		s.close();
	}

	return props;
}
 
Example 3
Source File: ExpandDocxNodes.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public static SubGraph run(SubGraph searchResult1, ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    for (long node : searchResult1.getNodes()) {
        Session session = context.connection.session();
        String stat = "match p=(n1)-[:" + CodeInDocxFileExtractor.API_EXPLAINED_BY + "]->(n2) where id(n1)=" + node + " unwind relationships(p) as r return id(r), id(startNode(r)), id(endNode(r))";
        StatementResult rs = session.run(stat);
        while (rs.hasNext()) {
            Record item=rs.next();
            long node1 = item.get("id(startNode(r))").asLong();
            long node2 = item.get("id(endNode(r))").asLong();
            long rel = item.get("id(r)").asLong();
            r.getNodes().add(node1);
            r.getNodes().add(node2);
            r.getEdges().add(rel);
        }
        session.close();
    }
    return r;
}
 
Example 4
Source File: ExpandFlossNodes.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public static SubGraph run(String query, SubGraph searchResult1, SubGraph linkedSearchResult1,  ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    List<LuceneSearchResult> luceneSearchResults=context.getLuceneSearcher().query(query);
    luceneSearchResults.sort((LuceneSearchResult a, LuceneSearchResult b)->{
        Double aDist=new Double(dist(a.nodeSet,searchResult1.getNodes(),context));
        Double bDist=new Double(dist(b.nodeSet,searchResult1.getNodes(),context));
        return aDist.compareTo(bDist);
    });
    for (int i=0;i<3&&i<luceneSearchResults.size();i++) {
        r.getNodes().add(luceneSearchResults.get(i).id);
        for (long node:linkedSearchResult1.getNodes()){
            Session session=context.connection.session();
            StatementResult rs=session.run("match (a)-[r]-(b) where id(a)="+node+" and id(b)="+luceneSearchResults.get(i).id+" return id(r)");
            while (rs.hasNext()){
                Record item=rs.next();
                r.getEdges().add(item.get("id(r)").asLong());
            }
            session.close();
        }
    }
    return r;
}
 
Example 5
Source File: Neo4jBoltPersistWriter.java    From streams with Apache License 2.0 6 votes vote down vote up
@Override
public void write(StreamsDatum entry) {

  List<Pair<String, Map<String, Object>>> statements;
  Session session = null;
  try {
    statements = Neo4jPersistUtil.prepareStatements(entry);
    session = client.client().session();
    Transaction transaction = session.beginTransaction();
    for( Pair<String, Map<String, Object>> statement : statements ) {
      StatementResult statementResult = transaction.run( statement.getValue0(), statement.getValue1() );
      LOGGER.debug("StatementResult", statementResult.single());
    }
    transaction.success();
  } catch( Exception ex ) {
    LOGGER.error("Exception", ex);
  } finally {
    if( session != null ) {
      session.close();
    }
  }
}
 
Example 6
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public String transactionEnlistmentReadAfterCallingTransactionClose() {
    // JTA transaction is started by CMT, the following obtains a Session that is enlisted into the JTA transaction.
    Session session = injectedDriver.session();
    // The only way to influence success/failure of the Neo4j + JTA transaction, is at the JTA transaction level.
    // If the JTA transaction fails, org.neo4j.driver.v1.Transaction.failure() is called.
    // If the JTA transaction succeeds, org.neo4j.driver.v1.Transaction.success() is called.
    // org.neo4j.driver.v1.Transaction.close() is also called when the JTA transaction ends.

    // Calls to Session.beginTransaction() in a JTA transaction are expected to throw a RuntimeException
    try {
        Transaction transaction = session.beginTransaction();
        fail("Calling Session.beginTransaction in a JTA transaction should throw a RuntimeException.");
    } catch (RuntimeException expectedException) {
        // success
    }

    try {
        session.run("CREATE (a:Person {name:'TRANSACTION', title:'King'})");
        return nestedBean.getPerson("TRANSACTION");
    } finally {
        if ( session.isOpen()) { // this will be true
            session.run("MATCH (a:Person) delete a");
            session.close();             // ignored, session is auto closed when the transaction ends.
        }
    }
}
 
Example 7
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public String addPerson() {
    Session session = driver.session();
    try {
        session.run("CREATE (a:Person {name:'Arthur', title:'King'})");
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title");


        Record record = result.next();
        return record.toString();
    } finally {
        session.run("MATCH (a:Person) delete a");
        session.close();
    }
}
 
Example 8
Source File: TwitterFollowNeo4jIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@AfterClass
public void cleanup() throws Exception {
  Session session = testClient.client().session();
  Transaction transaction = session.beginTransaction();
  transaction.run("MATCH ()-[r]-() DELETE r");
  transaction.run("MATCH (n) DETACH DELETE n");
  transaction.success();
  session.close();
}
 
Example 9
Source File: TwitterFollowNeo4jIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTest() throws IOException {

  testConfiguration = new StreamsConfigurator<>(TwitterFollowNeo4jConfiguration.class).detectCustomConfiguration();
  testClient = Neo4jBoltClient.getInstance(testConfiguration.getNeo4j());

  Session session = testClient.client().session();
  Transaction transaction = session.beginTransaction();
  transaction.run("MATCH ()-[r]-() DELETE r");
  transaction.run("MATCH (n) DETACH DELETE n");
  transaction.success();
  session.close();
}
 
Example 10
Source File: Neo4jBoltPersistIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@AfterClass
public void cleanup() throws Exception {
  Session session = testClient.client().session();
  Transaction transaction = session.beginTransaction();
  transaction.run("MATCH ()-[r]-() DELETE r");
  transaction.run("MATCH (n) DETACH DELETE n");
  transaction.success();
  session.close();
}
 
Example 11
Source File: Neo4jBoltPersistIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTest() throws IOException {

  testConfiguration = new ComponentConfigurator<>(Neo4jConfiguration.class).detectConfiguration( "Neo4jBoltPersistIT");
  testClient = Neo4jBoltClient.getInstance(testConfiguration);

  Session session = testClient.client().session();
  Transaction transaction = session.beginTransaction();
  transaction.run("MATCH ()-[r]-() DELETE r");
  transaction.run("MATCH (n) DETACH DELETE n");
  transaction.success();
  session.close();
}
 
Example 12
Source File: Neo4jBoltPersistReader.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public StreamsResultSet readAll() {

  Session session = null;

  String query = config.getQuery();
  Map<String, Object> params = mapper.convertValue(config.getParams(), Map.class);

  try {
    session = client.client().session();
    Transaction transaction = session.beginTransaction();

    this.statementResult = client.client().session().beginTransaction().run(query, params);

    while( statementResult.hasNext()) {
      Record record = statementResult.next();
      Optional<StreamsDatum> datum = buildDatum(record);
      if( datum.isPresent()) {
        write(datum.get());
      }
    }

  } catch(Exception ex) {
    LOGGER.warn("Exception", ex);
  } finally {
    if( session != null ) {
      session.close();
    }
  }
  return readCurrent();

}
 
Example 13
Source File: NestedBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@TransactionAttribute(REQUIRES_NEW)
public String getPerson(String name) {
    Session session = injectedDriver.session();
    try {
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = '" + name + "' RETURN a.name AS name, a.title AS title");
        if (result.hasNext()) {
            Record record = result.next();
            return record.toString();
        }
        return name + " not found";
    }
    finally {
        session.close();
    }
}
 
Example 14
Source File: StatefulTestBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public String addPersonClassInstanceInjection() {
    Session session = injectedDriver.session();
    try {
        session.run("CREATE (a:Person {name:'CDI', title:'King'})");
        StatementResult result = session.run("MATCH (a:Person) WHERE a.name = 'CDI' RETURN a.name AS name, a.title AS title");


        Record record = result.next();
        return record.toString();
    } finally {
        session.run("MATCH (a:Person) delete a");
        session.close();
    }
}
 
Example 15
Source File: ApiLocator.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public SubGraph query(String queryString) {

        if (queryString.matches("^[\\d\\s]+$")){ // 只有结点id构成的query
            List<Long> idList=new ArrayList<>();
            String[] eles = queryString.trim().split("\\s+");
            for (String e:eles)
                if (e.length()>0) {
                    Session session = context.connection.session();
                    long id=Long.parseLong(e);
                    String stat="match (n) where id(n)="+id+" return id(n)";
                    StatementResult rs = session.run(stat);
                    if (rs.hasNext()) {
                        idList.add(id);
                    }
                    session.close();
                }
            return idTest(idList);
        }

        /*
         * seedMap: - key: 定位到的代码元素结点的集合 - value: 这个集合的离散度,离散度越低,说明这个图的质量越好
		 */
        candidateMap.clear();// 清空candidateMap, 对于每个query即时生成
        scoreMap.clear();
        List<SubGraph> graphs = myFindSubGraphs(queryString);
        if (graphs.size() > 0) {
            if (debug)
                printGraphList(graphs);
            return graphs.get(0);
        }
        return new SubGraph();
    }
 
Example 16
Source File: ConnectCodeElements.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static SubGraph run(SubGraph searchResult1, ApiLocatorContext context){
    SubGraph r = new SubGraph();
    r.getNodes().addAll(searchResult1.getNodes());
    r.cost = searchResult1.cost;
    Set<Long> flags = new HashSet<>();
    for (long seed1 : searchResult1.getNodes()) {
        if (flags.contains(seed1))
            continue;
        for (long seed2 : searchResult1.getNodes()) {
            if (seed1 == seed2)
                continue;
            if (flags.contains(seed2))
                continue;
            Session session = context.connection.session();
            String stat = "match p=shortestPath((n1)-[:" + codeRels + "*..10]-(n2)) where id(n1)=" + seed1 + " and id(n2)=" + seed2
                    + " unwind relationships(p) as r return id(startNode(r)), id(endNode(r)), id(r)";
            StatementResult rs = session.run(stat);
            while (rs.hasNext()) {
                Record item=rs.next();
                long node1 = item.get("id(startNode(r))").asLong();
                long node2 = item.get("id(endNode(r))").asLong();
                long rel = item.get("id(r)").asLong();
                r.getNodes().add(node1);
                r.getNodes().add(node2);
                r.getEdges().add(rel);
                flags.add(seed2);
            }
            session.close();
        }
        flags.add(seed1);
    }
    return r;
}
 
Example 17
Source File: Neo4jNode.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static Neo4jNode get(long id, SnowGraphContext context){
    Neo4jNode node=null;
    Session session = context.getNeo4jBoltDriver().session();
    String stat = "match (n) where id(n)=" + id + " return id(n), labels(n)[0], n";
    StatementResult rs = session.run(stat);
    while (rs.hasNext()) {
        Record item=rs.next();
        node=new Neo4jNode(item.get("id(n)").asLong(),item.get("labels(n)[0]").asString());
        node.properties.putAll(item.get("n").asMap());
        node.properties.put("id",node.id);
        node.properties.put("label",node.label);
    }
    session.close();
    return node;
}
 
Example 18
Source File: InsightsGraphDBHandler.java    From Insights with Apache License 2.0 4 votes vote down vote up
@Override
public void closeSession(Session session) {
	if(session != null && session.isOpen()) {
		session.close();
	}
}
 
Example 19
Source File: LuceneSearcher.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public void index(boolean overWrite) throws IOException {

        if (!overWrite && new File(path).exists())
            return;

        Directory dir = FSDirectory.open(Paths.get(path));
        Analyzer analyzer = new EnglishAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(OpenMode.CREATE);
        IndexWriter writer = new IndexWriter(dir, iwc);

        Session session = context.connection.session();
        String stat = "match (n) where exists(n." + TextExtractor.IS_TEXT + ") and n." + TextExtractor.IS_TEXT + "=true return id(n), labels(n)[0], n." + TextExtractor.TITLE + ", n." + TextExtractor.TEXT;
        StatementResult rs = session.run(stat);
        int c=0;
        while (rs.hasNext()) {
            Record item = rs.next();
            String label=item.get("labels(n)[0]").asString();
            if (!(label.equals(StackOverflowExtractor.QUESTION)||label.equals(StackOverflowExtractor.ANSWER)||label.equals(JiraExtractor.ISSUE)))
                continue;
            String org_content = item.get("n." + TextExtractor.TEXT).asString();
            String title = item.get("n." + TextExtractor.TITLE).asString();
            String content = dealWithDocument("<html><title>" + title + "</title>" + org_content + "</html>");
            if (content.length() > 0) {
                Document document = new Document();
                long id=item.get("id(n)").asLong();
                document.add(new StringField("id", "" + id, Field.Store.YES));
                document.add(new StringField("type", item.get("labels(n)[0]").asString(), Field.Store.YES));
                document.add(new StringField("title", title, Field.Store.YES));
                document.add(new TextField("content", content, Field.Store.YES));
                document.add(new TextField("org_content", org_content, Field.Store.YES));
                Set<Long> nodes=new HashSet<>();
                Session session1=context.connection.session();
                StatementResult rs1=session1.run("match (a)-[:"+ ApiMentionExtractor.API_NAME_MENTION+"|"+ ReferenceExtractor.REFERENCE+"]->(b) where id(a)="+id+" and exists(b."+ LINEExtractor.LINE_VEC+") return distinct id(b)");
                while (rs1.hasNext()){
                    Record item1=rs1.next();
                    nodes.add(item1.get("id(b)").asLong());
                }
                session1.close();
                String nodeSet = StringUtils.join(nodes, " ").trim();
                document.add(new StringField("node_set", nodeSet, Field.Store.YES));
                writer.addDocument(document);
                System.out.println(c+": "+nodes.size());
                c++;
            }
        }
        session.close();

        writer.close();
    }
 
Example 20
Source File: ApiLocator.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public SubGraph queryExpand(String queryString) {
    SubGraph r = new SubGraph();
    SubGraph searchResult1 = query(queryString);
    r.nodes.addAll(searchResult1.nodes);
    r.cost = searchResult1.cost;

    Set<Long> selected = new HashSet<>();
    selected.add(r.nodes.iterator().next());
    int rootCount = searchResult1.nodes.size() - 1;

    while(rootCount-- > 0){
        int minStep = Integer.MAX_VALUE;
        long candidate = 0;
        SubGraph path = null;
        for (long seed1 : selected){
            for (long seed2: searchResult1.nodes){
                if (selected.contains(seed2))
                    continue;
                SubGraph currentPath = new SubGraph();
                Session session = context.connection.session();
                String stat = "match p=shortestPath((n1)-[:" + codeRels + "*..10]-(n2)) where id(n1)=" + seed1 + " and id(n2)=" + seed2
                        + " unwind relationships(p) as r return id(startNode(r)), id(endNode(r)), id(r)";
                StatementResult rs = session.run(stat);
                while (rs.hasNext()) {
                    Record item=rs.next();
                    long node1 = item.get("id(startNode(r))").asLong();
                    long node2 = item.get("id(endNode(r))").asLong();
                    long rel = item.get("id(r)").asLong();
                    currentPath.nodes.add(node1);
                    currentPath.nodes.add(node2);
                    currentPath.edges.add(rel);
                }
                session.close(); // may have no path
                if (currentPath.edges.size() > 0 && currentPath.edges.size() < minStep){
                    minStep = currentPath.edges.size();
                    path = currentPath;
                    candidate = seed2;
                }
            }

        }
        if (path == null) // cannot expand to other nodes
            break;
        selected.add(candidate);
        r.nodes.addAll(path.nodes);
        r.edges.addAll(path.edges);
    }
    if(debug)
        System.out.println("expanded graph size: " + r.nodes.size()+"\n");
    return r;
}