After add second servlet I am getting Exception:
java.lang.abstractmethoderror: receiver class com.sun.jersey.core.spi.factory.responseimpl does not define or inherit an implementation of the resolved method abstract getstatusinfo()ljavax/ws/rs/core/response$statustype; of abstract class javax.ws.rs.core.response.
I figure out that the problem is in dependencies in my pom.xml but I don't have any idea where.
Anyway, I gonna forward you some codes.
First, my servlets
package vs.api.serlvets;
import com.sun.jersey.api.NotFoundException;
import vs.api.database.UserDBO;
import vs.api.repository.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
#WebServlet(name = "LogInServlet", urlPatterns = { "/LogInUser"})
public class LogInServlet extends HttpServlet
{
main.java.vs.api.database.DatabaseManager databaseManager;
UserDBO userDBO;
HttpSession session;
public void init() throws ServletException
{
databaseManager = new main.java.vs.api.database.DatabaseManager();
try
{
userDBO = new UserDBO(databaseManager.dataSource.getConnection());
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
session = request.getSession();
session.removeAttribute("errorLogIn");
PrintWriter out = response.getWriter();
String email = "";
String password = "";
User user = new User();
try
{
email = request.getParameter("inputEmail");
password = request.getParameter("inputPassword");
user = userDBO.get(email, password);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NotFoundException e)
{
session.setAttribute("errorLogIn", e.getMessage());
response.sendRedirect(request.getHeader("Referer"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("User: " + user.getName());
}
#Override
public void destroy()
{
userDBO.exit();
}
}
package vs.api.serlvets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.jersey.api.NotFoundException;
import main.java.vs.api.database.DatabaseManager;
import vs.api.database.IDBO;
import vs.api.database.UserDBO;
import vs.api.repository.User;
#WebServlet(description = "RegistrationServlet", urlPatterns = { "/RegisterUser"})
public class RegisterUserServlet extends HttpServlet
{
DatabaseManager databaseManager;
IDBO userDBO;
public RegisterUserServlet()
{
super();
}
public void init() throws ServletException
{
databaseManager = new DatabaseManager();
try
{
userDBO = new UserDBO(databaseManager.dataSource.getConnection());
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
User user = new User();
user.setName(request.getParameter("inputFirstName"));
user.setSurname(request.getParameter("inputLastName"));
user.setEmail(request.getParameter("inputEmail"));
user.setPassword(request.getParameter("inputPassword"));
try
{
userDBO.add(user);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
HttpSession session = request.getSession();
session.setAttribute("errorUserExist", e.getMessage());
response.sendRedirect(request.getHeader("Referer"));
}
catch(AbstractMethodError e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void destroy()
{
userDBO.exit();
}
}
And second my 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>com.drimtim</groupId>
<artifactId>virtualspace</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>virtualspace Maven Webapp</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>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
<build>
<finalName>virtualspace</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.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>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
In end, my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Registration User Servlet</servlet-name>
<servlet-class>vs.api.serlvets.RegisterUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration User Servlet</servlet-name>
<url-pattern>/RegisterUser</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogIn User Servlet</servlet-name>
<servlet-class>vs.api.serlvets.RegisterUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogIn User Servlet</servlet-name>
<url-pattern>/LogInUser</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/AppExceptionHandler</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/AppExceptionHandler</location>
</error-page>
</web-app>
This is my all pom.xml Could you say me where is problem ?
Thanks in advance.
First you need to remove unnecessary dependencies for that you can use maven.
Execute below commands by opening terminal in your project root directory.
mvn clean
mvn dependency:analyze
It will show you the unused and required dependencies.
Also you can try by changing your pom. i think you only need following dependencies.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
Related
I have problem with my application. I added uploading image page but i get problem.
enter image description here
Before my project work corretly. I can login in test1 be user and test3. Admin can log test2 and test3, but when i add uploadImage and i wanna log be Admin i get whitelabel, if i change this for user i get this same problem. I think this should be problem with mapping or scaning, my structure maybe is not correctly but idk because i dont have enough experience. Lower i add my code, if someone need more code, ask.
My uploadImage:
package com.example.imageUploader.gui;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.imageUploader.ImageUploader;
import org.springframework.web.bind.annotation.GetMapping;
import java.awt.*;
// problem moze byc z mapowaniem albo zaleznosciami miedzy folderami ze ten jest za wysoko
#Route("uploadImage")
public class UploadGui extends VerticalLayout
{
private ImageUploader imageUploader;
#Autowired
public UploadGui(ImageUploader imageUploader)
{
this.imageUploader = imageUploader;
TextField textField = new TextField();
Button button = new Button("upload");
button.addClickListener(clickEvent -> imageUploader.uploadFile(textField.getValue()));
add(textField);
add(button);
}
}
My run:
package com.example.imageUploader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#SpringBootApplication
//#ComponentScan(basePackages = "com.example.imageUploader.gui.UploadGui")
public class ImageUploaderApplication {
public static void main(String[] args) {
SpringApplication.run(ImageUploaderApplication.class, args);
}
}
My logging:
package com.example.imageUploader;
import com.example.imageUploader.model.AppUser;
import com.example.imageUploader.repo.AppUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
private UserDetailsServiceImpl userDetailsService;
private AppUserRepo appUserRepo;
#Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AppUserRepo appUserRepo) {
this.userDetailsService = userDetailsService;
this.appUserRepo = appUserRepo;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.antMatchers("/test1").hasRole("USER")
.antMatchers("/test2").hasRole("ADMIN")
.antMatchers("/uploadImage").hasRole("ADMIN")
.and()
.formLogin().permitAll();
}
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
#EventListener(ApplicationReadyEvent.class)
public void get()
{
AppUser appUserUser = new AppUser("User", passwordEncoder().encode("haslo123"), "ROLE_USER");
AppUser appUserAdmin = new AppUser("Admin", passwordEncoder().encode("haslo123"), "ROLE_ADMIN");
appUserRepo.save(appUserUser);
appUserRepo.save(appUserAdmin);
}
}
My 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.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>imageUploader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>imageUploader</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<vaadin.version>23.1.4</vaadin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-http44</artifactId>
<version>1.22.1</version>
</dependency>
<dependency>
<groupId>com.cloudinary</groupId>
<artifactId>cloudinary-taglib</artifactId>
<version>1.0.14</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Screen of my structure:
enter image description here
Ok, problem solved. I put this part of my pom.xml in the comment and resolve problem.
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<id>frontend</id>
<phase>compile</phase>
<goals>
<goal>prepare-frontend</goal>
<goal>build-frontend</goal>
</goals>
<configuration>
<productionMode>true</productionMode>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
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.
I am trying to run a webapp called TestServer2 in the Tomcat 7 running Ubuntu 14.04 but it gave failed as FAIL - Application at context path /TestServer2-0.0.1-SNAPSHOT could not be started. I followed an example online here and I tested it on my local Tomcat server instance running with Eclipse and it works just fine but when I deployed it into the server Ubuntu 14.04 with Tomcat 7 it gave me that error. Below are the codes I used:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>TestServer2</display-name>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.heyho.rest.JSONService</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<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>TestServer2</groupId>
<artifactId>TestServer2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<!-- <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version> </dependency> -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
JSONService.java
package com.heyho.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/service")
public class JSONService {
#POST
#Path("/post")
#Consumes("application/json")
public Response createProductInJSON(UserInput input) {
String result = "User input submitted : " + input;
return Response.status(201).entity(result).build();
}
}
UserInput.java
package com.heyho.rest;
public class UserInput {
int counter;
String attribute;
String publicKey;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
#Override
public String toString() {
return "User Input = counter " + counter + " attribute = " + attribute + " public key = " + publicKey ;
}
}
ClientPost.java
package com.heyho.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.gson.Gson;
public class ClientPost {
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CloseableHttpClient client = HttpClients.custom()
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpPost postRequest = new HttpPost(
"http://somewebsite.de:50064/TestServer2/service/post");
Gson gson = new Gson();
Map<String,Object> test = new HashMap<String,Object>();
test.put("counter", 1000);
test.put("attribute", "user attribute");
test.put("publicKey", "user public key");
String json = gson.toJson(test);
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is there something wrong with my code? Also how do I debug the Tomcat 7 running on the server so that it could give me some logs or error?
UPDATE
I have found the error in log something like this:
SEVERE: Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.UnsupportedClassVersionError: com/heyho/rest/JSONService : Unsupported major.minor version 52.0 (unable to load class com.heyho.rest.JSONService)
I'm not sure what is the problem here. I have declared JSONService on my web.xml but it still gives me error
"Unsupported major.minor version 52.0" means that the class com.heyho.rest.JSONService has been compiled for a newer version of Java as you try to run it with. Upgrade the JVM to 1.8 and it should work. Alternatively, you can make sure to compile the class for the version of the JVM.
it is my first post here, till now I finally always found the solution for my dev problem, but now I am really exchausted. Maybe you can help me.
I am trying to setup simple Rest get web app basing on vaadin + spring boot +
maven on tomcat. In some combinations in .pom i received the get response : "sth else" but in such case the vaadin ui wasnt loaded. In such configuration I paste below I cannot obtain the get response:
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>com.drzinks</groupId>
<artifactId>site</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Site</name>
<description>CRUD Vaadin Spring App</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<vaadin.version>7.7.3</vaadin.version>
<vaadin.plugin.version>7.7.3</vaadin.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!-- in order to have hot deploy in tomcat -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>7.7.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
web.xml:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Servlet declaration can be omitted in which case
it would be automatically added by Jersey -->
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
WelcomeController.java:
package com.drzinks;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.stereotype.Component;
#Component
#Path("/sth")
public class WelcomeController {
#GET
#Produces("text/plain")
public String getSthElse(){
return "sth elese";
}
}
SiteApplication:
package com.drzinks;
import javax.ws.rs.ApplicationPath;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SiteApplication {
public static void main(String[] args) {
SpringApplication.run(SiteApplication.class, args);
}
}
SiteUI.java:
package com.drzinks;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SpringUI
#Theme("valo")
public class SiteUI extends UI {
#Autowired
private RestClient restClient;
private VerticalLayout layout;
#Override
protected void init(VaadinRequest request) {
setupLayout();
addHeader();
}
private void setupLayout() {
layout = new VerticalLayout(); //alt shift l extr local var
setContent(layout);
}
private void addHeader() {
// Label label1 = new Label(welcomeController.returnSth());
// layout.addComponent(label1);
Label label2 = new Label(restClient.getSthFromServer());
// Label label2 = new Label("restClient.getSthFromServer()");
layout.addComponent(label2);
}
}
RestClient.java:
package com.drzinks;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
import com.vaadin.spring.annotation.UIScope;
#UIScope
#Component
public class RestClient {
private Client client = ClientBuilder.newClient();
private WebTarget webtarget = client.target("http://localhost:8080");
public String getSthFromServer() {
String response;
response = webtarget.path("sth")
.request().get(String.class);
return response;
}
}
folder_structure
If anyone could help, I would be very appreciated as I spent on this more than 12 hrs, breaking all night..
I've got a strange problem when using AspectJ, Neo4j NodeEntities and transactions.
I'm developing a spring application and using spring-data-neo4j with aspectj weaving. The problem is, that my fetched entities are empty outside of the transaction. Without AspectJ everything works as expected.
Here is a full test-case with maven:
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>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<neo4j.version>2.1.7</neo4j.version>
<spring-data-commons.version>1.10.0.RELEASE</spring-data-commons.version>
<spring-data-neo4j.version>3.3.0.RELEASE</spring-data-neo4j.version>
</properties>
<dependencies>
<!-- spring dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data-commons.version}</version>
</dependency>
<!-- spring + neo4j dependencies -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-tx</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
<version>${spring-data-neo4j.version}</version>
</dependency>
<!-- for aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-kernel</artifactId>
<version>${neo4j.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>aspects</id>
<build>
<plugins>
<!-- disable default compiler -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<!-- enable aspectj compiler -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
<aspectLibrary>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<complianceLevel>${java.version}</complianceLevel>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<name>Spring Milestone</name>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>
</project>
demo/DemoNode.java
package demo;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class DemoNode {
#GraphId
private Long id;
#Indexed(unique = true)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
demo/DemoRepository.java
package demo;
import org.springframework.data.neo4j.repository.GraphRepository;
public interface DemoRepository extends GraphRepository<DemoNode> {
public DemoNode findByName(String name);
}
demo/DemoApplicationTests.java
package demo;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.aspects.config.Neo4jAspectConfiguration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.node.Neo4jHelper;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DemoApplicationTests {
#Configuration
#ComponentScan("demo")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "demo")
public static class DemoConfiguration extends Neo4jAspectConfiguration {
public DemoConfiguration() {
setBasePackage("demo");
}
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
}
#Autowired
private GraphDatabaseService graphDbService;
#Autowired
private DemoRepository demoRepo;
#Before
public void resetDb() {
Neo4jHelper.cleanDb(graphDbService);
}
// NOT successful
#Test
public void testNeo4jTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
assertEquals(name, node.getName()); // expected:<demo> but was:<null>
}
// successful
#Test
public void testNeo4jWithGetTransaction() {
DemoNode node;
final String name = "demo";
try (Transaction tx = graphDbService.beginTx()) {
node = new DemoNode();
node.setName(name);
node = demoRepo.save(node);
tx.success();
}
assertEquals(name, node.getName());
try (Transaction tx = graphDbService.beginTx()) {
node = demoRepo.findByName(name);
tx.success();
}
try (Transaction tx = graphDbService.beginTx()) {
assertEquals(name, node.getName());
}
}
}
When you test this with mvn test everything is fine. But when using aspectj (mvn test -Paspects) it will fail:
DemoApplicationTests.testNeo4jNativeTransaction:64 expected:<demo> but was:<null>
What I found out when debugging this: Inside the transaction with AspectJ I could retrieve the name with the getter. BUT: All properties are always null. So my guess is: AspectJ weaving stores the values somewhere else and overrides the setter/getter for this. The new getter requires an active transaction, so outside of the transaction it will not work/will use the default getter that doesn't work with the null properties.
When I'm increasing the debug level I could see some message regarding this:
DEBUG o.s.d.n.f.DetachedEntityState - Outside of transaction, GET value from field class java.lang.String name rel: false idx: true
Am I doing something wrong? Do I need to create a clone and return this? Imho this would be an ugly way ...
Thanks in advance! I'm already searched and tried multiple hours but couldn't find any solution and any other problems here on stackoverflow or somewhere else in the internet. Maybe it's a bug ... maybe expected behaviour or maybe I'm doing some wrong ... I don't know.
UPDATE
I added a second test that works. It has a transaction around the getter. So when the getter is called in a transaction everything is fine. But I think this is a curious behaviour. Outside of the transaction the entity should be detached, but usable.