Neo4j, REST API, java - cypher queries - java

I learn REST API with Java and tried run this simple code, but I got error. Something wrong with this part of code: RestAPI graphDb = new RestAPI.... I use this external JAR (http://m2.neo4j.org/content/repositories/releases/org/neo4j/neo4j-rest-graphdb/2.0.0/neo4j-rest-graphdb-2.0.0.jar)
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.rest.graphdb.RestAPI;
import org.neo4j.rest.graphdb.RestAPIFacade;
import org.neo4j.rest.graphdb.RestGraphDatabase;
import org.neo4j.rest.graphdb.query.QueryEngine;
import org.neo4j.rest.graphdb.query.RestCypherQueryEngine;
import org.neo4j.rest.graphdb.util.QueryResult;
public class CypherQuery {
public static void main(String[] args) {
RestAPI graphDb = new RestAPIFacade("http://localhost:7474/db/data/");
QueryEngine engine=new RestCypherQueryEngine(graphDb);
QueryResult<Map<String,Object>> result = engine.query("start n=node(*) return count(n) as total", Collections.EMPTY_MAP);
Iterator<Map<String, Object>> iterator=result.iterator();
if(iterator.hasNext()) {
Map<String,Object> row= iterator.next();
System.out.println("Total nodes: " + row.get("total"));
}
}
}
Error:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/ws/rs/core/Response$StatusType
at org.neo4j.rest.graphdb.RestAPIFacade.<init>(RestAPIFacade.java:295)
at cz.mendelu.bp.CypherQuery.main(CypherQuery.java:19)
Caused by: java.lang.ClassNotFoundException: javax.ws.rs.core.Response$StatusType
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more

Like #chrylis pointed out, your error seems to be the issue that you don’t have the required jars and hence the errors. Now from your comments, I see that you are having difficulties with understanding maven and dependencies. So here's a simple guide that I made for you.
[Understand that this is NOT a one stop guide and this program might
not run out of the box. Its running for me at the moment but it
depends on many things including what version of neo4j you are running
and several other configuration factors. Nonetheless, this should be sufficient to get
you started. ]
You need to have maven installed on your system. There are few cool tutorials on maven. One is here. https://www.youtube.com/watch?v=al7bRZzz4oU&list=PL92E89440B7BFD0F6
But like me if you want a faster way, the new Eclipse Luna comes with maven installed for it. So download the new eclipse luna if you wish. Even with older eclipse versions you can go to marketplace and install the maven for eclipse.
Once done, make a maven quickstart project and replace your pom.xml file with the one below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>rash.experiments</groupId>
<artifactId>neo4j</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>neo4j</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>neo4j-release-repository</id>
<name>Neo4j Maven 2 release repository</name>
<url>http://m2.neo4j.org/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-rest-graphdb</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
</project>
I assume that you have neo4j setup. I will not go into major details, but in the neo4j directory, under conf, in neo4j-server.properties file, you need to uncomment the line
org.neo4j.server.webserver.address = 0.0.0.0
This basically lets you access this server from your java code that you will run from another machine. After making this change, make sure that you restart your server and that its accessible to other machines. To test you can run http://ip.address.of.this.machine:7474 and the web portal that comes with neo4j should open up.
Note: I assume that you have some data in your database. This is
required otherwise the program will fail. If you need some sample
data, go to http://ip_address_of_your_neo4j_web_server:7474/ and load the
movie graph database that comes with the installation.
Now lets code. Make this class in the project that you created above.
package rash.experiments.neo4j;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.neo4j.rest.graphdb.RestAPI;
import org.neo4j.rest.graphdb.RestAPIFacade;
import org.neo4j.rest.graphdb.query.QueryEngine;
import org.neo4j.rest.graphdb.query.RestCypherQueryEngine;
import org.neo4j.rest.graphdb.util.QueryResult;
public class Neo4JRestTest
{
public static void main(String args[])
{
RestAPI graphDb = new RestAPIFacade("http://192.168.1.8:7474/db/data/");
QueryEngine engine = new RestCypherQueryEngine(graphDb);
QueryResult<Map<String, Object>> result = engine.query("start n=node(*) return count(n) as total", Collections.EMPTY_MAP);
Iterator<Map<String, Object>> iterator = result.iterator();
if (iterator.hasNext())
{
Map<String, Object> row = iterator.next();
System.out.print("Total nodes: " + row.get("total"));
}
}
}
Now to run, you need to build your project first because maven will not download any of your jars that your specified in pom.xml until you have run it. So if you installed maven, go to the directory where you have your pom.xml and then write in the command line mvn clean package. This command will run and install all the dependencies and then will run your program. Since there are no test cases to run, it will succeed. But our goal was not to run any test cases. It was to download all the jars. Now that you have everything, you can run the java code and you will see your end results.
In case you are using maven from eclispe, then you right click your project and then do run as -> maven build. For the first time, a dialog will appear. Just write package in it and press enter. It will do the same things as above and bring all the jars. Then execute the program like you would above.
In case you get errors such as "No endpoint" or "error reading JSON", then understand that somehow the REST API is not able to read your graph.
check the property inside neo4j-server.properties. It should be whatever you are mentioning in your URL.
org.neo4j.server.webadmin.data.uri = /db/data/

Related

cannot add spigot to build path succesfully for 1.18 plugins

I've been trying to import spigot/bukkit for minecraft plugins. When trying to create the main class, I entered
public class Main extends JavaPlugin{
}
With an error under JavaPlugin, since their is no import. The tutorial im following told me to click the fix that will import it for me, but
the fix simply does not show up when I attempt to resolve it, and if I manually import it, it gives the error: "the import org.bukkit.plugin cannot be resolved." I've tried restarting the project, deleting and reinstalling, and everything in between. Please let me know if you need more information on how I've added spigot to the build path, or anything else I can help with.
Since the 1.17, it seems to have some changes with jar. Now, if you start server, it will create the bundler/versions folder, with a given jar that -for me- should fix your issue.
Also, you can use more preferable way to import project, such as maven or gradle. They can help you to easier share the project, and make it faster to run (you can also automatically run it with github actions for example.
To use spigot with maven, use this:
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
(Documentation)
To use spigot with gradle, use this:
repositories {
maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' }
maven { url = 'https://oss.sonatype.org/content/repositories/central' }
}
dependencies {
compileOnly 'org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT'
}
(Documentation)

Executing a test on Headless (HtmlUnitDriver) mode, passes on Eclipse IDE but fails when executed in JMeter

I have a simple java-selenium-maven script written in Eclipse IDE which I have exported in a JAR file and I tried to execute from JMeter.
I have two versions of this script, one is with normal ChromeDriver and the other one is headless and it uses the HtmlUnitDriver.
Here is the second one as it is the one that misbehaves:
package testing1;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class NewTestHeadless {
#Test
public void testGoogleSearch() throws InterruptedException {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.google.com/");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();
}
#Before
public void beforeT() {
System.out.println("BEFOREEEE");
}
#After
public void afterT() {
System.out.println("AFTEERRRR");
}
}
This is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>selenium.example</groupId>
<artifactId>testing-example-selenium</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testing</name>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>4.0.0-alpha-2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<version>2.43.1</version>
</dependency>
</dependencies>
</project>
And this is the structure of my project in Eclipse IDE
Here is how i exported to JAR file
I have put this file under apache-jmeter-5.3\lib\junit and I can see correctly in JUnit Request Samplers the classes and methods from that script
When i execute in Eclipse, both test (headless + chrome) passes but when i execute from JMeter, the headless one fails
Any ideas of what might be the problem?
This is the sampler response in the Results Tree listener and the response is empty:
Thread Name:Scenario 27 - Selenium JUnit 5-1
Sample Start:2020-08-25 12:26:16 EEST
Load time:980
Connect Time:0
Latency:0
Size in bytes:0
Sent bytes:0
Headers size in bytes:0
Body size in bytes:0
Sample Count:1
Error Count:1
Data type ("text"|"bin"|""):text
Response code:1000
Response message:
SampleResult fields:
ContentType:
DataEncoding: windows-1252
You're missing one important step: your .jar file has only your code and doesn't contain htmlunit-driver, selenium-java, etc. so my expectation is that if you look into jmeter.log file you will see that JMeter cannot find Selenium-related classes.
Quick and dirty solution would be executing mvn dependency:copy-dependencies command and once it is done copy everything from target/dependencies folder of your project to the "lib" folder of your JMeter installation (or other place in JMeter Classpath)
After restart you should see your test working.
A better option would be using Maven Shade plugin for creating a "uber jar" containing everyting which is needed for running your test
And last but not the least you may find JMeter WebDriver Sampler much easier to use

Java Package doesnt not exist in intelliJ IDEA

I am new to Java and i have to execute a code snippet related to Kafka which is given below:
import java.util.*;
import org.apache.kafka.clients.producer.*;
public class Producer {
public static void main(String[] args) throws Exception
{
String topicName = "SimpleProducerTopic";
String key = "Key1";
String value = "Value-1";
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092,localhost:9093");
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer <>(props);
ProducerRecord<String, String> record = new ProducerRecord<>(topicName,key,value);
producer.send(record);
producer.close();
System.out.println("SimpleProducer Completed.");
}
}
I have downloaded IntelliJ Idea editor and running the above script there but it is giving me an error
Error:(2, 1) java: package org.apache.kafka.clients.producer does not
exist
I know that i apache kafka is missing so i downloaded a jar file of apache and add it to modules but the error still persist. What should i do? How do install the pacakge?
Simply adding the jar to the corresponding module does not give you access to it. Have you tried right click on the jar Add as Library... option?
Edit: you could perhaps explore other options for external library usage like maven, or gradle.
As being new to Java, you'll want to understand what is the classpath.
Putting JARs directly into your IDE isn't changing that
Even from the command line, you'd need to explicitly specify -cp kafka-clients.jar
There's multiple ways to modify the module classpath in Intellij, but manually downloading JARs should be avoided, and that problem is solved by dependency management tools such as Maven or Gradle (or sbt, etc)
Your profile mentions other languages, so think Nuget, npm, pip, etc. Apply that knowledge to Java
One way to install the package is to use Maven. If you want to configure Maven and IntelliJ, take a look at this tutorial. Eventually, once you are done, you should add this to the auto-generated pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Whatever you put during setup</groupId>
<artifactId>Whatever you put during setup</artifactId>
<version>1.0-SNAPSHOT</version>
//Add this - copy and paste
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
</project>
You can add any additional packages/dependencies within the <dependencies></dependencies> tags. There are plenty of tutorials online on how to handle dependencies using Maven.

JUnit 5 Disabled is ignored?

I'm using JUnit 5 with IntelliJ IDEA Community Edition version 2018.
My code is simple:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
#Disabled
#Test
void addTwoZeroNumerators(){
int[] resultExpected = {0,0};
assertArrayEquals(resultExpected, Calculator.calculate(0,0,0,1));
}
I use #Disabled. But when I run the test, the Event log still report 1 test passed. Can someone tell me what's wrong with this? I want the system to Ignore this test.
Here is the caption of the log section:
#Nicolai answer is 100% correct, IntelliJ will execute test if you force it to be executed by IntelliJ.
However, if you want to enable #Disabled annotation in build management system, remember about surefire plugin (details). If it is missing, annotation will not work.
I think this may be a bug with Maven SureFire Plugin where if you have a class with a single #Test and it's also #Disabled it still tries to run it. I've tried on maven-surefire-plugin:2.22.0, 2.22.2, and 3.0.0-M3 and all seem to have the issue.
Ticket opened with Apache Maven team:
https://issues.apache.org/jira/browse/SUREFIRE-1700?filter=-2
Tickets opened with JetBrains:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360006399720-IDEA-2019-2-2-Ultimate-Edition-ignores-Disabled-for-JUnit5-tests-having-a-single-Test-method
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360006399760-IDEA-2019-2-2-Ultimate-Edition-requires-junit-vintage-engine-for-Maven-package-using-only-JUnit5
#Tony Falabella
In the Jira I replied to you with a hint. Please use the latest snapshot version 3.0.0-SNAPSHOT and let me know about this issue. This snapshot version can be found on Apache Nexus repository. Please provide us with your feedback asap during the development of the plugin and try to use snapshot version because this avoids new issues:
<pluginRepository>
<id>surefire-snapshot</id>
<name>surefire-snapshot</name>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-SNAPSHOT</version>
</plugin>
</plugins>
</build>
In Jira I found that you use
<artifactId>junit-platform-launcher</artifactId>
Please do not use it. It is not related to you. It is related to usages by Surefire/Failsafe and IDEs only.
With JUnit 5.8.2 and maven surefire 2.22.2 I see this issue also
NB. only test methods whose name starts "test..." seem to be affected for me. If your test methods have a different name I can't reproduce the issue. Hence workaround is to rename the test method to not start "test..."

Using imported module in intellij

I'm having trouble figuring out how to actually use an imported module inside of intellij.
I'm trying to make use of maryTTS. More exactly MaryInterface. https://github.com/marytts/marytts/wiki/MaryInterface
Readme says use maven or gradle. I've never used maven, not that that means I can't, but my current project is not a maven project. Just a plain java project. Same with gradle. I'll try maven.
I started just a plain new project called test.
Then I imported the module via:
File->New->Module from existing sources.
Which left me with a module that I could not/did not know how to access. So basically two separate modules in my project.
That meaning if I use this test code:
import javax.sound.sampled.AudioInputStream;
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.util.data.audio.AudioPlayer;
public class Voice
{
private MaryInterface marytts;
private AudioPlayer ap;
public Voice(String voiceName)
{
try
{
marytts = new LocalMaryInterface();
marytts.setVoice(voiceName);
ap = new AudioPlayer();
}
catch (MaryConfigurationException ex)
{
ex.printStackTrace();
}
}
public void say(String input)
{
try
{
AudioInputStream audio = marytts.generateAudio(input);
ap.setAudio(audio);
ap.start();
}
catch (SynthesisException ex)
{
System.err.println("Error saying phrase.");
}
}
}
All of the marytts imports fail from my main module. Obviously they are fine in the marytts module.
I also tried creating a blank maven project, then adding the example code to the pom.xml . I changed the artifactId to marytts. It then just gave a path error under dependencies for files in ~/.m2 that were there.
Example here. https://github.com/marytts/marytts
<repositories>
<repository>
<id>central</id>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>de.dfki.mary</groupId>
<artifactId>marytts</artifactId>
<version>5.2</version>
</dependency>
</dependencies>
I've looked through intellj's docs. The module import seems pretty straightforward. Obviously I'm not getting part of the process or doing something wrong.
So my question then is what are the correct steps to be able to call that interface from my main module? Should I use/learn maven?
I'm not sure why this is the answer but it seems to work.
I used the exact verbage from the README but had to ad an id.
<repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>de.dfki.mary</groupId>
<artifactId>voice-cmu-slt-hsmm</artifactId>
<version>5.2</version>
</dependency>
</dependencies>
This seemed to work in as much as I can use all the import statements and create a MaryInterface.
What I do not understand is why it would not have worked this way. I just assumed I needed the marytts artifact.
http://cs.unk.edu/~mcconvilletl/?p=59

Categories

Resources