CypherCode:LineReader

From PRGs Wiki
Revision as of 14:03, 7 December 2017 by Phil (talk | contribs) (Created page with "This is a really simple project that loads data from a file and put it into a Neo4J data. It assumes that each line of the file is an individual cypher command. Its great for...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This is a really simple project that loads data from a file and put it into a Neo4J data. It assumes that each line of the file is an individual cypher command. Its great for building a network offline in a text file, and then you can simply run the program and it will put the data in neo4j.

Obviously you need to provide it with the server address, and a username/password if needed. It just runs so make sure you don't send all the data to the wrong place!

package net.prgarnett.cypherlinereader;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;

/**
 *
 * @author philip
 */
public class LineReader {
    
    private final Driver driver;
    
    /**
     * Load up the driver, using the address, pword, and username.
     * 
     * @param serveradd
     * @param password
     * @param username 
     */
    public LineReader(String serveradd, String password, String username)
    {
        this.driver = GraphDatabase.driver(serveradd, AuthTokens.basic(username, password));
    }
    
    /**
     * Give the method the path to the file, it will read any line that does not
     * start with a '#'.
     * 
     * @param path 
     */
    public void ExecuteLines(String path)
    {
        try{
            File targetFile = new File(path);
        
            try(Session session = driver.session())
            {
                Scanner lineScanner = new Scanner(targetFile);
                while(lineScanner.hasNext())
                {
                    String line = lineScanner.nextLine();
                    if(!line.startsWith("#"))
                    {
                        this.processLine(line, session);
                    }
                }
            }
        }
        catch (FileNotFoundException e)
        {
            System.err.println(e.getMessage());
        }
    }
    
    /**
     * Private method that processes the line in a transaction, requires the
     * session to be past.
     * 
     * @param line
     * @param session 
     */
    private void processLine(String line, Session session)
    {
        try (Transaction tx = session.beginTransaction())
        {
            tx.run(line);
            tx.success();
        }
    }
}