Using Java ServiceLoader results NoSuchElementException error - java

My class DoFindMiddleService extends the abstract class DoFindMiddle.
Here is the DoFindMiddle class:
public abstract class DoFindMiddle<T extends Comparable<T>> {
public abstract ListItem<T> findMiddle(ListItem<T> paramListItem);
public static <D extends Comparable<D>> DoFindMiddle<D> newInstance() {
return (DoFindMiddle)ServiceLoader.load(DoFindMiddle.class).iterator().next();
}
}
Here is the first part of DoFindMiddleService class:
package com.nng.interview.homework.applicant.kovacskalman;
import com.nng.interview.homework.exercise.DoFindMiddle;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
public class DoFindMiddleService<T extends Comparable<T>> extends DoFindMiddle<T> {
public static DoFindMiddle service;
public volatile ServiceLoader<DoFindMiddleService> loader;
public DoFindMiddleService() {
loader = ServiceLoader.load(DoFindMiddleService.class);
}
public static synchronized DoFindMiddle getInstance() {
if (service == null) {
service = new DoFindMiddleService();
}
return service;
}
public String getDefinition(String word) {
String definition = null;
try {
Iterator<DoFindMiddleService> dictionaries = loader.iterator();
while (definition == null && dictionaries.hasNext()) {
DoFindMiddleService d = dictionaries.next();
definition = d.getDefinition(word);
}
} catch (ServiceConfigurationError serviceError) {
definition = null;
serviceError.printStackTrace();
}
return definition;
}
.....
}
If I try the following in the Unit test:
final DoFindMiddle<Integer> instance = new DoFindMiddleService();
Then it is working. But when I try in the Unit test:
final DoFindMiddle<Integer> instance = DoFindMiddle.newInstance();
Then it results NoSuchElementException error.
What can be my fault?
My pom.xml is the following:
<?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>com.nng.interview.homework.applicant</groupId>
<name>Kovács Kálmán</name>
<artifactId>kovacskalman</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.nng.interview.homework</groupId>
<artifactId>comnnginterviewhomework</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>
When I try to execute I got this error:
d:\kovacskalman>mvn exec:java -Dexec.mainClass="com.nng.interview.homework.appli
cant.kovacskalman.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Kovacs Kalman 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.3.2:java (default-cli) # kovacskalman ---
[WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment
on MEXEC-6.
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.util.NoSuchElementException
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:357)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at com.nng.interview.homework.exercise.DoFindMiddle.newInstance(DoFindMi
ddle.java:52)
at com.nng.interview.homework.applicant.kovacskalman.App.<init>(App.java
:9)
at com.nng.interview.homework.applicant.kovacskalman.App.main(App.java:1
3)
... 6 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.076 s
[INFO] Finished at: 2014-11-01T15:19:51+01:00
[INFO] Final Memory: 9M/96M

I have to put inside the jar META-INF/services/com.nng.interview.homework.exercise.DoFindMiddle
named file, which contains only one row:
com.nng.interview.homework.applicant.kovacskalman.DoFindMiddleService # Standard service provider
Let see the Jar file specification Service Provider part:
https://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Service_Provider

According to the javadoc, iterator() does that :
 Lazily loads the available providers of this loader's service.
According to your exception, the iterator is empty, that means no implementation has been found.
Is DoFindMiddleService in your classpath ?

Related

Pushing Spring boot app to heroku not completed

when I'm deploying my simple project to Heroku I'm getting a maven-plugin error
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
my code is very simple it's one entity class and restController class, when I run my project on my pc it working but the deployment failed.
my class
package com.hosting.hostingTest;
public class BucketList {
private long id;
private String name;
public BucketList(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
my rest controller
package com.hosting.hostingTest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class BucketListController {
private List<BucketList> myBucketList = new ArrayList<>();
private final AtomicLong counter = new AtomicLong();
public BucketListController(){
myBucketList.add(new BucketList(counter.incrementAndGet(), "Visit Colosseum in Rome"));
}
#GetMapping(value = "/")
public ResponseEntity index() {
return ResponseEntity.ok(myBucketList);
}
#GetMapping(value = "/bucket")
public ResponseEntity getBucket(#RequestParam(value="id") Long id) {
BucketList itemToReturn = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToReturn = bucket;
}
if(itemToReturn == null){
return ResponseEntity.ok("No bucket found with id " + id);
}else {
return ResponseEntity.ok(itemToReturn);
}
}
#PostMapping(value = "/")
public ResponseEntity addToBucketList(#RequestParam(value="name") String name) {
myBucketList.add(new BucketList(counter.incrementAndGet(), name));
return ResponseEntity.ok(myBucketList);
}
#PutMapping(value = "/")
public ResponseEntity updateBucketList(#RequestParam(value="name") String name, #RequestParam(value="id") Long id) {
myBucketList.forEach(bucketList -> {
if(bucketList.getId() == id){
bucketList.setName(name);
}
});
return ResponseEntity.ok(myBucketList);
}
#DeleteMapping(value = "/")
public ResponseEntity removeBucketList(#RequestParam(value="id") Long id) {
BucketList itemToRemove = null;
for(BucketList bucket : myBucketList){
if(bucket.getId() == id)
itemToRemove = bucket;
}
myBucketList.remove(itemToRemove);
return ResponseEntity.ok(myBucketList);
}
}
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hosting</groupId>
<artifactId>hostingTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hostingTest</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
the error :
[INFO] Compiling 3 source files to /tmp/build_a3c8365b/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.228 s
[INFO] Finished at: 2020-08-12T12:41:17Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project hostingTest: Compilation failure -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
! ERROR: Failed to build app with Maven
We're sorry this build is failing! If you can't find the issue in application code,
please submit a ticket so we can help: https://help.heroku.com/
! Push rejected, failed to compile Java app.
! Push failed

import org.neo4j cannot be resolved?

I am very new to Neo4j and I'd like to get started with an embedded Neo4j in a Java Application. I try to run a HelloWorld Application as follows.
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import org.neo4j.driver.Result;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.TransactionWork;
import static org.neo4j.driver.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
#Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
#Override
public String execute( Transaction tx )
{
Result result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
The Pom code is as follows.
<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>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>4.0.1</version>
<name>neo4jtest</name>
<build>
<plugins>
<plugin>
<groupId>1</groupId>
<artifactId>2</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-core</artifactId>
<version>3.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-bolt-driver</artifactId>
<version>3.1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Unfortunately I cannot run the code it raises "Exception in thread "main" java.lang.Error: Unresolved compilation problem: at HelloWorldExample.main(HelloWorldExample.java:46)". Additionally, when hovering over the import lines I see "import org.neo4j cannot be resolved".
Can somebody provide information about this?
As documented, in order to use neo4j's Java driver, you need to specify the appropriate dependency:
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>x.y.z</version>
</dependency>
The latest release version is 4.0.1.
[UPDATE]
Also, your pom.xml file has a lot of other issues. Try something like this instead:
<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>com.example</groupId>
<artifactId>helloworld</artifactId>
<version>1</version>
<name>neo4jtest</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
</project>
This example POM file uses some dummy groupId, artifactId, and version values for itself (near the top). You should replace them with your own values (not values belonging to neo4j).

The type com.google.cloud.ServiceOptions$Builder cannot be resolved. It is indirectly referenced from required .class files

Here I am trying to insert CSV data into bigQuery table, I already configured google-cloud-bigquery-1.93.0.jar file in eclipse. But I am getting error for "com.google.cloud.ServiceOptions$Builder". see below code which I am using.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.cloud.bigquery.InsertAllResponse;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.InsertAllRequest;
import com.google.cloud.bigquery.InsertAllResponse;
import com.google.cloud.bigquery.TableId;
public class InsertData {
public static void uploaddata(String datasetname) throws IOException {
BigQuery bigquery = BigQueryOptions
.getDefaultInstance()
.toBuilder()
.setProjectId("my-project-id")
.build()
.getService();
TableId tableIdor = TableId.of(datasetname, "table_name");
String csvFile = "D:/my-file/my.csv";
BufferedReader br = null;
FileReader myFile = null;
String line = "";
String cvsSplitBy = ",";
String[] beschriftung = null;
int i = 0;
Map<String, Object> rowContent = new HashMap<>();
myFile = new FileReader(csvFile);
br = new BufferedReader(myFile);
// read CSV file line by line and upload it into BigQuery
while ((line = br.readLine()) != null) {
// get the name of the fields from the first row of the CSV File
if (i == 0) {
beschriftung = line.split(cvsSplitBy);
i = i + 1;
for (int e = 0; e < beschriftung.length; e++) {
rowContent.put(beschriftung[e], "init");
}
} else
// Format Data for BigQuery and upload the row
{
String[] Zeile = line.split(cvsSplitBy);
for (int e = 0; e < Zeile.length; e++) {
rowContent.put(beschriftung[e], Zeile[e]);
}
i = i + 1;
}
InsertAllResponse response = bigquery
.insertAll(InsertAllRequest
.newBuilder(tableIdor)
.addRow(String.valueOf(i), rowContent)
.build());
if (response.hasErrors()) {
System.out.println(response.getErrorsFor(0));
}
}
br.close();
myFile.close();
}
}
I am getting syntax error in below lines.
BigQuery bigquery = BigQueryOptions
.getDefaultInstance()
.toBuilder()
.setProjectId("my-project-id")
Error notification is -
The type com.google.cloud.ServiceOptions$Builder cannot be resolved. It is indirectly referenced from required .class files
=======
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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>insertdata</groupId>
<artifactId>insertdata</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>insertdata</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-bigquery</artifactId>
<version>1.93.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core</artifactId>
<version>1.90.0</version>
</dependency>
</dependencies>
</project>
Now I am getting below error -
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/cloud/bigquery/BigQueryOptions
at insertdata.insertdata.InsertDataBigQuery.uploaddata(InsertDataBigQuery.java:24)
at insertdata.insertdata.InsertDataBigQuery.main(InsertDataBigQuery.java:78)
Caused by: java.lang.ClassNotFoundException:
com.google.cloud.bigquery.BigQueryOptions
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 2 more
What would be the solution, Thanks in advance.
In addition to google-cloud-bigquery-1.93.0.jar, you have to also configure at least google-cloud-core-1.90.0.jar in Eclipse.
BigQueryOptions.getDefaultInstance().toBuilder() returns BigQueryOptions.Builder that extends the missing ServiceOptions.Builder. This is why you get the error.
For all by Google Cloud BigQuery 1.93.0 required dependencies which may require additional dependencies themselves, see section Compile Dependencies in Maven Repository - Google Cloud BigQuery 1.93.0.
Alternatively, you could use a build tool like Maven or Gradle, which will automatically download all necessary dependencies and configure them in Eclipse.
<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>insertdata</groupId>
<artifactId>insertdata</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>insertdata</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-bigquery</artifactId>
<version>1.93.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core</artifactId>
<version>1.90.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

"Exception in thread "mainHow to resolve this exception: " java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy..."

I'm trying to connect a local database to my application using hibernate. I'm getting the following error:
Jul 02, 2019 9:20:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {[WORKING]}
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:345)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:337)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.cfg.Environment.<clinit>(Environment.java:230)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:78)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:67)
at org.hibernate.orm.core#5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:58)
at ProjectDBTest/ProjectDBTest2.HibernateUtil.getSessionFactory(HibernateUtil.java:28)
at ProjectDBTest/ProjectDBTest2.App.main(App.java:28)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.NamingStrategy$SuffixingRandom$BaseNameResolver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 8 more
Any help on how to resolve this would be greatly appreciated.
Initially, I was getting 'java.lang.NoClassDefFoundError: java/sql/SQLException' exception and so I added 'requires java.sql' after seeing this as a suggested solution elsewhere on Stack Overflow, but now a the exception described above arises. I'm not sure where I'm gone wrong in my code or what is missing.
Here is my module-info.java file:
module ProjectDBTest {
requires java.persistence;
//requires lombok;
requires javafx.graphics;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
exports ProjectDBTest2.DB;
}
main class:
package ProjectDBTest2;
import ProjectDBTest2.DB.Vocabulary;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Vocabulary word1 = new Vocabulary();
word1.setUnitID(1);
word1.setWord("test");
word1.setVocabClass("noun");
word1.setVocabDefinition("this is a test");
word1.setVocabID(7);
System.out.println(word1.getUnitID());
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(word1);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
List< Vocabulary > students = session.createQuery("from Vocabulary ", Vocabulary.class).list();
students.forEach(s -> System.out.println(s.getWord()));
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
Hibernate util file:
package ProjectDBTest2;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry
registry = new StandardServiceRegistryBuilder().configure().build();
// Create MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
Persistence data class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//#Data
#Entity
#Table(name = "vocabulary")
public class Vocabulary {
#Id
#Column(name = "V_ID")
private int vocabID;
#Column(name = "V_WORD")
private String word;
#Column(name = "V_CLASS")
private String vocabClass;
#Column(name = "V_DEFINITION")
private String vocabDefinition;
#Column(name = "U_ID")
private int unitID;
public int getVocabID() {
return vocabID;
}
public void setVocabID(int vocabID) {
this.vocabID = vocabID;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getVocabClass() {
return vocabClass;
}
public void setVocabClass(String vocabClass) {
this.vocabClass = vocabClass;
}
public String getVocabDefinition() {
return vocabDefinition;
}
public void setVocabDefinition(String vocabDefinition) {
this.vocabDefinition = vocabDefinition;
}
public int getUnitID() {
return unitID;
}
public void setUnitID(int unitID) {
this.unitID = unitID;
}
}
pom.xml:
<?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>ProjectDBTest2</groupId>
<artifactId>ProjectDBTest2.0</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ProjectDBTest2.0</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-->
<!--
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>13-ea+9</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<version>13-ea+9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13-ea+9</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I'm using intelliJ ultimate 2019.1 and language level is set to 11.
I finally managed to solve the issue by updating my module-info.java file to include:
module AlienDB {
requires static lombok;
requires java.persistence;
requires org.hibernate.orm.core;
requires java.naming;
requires java.sql;
requires com.sun.xml.bind;
requires net.bytebuddy;
opens Aliens to org.hibernate.orm.core;
exports Aliens;
}
Previously I was adding java.xml.bind which was causing further issues.

neo4j in JEE (JBoss) environment:

I have built a RESTful web service for Wildfly using Neo4j OGM, but when I access it I get a NullPointerException.
It seems that a Map that should be populated with my model classes has not been initialized by the time it is accessed. Why is this happening?
Upfront I have to say that this module, salessupport-ui, is currently implemented as a fat client using javafx and it works fine connecting to the neo4j community edition 2.2.4, reading, writing, no problem.
What I would like to do now and this is where I face problems, I want to use wildfly as a server which itself connects to neo4j, thus that the javafx client application sends requests only to the wildfly server.
The protocol which I decided to use is REST, the implementation which is already kind-of provided on wildfly is resteasy.
Below are 1) the exception and some debugging info, 2) details about my context, project structure and the code for my classes.
1. Problem
Here are the exception and my findings when debugging.
Exception
Now when I call this REST service by entering http://localhost:8080/salessupport-restsvc/rest/address/list in the browser, the following exception is raised:
00:07:38,458 ERROR [io.undertow.request] (default task-5) UT005023: Exception handling request to /salessupport-restsvc/rest/address/list: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:76)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:212)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:149)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at org.neo4j.ogm.metadata.MetaData.entityType(MetaData.java:231)
at org.neo4j.ogm.session.Neo4jSession.entityType(Neo4jSession.java:451)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:55)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:94)
at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:114)
at groupid.salessupport.db.core.ApplicationContext$GraphRepositoryImpl.findAll(ApplicationContext.java:74)
at groupid.salessupport.restsvc.impl.SimpleRestGraphRepositoryImpl.findAll(SimpleRestGraphRepositoryImpl.java:29)
at groupid.salessupport.restsvc.impl.AddressRestImpl$Proxy$_$$_WeldClientProxy.findAll(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:296)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:250)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:237)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356)
... 32 more
Debugging info
By debugging I can see that it goes, as expected, to my first breakpoint in class SimpleRestGraphRepositoryImpl, method findAll() calling repository.findAll();
2nd also expected, it goes to the inner GraphRepositoryImpl class to method findAll(...) and line context.getSession().loadAll(clazz); which creates a Session.
A few steps later it tries in org.neo4j.ogm.metadata.MetaData class in method _classInfo(String,String,String) to call domainInfo.getClassInfosWithAnnotation(nodeEntityAnnotation); where nodeEntityAnnotation="org.neo4j.ogm.annotation.NodeEntity".
In the DomainInfo class method getClassInfosWithAnnotation which is then invoked the map annotationNameToClassInfo is empty. I expect it to be filled with my models, which obviously happens in the javafx environment, but not in the JavaEE env.
here is that method
public List<ClassInfo> getClassInfosWithAnnotation(String annotation) {
return annotationNameToClassInfo.get(annotation);
}
For checking, if the REST mechanism works as is I put a class next to the AddressRestImpl>
#Path("dummy")
public class DummyImpl {
#GET
#Path("list")
#Produces(MediaType.APPLICATION_JSON)
public List<Amount> getAll() {
return Arrays.asList(new Amount());
}
}
Calling this in the browser by navigating to http://localhost:8080/salessupport-restsvc/rest/dummy/list results in the expected: [{"amount":null,"currency":null}]
I have plenty of simple stuff to improve here, I have tried quite a lot of approaches, also on Tomcat 8 the same exception happens, but there the Rest approach did not work even in the dummy case so I switched to wildfly.
Did I find a bug here or is there something simply I have missed in my setup?
2) Project and Code Details
Here is information about my environment, project structure and the code I run when I have this problem.
Environment
My environment is as follows:
I have Neo4J community edition 2.2.4.
I downloaded wildfly-9.0.1.Final and, except for a management port which conflicted with my NVidia Driver Software I left everything untouched.
Project Structure
I have a maven multimodule application which consists of the following modules:
<modules>
<module>salessupport-ui</module>
<module>salessupport-intf</module>
<module>salessupport-db</module>
<module>salessupport-restsvc</module>
</modules>
The dependencies are as follows:
salessupport-intf <-- salessupport-db
^
|-- salessupport-ui
|-- salessupport-restsvc
Dependencies
Let me explain the dependencies:
salessupport parent has a dependency management definition like this:
<dependencyManagement>
<dependencies>
...
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm</artifactId>
<version>1.1.2</version>
<exclusions>
<exclusion>
<groupId>org.neo4j.app</groupId>
<artifactId>neo4j-server</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
salessupport-intf uses the following dependencies:
<dependencies>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
</dependencies>
salessupport-restsvc pom.xml is
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>groupid</groupId>
<artifactId>salessupport</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>salessupport-restsvc</artifactId>
<name>salessupport-restsvc</name>
<url>http://maven.apache.org</url>
<properties>
<jersey.version>1.19</jersey.version>
<resteasy.version>3.0.11.Final</resteasy.version>
</properties>
<dependencies>
<dependency>
<groupId>groupid</groupId>
<artifactId>salessupport-intf</artifactId>
</dependency>
<dependency>
<groupId>groupid</groupId>
<artifactId>salessupport-db</artifactId>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>${resteasy.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>${resteasy.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- webXml>src\main\webapp\WEB-INF\web.xml</webXml -->
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>
org.neo4j.server.rest.discovery,
org.neo4j.server.rest.web
</packagingExcludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Code
Here are the relevant classes.
GraphRepository interface
I defined my custom GraphRepository interface:
public interface GraphRepository<S> {
Iterable<S> findAll(Iterable<Long> nodeIds);
Iterable<S> findAll();
void delete(S arg0);
S save(S arg0);
}
Model Classes
There are some model classes, e.g.:
package groupid.salessupport.db.model;
import java.text.DecimalFormat;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
#NodeEntity(label="Amount")
public class Amount {
#GraphId Long id;
private Double amount;
private Currency currency;
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
#Override
public String toString() {
return new DecimalFormat().format(amount)+" "+currency;
}
}
and
#NodeEntity(label="Currency")
public class Currency extends BaseObject {
#Override
public String toString() {
return getName();
}
}
Generic Simple Rest Graph Repository interface
public interface ISimpleRestGraphRepository<T> {
#DELETE
#Path("delete")
#Consumes(MediaType.APPLICATION_JSON)
public void delete(T arg0);
#PUT
#Path("save")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public T save(T arg0);
#GET
#Path("list")
#Produces(MediaType.APPLICATION_JSON)
public Iterable<T> findAll();
#POST
#Path("listbyids")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Iterable<T> findAll(Iterable<Long> arg0);
}
REST Interface Definition for Amount
#Path("amount")
public interface AmountRest extends ISimpleRestGraphRepository<Amount> {
}
REST Activator
#ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}
Generic implementation of my REST Service
#RequestScoped
public class SimpleRestGraphRepositoryImpl<T> implements ISimpleRestGraphRepository<T> {
private final GraphRepository<T> repository;
public SimpleRestGraphRepositoryImpl(GraphRepository<T> repository) {
this.repository = repository;
}
#Override
public void delete(T arg0) {
repository.delete(arg0);
}
#Override
public T save(T arg0) {
return repository.save(arg0);
}
#Override
public Iterable<T> findAll() {
return repository.findAll();
}
#Override
public Iterable<T> findAll(Iterable<Long> arg0) {
return repository.findAll(arg0);
}
}
... and the specific Implementation for Address:
public class AmountRestImpl extends SimpleRestGraphRepositoryImpl<Amount> implements AmountRest {
public AmountRestImpl() {
super(NeoRepositories.getInstance().getAmountRepository());
}
}
DB Connection
in salessupport-db we connect to the database with some code:
public class ApplicationContext {
private SessionFactory sessionFactory;
private Session openSession;
public ApplicationContext() {
}
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = new SessionFactory("groupid.salessupport.db.model");
}
return sessionFactory;
}
public Session getSession() {
if (openSession == null) {
openSession = getSessionFactory().openSession("http://localhost:7474",
"username", "password"); // it is not really like this
}
return openSession;
}
public <S,G extends GraphRepository<S>> GraphRepository<S> getGraphRepository(Class<S> clazz) {
return new GraphRepositoryImpl<S>(this, clazz);
}
public static class GraphRepositoryImpl<S> implements GraphRepository<S> {
private ApplicationContext context;
private Class<S> clazz;
public GraphRepositoryImpl(ApplicationContext context, Class<S> clazz) {
this.context = context;
this.clazz = clazz;
}
#Override
public Iterable<S> findAll(Iterable<Long> nodeIds) {
List<Long> listNodeIds;
if (nodeIds instanceof List) {
listNodeIds = (List<Long>) nodeIds;
} else {
listNodeIds = new LinkedList<>();
for (Long l : nodeIds) {
listNodeIds.add(l);
}
}
return context.getSession().loadAll(clazz,listNodeIds);
}
#Override
public Iterable<S> findAll() {
return context.getSession().loadAll(clazz);
}
#Override
public void delete(S arg0) {
Session session = context.getSession();
Transaction transaction = session.beginTransaction();
context.getSession().delete(arg0);
transaction.commit();
transaction.close();
}
#Override
public S save(S arg0) {
Session session = context.getSession();
Transaction transaction = session.beginTransaction();
session.save(arg0);
transaction.commit();
transaction.close();
return arg0;
}
}
}
Usage
Implementors acquire an instance of this GraphRepository quick and dirty with a "singleton":
public class NeoRepositories {
private ApplicationContext context;
private static final NeoRepositories INSTANCE = new NeoRepositories();
private NeoRepositories() {
context = new ApplicationContext();
}
public GraphRepository<Person> getPersonRepository() {
return context.getGraphRepository(Person.class);
}
public static NeoRepositories getInstance() {
return INSTANCE;
}
public GraphRepository<Amount> getAmountRepository() {
return context.getGraphRepository(Amount.class);
}
...
}
P.S.: It is my first question on stackoverflow, I hope I wrote as little and as much as necessary to convey the problem ...
Is this #NodeEntity from Spring Data Neo4j? If yes, Spring must be setup correctly, which I cannot find here.
In https://github.com/neo4j/neo4j-ogm/issues/48 there has been an update, which has been implemented with neo4j-ogm version >2 .
I made the whole sourcecode available on https://github.com/mkirchmann/hello-neo4j-ogm , No guarantee that everything is working or all is correct, at least listing the whole nodes for one type should be possible. And don't forget to set up ogm.properties correctly.
The key for the solution is the vfs driver for neo4j-ogm, which can be found in https://github.com/mkirchmann/neo4j-ogm-resourceresolver-vfs (it has been forked from ctpconsulting, use version 2.1.1 and mvn install in order to make it available in your local maven repository)
pom.xml
The following pom.xml is setting up the necessary (maybe more, not sure), so that a Rest call can be made successfully.
<?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>de.neuenberger</groupId>
<artifactId>hello-neo4j-ogm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HelloNeo4jOgmOnWildFly</name>
<description>Very Simple configuration to use neo4j ogm on WildFly application server</description>
<packaging>war</packaging>
<properties>
<neo4jogmversion>2.1.1</neo4jogmversion>
<resteasy.version>3.1.1.Final</resteasy.version>
<version.war.plugin>3.0.0</version.war.plugin>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>${resteasy.version}</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>${resteasy.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.ctp.neo4j</groupId>
<artifactId>neo4j-ogm-resourceresolver-vfs</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-core</artifactId>
<version>${neo4jogmversion}</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-http-driver</artifactId>
<version>${neo4jogmversion}</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- webXml>src\main\webapp\WEB-INF\web.xml</webXml -->
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>
org.neo4j.server.rest.discovery,
org.neo4j.server.rest.web
</packagingExcludes>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>neo4j</id>
<name>Neo4j</name>
<url>http://m2.neo4j.org/</url>
</repository>
</repositories>
</project>
Thanks for everyones contribution and support!

Categories

Resources