I have uploaded a CSV file and already have nodes and relationship defined on Neo4j. I've tried to create a program base on an example that basically run a cypher query from Spring that would generate the output from neo4j. However, I'm encountering this error:
Exception in thread "main" java.lang.NoSuchMethodError:org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(Ljava/io/File;)Lorg/neo4j/graphdb/GraphDatabaseService;
at org.neo4j.connection.Neo4j.run(Neo4j.java:43)
at org.neo4j.connection.Neo4j.main(Neo4j.java:37)
I'm wondering what could possibly be the error?
Here is my code:
public class Neo4j{
public enum NodeType implements Label{
Issues, Cost, Reliability, Timeliness;
}
public enum RelationType implements RelationshipType{
APPLIES_TO
}
String rows = "";
String nodeResult;
String resultString;
String columnString;
private static File DB_PATH = new File("/Users/phaml1/Documents/Neo4j/default.graphdb/import/");
public static void main(String[] args){
Neo4j test = new Neo4j();
test.run();
}
void run()
{
clear();
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
try(Transaction tx1 = db.beginTx();
Result result = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
while(result.hasNext())
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
try (Transaction something = db.beginTx();
Result result1 = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
Iterator<Node> n_column = result.columnAs("n");
for(Node node: Iterators.asIterable(n_column))
{
nodeResult = node + ": " + node.getProperties("Description");
}
List<String> columns = result.columns();
columnString = columns.toString();
resultString = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e").resultAsString();
}
db.shutdown();
}
}
private void clear(){
try{
deleteRecursively(DB_PATH);
}
catch(IOException e){
throw new RuntimeException(e);
}
}
}
It looks like a Neo4j version conflict.
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
has a String as the argument in Neo4j 2x (https://neo4j.com/api_docs/2.0.3/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase(java.lang.String))
but a File in Neo4j 3x (http://neo4j.com/docs/java-reference/current/javadocs/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase-java.io.File-)
SDN is probably pulling in Neo4j 2.3.6 as a dependency- please check your dependency tree and override the Neo4j version
Related
spring Boot project gives me No message available, null output! i know this error means i have an issue with my code but i am so new to the ontologies and TDB so please help! I am trying to bring all the individualsfrom my rdf file and store it in TDB and i can't find helpful answer!
Example.java
public class Example {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
ExampleController.java
#RestController
public class ExampleController {
File file;
Model model;
InfModel infModel;
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
Dataset dataset;
QueryExecution qe;
#RequestMapping("/getAll")
public List getAllIndiv() {
List list = new ArrayList();
try {
String directory = "tdb" ;
dataset = TDBFactory.createDataset(directory) ;
dataset.begin(ReadWrite.READ) ;
String uri ="http://example#";
model = dataset.getNamedModel(uri);
String source = "example.owl";
FileManager.get().readModel(model, source);
String a = "";
String queryString = "\r\n"
+ "PREFIX ns: <http://example#>"
+ "PREFIX rdf: <http://example-syntax-ns#>" + "SELECT ?Individuals " + "WHERE {"
+ "?Individuals rdf:type ns:Concept." + "}";
Query query = QueryFactory.create(queryString);
query.getQueryPattern();
qe = QueryExecutionFactory.create(query, dataset);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(results);
while (results.hasNext()) {
QuerySolution result = (results.next());
RDFNode ind = result.get("Individuals");
a = ind.asResource().getLocalName() + "";
list.add(a);
qe.close();
}
return list;
} catch (Exception e) {
e.printStackTrace();
}finally {
if(model != null && dataset != null) {
qe.close();
dataset.commit();
model.close();
dataset.end();
}
}
return null;
}
}
I am trying to write a Spring Boot Controller that allows the user to make arbitrary SELECT queries to a Postgres database and see the result. I implemented this by using a form like the one in the link. The project is based on this starter app.
Code:
#Controller
#SpringBootApplication
public class Main {
#Value("${spring.datasource.url}")
private String dbUrl;
#Autowired
private DataSource dataSource;
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
#GetMapping("/query")
public String queryForm(Model model) {
model.addAttribute("query", new Query());
return "query";
}
#PostMapping("/query")
public String querySubmit(#ModelAttribute Query query) {
try (final Connection connection = dataSource.getConnection()) {
final Statement stmt = connection.createStatement();
final String rawQueryContent = query.getContent().trim();
final String queryContent;
if(!rawQueryContent.toLowerCase().contains("limit")) {
queryContent = rawQueryContent + " LIMIT 500";
} else {
queryContent = rawQueryContent;
}
final ResultSet rs = stmt.executeQuery(queryContent);
final StringBuilder sb = new StringBuilder();
while (rs.next()) {
sb.append("Row #" + rs.getRow() + ": " + rs.toString() + "\n");
}
query.setContent(sb.toString());
rs.close();
stmt.closeOnCompletion();
} catch (Exception e) {
query.setContent(e.getMessage());
}
return "queryresult";
}
#Bean
public DataSource dataSource() throws SQLException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
}
}
}
The form looks like this:
But the output I am getting looks like this:
Row 1: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 2: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 3: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
Row 4: HikariProxyResultSet#188463256 wrapping org.postgresql.jdbc.PgResultSet#ff61f7d
This is not what I want! I want to see the actual rows in the database, as in:
Row 1: "Dave" | 23 | "Philadelphia"
Row 2: "Anne" | 72 | "New York"
Row 3: "Susie" | 44 | "San Francisco"
Row 4: "Alex" | 22 | "Miami"
Heck, I would rather get the raw string output that I normally get when I hand-type SQL into the database than the address in memory of the ResultSet.
How do I get the actual database output without knowing in advance exactly how many columns there will be in the table or the types of the columns?
I would suggest, for starters to simplify your code by using the JdbcTemplate combined with a ResultSetExtractor to simplify the code. You can use the ResultSet itself to get the number of columns for a result.
I'm also not sure why you are redefining the DataSource.
All in all something like the code below should do the trick (haven't tested it and typed it from the top of my head, so might need some polishing).
#Controller
#SpringBootApplication
public class Main {
#Autowired
private JdbcTemplate jdbc;
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
#GetMapping("/query")
public String queryForm(Model model) {
model.addAttribute("query", new Query());
return "query";
}
#PostMapping("/query")
public String querySubmit(#ModelAttribute Query query) {
final String rawQueryContent = query.getContent().trim();
final String queryContent;
if(!rawQueryContent.toLowerCase().contains("limit")) {
queryContent = rawQueryContent + " LIMIT 500";
} else {
queryContent = rawQueryContent;
}
String content = jdbc.query(queryContent, new ResultSetExtractor<StringBuilder>() {
public StringBuilder extractData(ResultSet rs) {
StringBuilder sb = new StringBuilder();
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
int row = rs.getRow();
sb.append(rs.getRow()).append('|');
for (int i = 1 ; i <= columns ; i++) {
sb.append(rs.getObject(i)).append('|');
}
}
return sb.toString();
}
});
query.setContent(content);
return "queryresult";
}
}
See also How to get the number of columns from a JDBC ResultSet? on how to get the number of columns.
I need to figure out how many writes MongoDB has performed in the last hour against reads.
Is there an easy way to find these stats, which are needed to create an alarm. If the solution is command driven or Java based, it will be really helpful.
after digging up source code of MongoDB jdbc driver . i finally able to get what is required . below is a code for it
public class MongoJmxStat {
private MongoClient mongo;
public MongoJmxStat(MongoClient mongo) {
this.mongo = mongo;
}
public CommandResult getServerStatus() {
CommandResult result = getDb("mongoDB").command("serverStatus");
if (!result.ok()) {
throw new MongoException("could not query for server status. Command Result = " + result);
}
return result;
}
public DB getDb(String databaseName) {
return MongoDbUtils.getDB(mongo, databaseName);
}
private int getOpCounter(String key) {
DBObject opCounters = (DBObject) getServerStatus().get("opcounters");
return (Integer) opCounters.get(key);
}
#ManagedMetric(metricType = MetricType.COUNTER, displayName = "Write operation count")
public int getWriteCount() {
return getOpCounter("insert") + getOpCounter("update") + getOpCounter("delete");
}
#ManagedMetric(metricType = MetricType.COUNTER, displayName = "Read operation count")
public int getReadCount() {
return getOpCounter("query") + getOpCounter("getmore");
}
}
I have 15 usernames with me, I need to pull worklog entries of these users and manipulate it from JAVA client
Below are the jar files am using to connect JIRA api and fetch values
The code is pasted below
public class JiraConnector {
JiraRestClient jira;
public JiraConnector() throws URISyntaxException {
String url = prop().getUrl();
String userName = prop().getUser() ;
String password = prop().getpwd() ;
JerseyJiraRestClientFactory clientFactory = new JerseyJiraRestClientFactory();
jira = clientFactory.createWithBasicHttpAuthentication(new URI(url),
userName, password);
System.out.println("Connection established to >> " + url);
}
public void printIssueDetails(String jiraNumber) {
System.out.println("JiraNumber is " + jiraNumber);
Issue issue = jira.getIssueClient().getIssue(jiraNumber, null);
System.out.println(issue.getSummary());
System.out.println(issue.getDescription());
}
public void printUserWorkLog(String userName) {
System.out.println("user details invoked ... ");
User user = jira.getUserClient().getUser(userName, null);
System.out.println(user.getDisplayName());
System.out.println(user.getEmailAddress());
}
For any given username, am able to print his displayName and emailAdress (all those basic infos).
But I need to get the list of worklogs for the given user. Not sure how to proceed
You can find all worklog records for selected issue:
List<Worklog> worklogByIssue = ComponentAccessor.getWorklogManager().getByIssue(issue);
After that you can parse all worklog records to determine for what user this record created:
for (Worklog worklogByIssueItem : worklogByIssue)
{
int timeSpent = worklogByIssueItem.getTimeSpent().intValue();
String worklogAuthorName = worklogByIssueItem.getAuthorObject().getName();
...
}
And last task is search of issues by some params:
public static List<Issue> searchIssues(SearchParametersAggregator searchParams)
{
String jqlQuery = searchParams.getJqlQuery();
String projectId = searchParams.getProjectId();
String condition = createCondition(jqlQuery, projectId);
JqlQueryBuilder jqlQueryBuilder = prepareJqlQueryBuilder(condition);
return searchIssues(jqlQueryBuilder);
}
static List<Issue> searchIssues(JqlQueryBuilder jqlQueryBuilder)
{
Query query = jqlQueryBuilder.buildQuery();
SearchService searchService = ComponentAccessor.getComponent(SearchService.class);
try
{
ApplicationUser applicationUser = ComponentAccessor.getJiraAuthenticationContext().getUser();
User user = applicationUser.getDirectoryUser();
SearchResults searchResults = searchService.search(user, query, PagerFilter.getUnlimitedFilter());
List<Issue> issues = searchResults.getIssues();
return issues;
}
catch (SearchException e)
{
LOGGER.error("Error occurs during search of issues");
e.printStackTrace();
}
return new ArrayList<Issue>();
}
static JqlQueryBuilder prepareJqlQueryBuilder(String condition)
{
try
{
Query query = jqlQueryParser.parseQuery(condition);
JqlQueryBuilder builder = JqlQueryBuilder.newBuilder(query);
return builder;
}
catch (JqlParseException e)
{
throw new RuntimeException("JqlParseException during parsing jqlQuery!");
}
}
i have problem
I'm using jelastic to host java and mongoDB app. And I have problem for the connection between my app and their mongoDB provide by Jelasctic.
Their config file look like this :
public class MongoManager {
static String host, dbname, user, password;
public void addData(int repeats) {
try {
DBCollection dbc = null;
Properties prop = new Properties();
prop.load(new FileInputStream(System.getProperty("user.home") + "/mydb.cfg"));
host = prop.getProperty("host").toString();
dbname = prop.getProperty("dbname").toString();
user = prop.getProperty("user").toString();
password = prop.getProperty("password").toString();
System.out.println("host: " + host + "\ndbname: " + dbname + "\nuser: " + user + "\npassword: " + password);
Mongo m = new Mongo(host, 27017);
DB db = m.getDB(dbname);
if (db.authenticate(user, password.toCharArray())) {
System.out.println("Connected!");
} else {
System.out.println("Connection failed");
}
try {
db.getCollection("mycollection");
} catch (Exception e) {
db.createCollection("mycollection", null);
} finally {
System.out.println("Repeats: " + repeats);
for (int i = 1; i <= repeats; i++) {
BasicDBObject data = new BasicDBObject("data", new Date());
db.getCollection("mycollection").save(data);
System.out.println("INFO: row added " + data);
}
}
} catch (IOException ex) {
}
}
and mine
public class MongodbUtil {
private static Mongo mongo = null;
private static Morphia morphia = null;
private static Datastore ds = null;
private MongodbUtil() {};
public static synchronized DB getDB(String str) throws Exception {
if(mongo == null) {
mongo = new Mongo();
}
return mongo.getDB(str);
}
public static synchronized Mongo getMongo() throws Exception {
if(mongo == null) {
mongo = new Mongo("localhost", 27017);
}
return mongo;
}
public static synchronized Morphia getMorphia() throws Exception {
if(morphia == null) {
mongo = getMongo();
morphia = new Morphia();
morphia.mapPackage("com.sogeti.simulator.entity");
}
return morphia;
}
public static synchronized Datastore getDataStore(){
if(ds == null){
try {
morphia = getMorphia();
ds = morphia.createDatastore(mongo, "Simulator");
} catch (Exception e) {
e.printStackTrace();
}
}
return ds;
}
IS that same file or not ?
How can i put in my config file properties like host ? password ? and others ?!
My MongoDB.cfg.xml looks like this but i think this is bad because i don't use SPRING OR MAVEN :
i don'T see any example of a simple MongoDB.cfg.xml in the web.
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd;">
<dependency>
<groupId>com.morphia.Morphia</groupId>
<artifactId>morphia</artifactId>
<version>0.99</version>
</dependency>
<dependency>
<groupId>com.mongodb.Mongo</groupId>
<artifactId>mongo</artifactId>
<version>2.10.1</version>
</dependency>
It seems to me that similar problem was asked at Jelastic community here.
The problem is resolved for that user, please pay your attention to the suggestions stated at that thread.